Skip to content

Instantly share code, notes, and snippets.

@MikeDigitize
Last active January 21, 2016 21:59
Show Gist options
  • Save MikeDigitize/630017ddb60a7232cca5 to your computer and use it in GitHub Desktop.
Save MikeDigitize/630017ddb60a7232cca5 to your computer and use it in GitHub Desktop.
Helpers for beginners to JavaScript at AO.com
/*
Constructor vs Literal
*/
// Array
var foo = new Array(); // constructor
var bar = []; // literal
// difference?
// constructor - inconsistent API
foo = new Array(100); // creates array with 100 undefined values
foo = new Array(1,2,3); // creates an array with three values - 1,2,3
// literal - consistent API
bar = [100]; // creates an array with one value of 100
bar = [1,2,3]; // creates an array with three values - 1,2,3
// Object
foo = new Object();
bar = {};
// literal is better because you can define properties?
bar = {
cantDoThisWithConstructor : false
};
// no, you can also with constructor, but it's more verbose and less readable
foo = new Object({
canDoThisWithConstructor : true
});
// Function
// ...don't ask
bar = new Function(["iAmArgument", "imAnother"], "return iAmArgument + ' ' + imAnother");
bar("This is", "not good"); // This is not good
// Function constructor means:
// no lexical scope
// no access to globals
// uses eval
// kill with fire
// literal is literally infinitely better in a figurative way
function foo(iAmArgument, imAnother) {
return `${iAmArgument} ${imAnother}`;
}
// RegExp
// literal
foo = /\d/;
foo.test("try1"); // true
// constructor
// extra escape needed - point dropped
bar = new RegExp("\\d");
bar.test("try1"); // true
// dynamic arguments - point gained
var foobar = "foobar";
bar = new RegExp(foobar);
bar.test("foobario"); // true
// no Date literal
// constructor only - understandable due to number of Date constructor argument variations
var date = new Date(2016, 1, 21);
// headsup: months - not day or year - is index based
// so the above is Sun Feb 21 2016 00:00:00 GMT+0000 (GMT Standard Time)
// not Sun Jan 21 2016 00:00:00 GMT+0000 (GMT Standard Time)
// consistency FTW
// strings
// constructor
foo = new String("foo");
foo; // foo is an object and inherits properties from String prototype
foo.length; // 3
// literal
bar = "bar";
bar; // is the literal value "bar" and therefore is less of a memory footprint than an object
bar.length; // but still gets co-erced into an object to access properties from String prototype! #winning
// numbers - same as string
// lesson:
// if you need dynamic regular expressions use a constructor, otherwise use a literal!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment