JS Cheat Sheet
Over a dozen reusable components built to provide iconography, dropdowns, input groups, navigation, alerts, and much more.
Over a dozen reusable components built to provide iconography, dropdowns, input groups, navigation, alerts, and much more.
array.concat(items) |
Create shallow copy of array with items added to the end. |
array.join(separator) |
|
array.pop() |
Remove (and return) last element |
array.push() |
Add elements to end, returns length |
array.reverse() |
|
array.shift() |
Remove (and return) first element |
array.unshift(item) |
Add elements to beginning, returns length |
array.slice(start, end) |
Shallow copy |
array.splice() |
Modifies original element, returns array of removed elements |
array.sort(comparator) |
comparator = function(a, b){} |
function.apply(thisArg, argArray) |
Invoke function with thisArg as the receiver |
function.bind(thisArg, argArray) |
Returns a function that has thisArg as the receiver. |
Implementing Bind http://jsbin.com/vewapaci/3/edit
Object.create(proto, propertiesObj) |
TODO! |
Object.defineProperty(obj, prop, descriptor) |
Attaches prop to obj given the property descriptor object |
Object.getOwnPropertyDescriptor(obj, name) |
name is a string |
Object.getOwnPropertyNames(obj) |
|
Object.keys() |
Returns an object's own properties |
Object.getPrototypeOf() |
Return's the argument's prototype. |
hasOwnProperty('propName') |
true if propName is a property |
propertyIsEnumerable('propName') |
|
isPrototypeOf() |
var person = {...}
var dev = Object.create(person, { propertyDescriptor }); person.isPrototypeOf(person) // true |
valueOf() |
Called when an operator is used. |
toString() |
Used as a fallback when valueOf() returns a reference value |
length
property232 - 1
elementsfruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.slice(2, 3);
//fruits = [ 'apples', 'oranges', 'banana', 'pear', 'grape' ]
//basket = [ 'banana' ]
(start, end)
, exclusive of endfruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.splice(2, 3);
//fruits = [ 'apples', 'oranges' ]
//basket = [ 'banana', 'pear', 'grape' ]
(start, count)
count
number of elements from the arraysomeArray.forEach(function(element, index, array) {
//
});
element
index
array
- the original arraystr.substr(start[, length])
length
characters from start position.
start
is negative, it counts from the right.
str.substring(indexA[, indexB])
foo(); // works
function foo() {
console.log('hi');
}
foo(); // works
foo(); // fails
foo = function() {
console.log('hi');
}
foo(); // works
foo(); // TypeError: undefined not a function
bar(); // ReferenceError: bar is not defined
foo = function bar() {
console.log('hi');
}
foo(); // okay!
bar(); // ReferenceError: bar is not defined
x >> n | right shift (by n) | sign is copied; effectively divide by 2n |
x >>> 0 | right-shift (by 0) without sign extension | Cast native JS double to int |
~~x | double bit-wise not | parseInt(x, 10), or Math.floor(x) |
!!~array.indexOf(...) |
Fancy way of: if (array.indexOf(...) >= 0) |
typeof 1 // "number"
typeof '1' // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object"
typeof {} // "object"
typeof function(){} // "function"
function
if an object has a [[Call]]
internal property.
someArray = [...];
// ES5
Array.isArray(someArray);
// Polyfill
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
toString
on an object, you get [object Cnstrctr]
_.isObject = function(obj) {
return obj === Object(obj);
};
obj.prop !== undefined
obj.hasOwnProperty('prop')
'prop' in obj
+x
x + ""
!!x
config = typeof config !== 'undefined' ? config : 42;
[[Put]] |
Method: Add an own property to an object |
---|---|
[[Set]] |
Method: Modify a property already on an object |
[[Delete]] |
Method: remove a property. Called by delete operator. |
hasOwnProperty() |
Determine if own property exists with given name |
---|---|
propertyIsEnumerable() |
Determine if property is enumerable (has enumerable attribute = true) |
isPrototypeOf() |
Determine if object is prototype of another |
valueOf() |
Called when operator is used on an object |
toString() |
Called when valueOf() returns a reference value instead of primitive. |
for-in
loop[[Enumerable]]
attribute set to trueProperty Attribute | Data Properties | Accessor Properties |
---|---|---|
[[Value]] |
Automatically filled, even functions | N/A |
[[Enumerable]] Counted by Object.keys() |
true |
|
[[Configurable]] Can remove with delete, or update config |
true |
|
[[Writable]] |
true Throw an error if attempt to change a nonwritable prop |
N/A |
[[Get]] |
N/A | |
[[Set]] |
N/A |
Cannot add properties
Object.isExtensible(obj);
Object.preventExtensions(obj);
Cannot add properties
Cannot remove properties
Cannot change property type (data ⇔ accessor)
Object.isSealed(obj);
Object.seal(obj);
Cannot add properties
Cannot remove properties
Cannot change property type (data ⇔ accessor)
Cannot write to data property
Object.isFrozen(obj);
Object.freeze(obj);
var person1 = {
_name: "Nicholas",
get name() { // ES5
// ...
}
}
var MySingleton = (function(){
// store reference to instance
var instance;
function init(){
// private variables
return {
}
}
// Singleton Return Object: A single accessor getInstance()
return {
getInstance: function(){
if (!instance) {
instance = init();
}
return instance;
}
}
})();
function Universe() {
// cache the instance
var instance = this;
// declare variables, init
// redefine constructor
Universe = function() {
return instance;
}
/* May need to preserve prototype....
Universe.prototype = this;
instance = new Universe();
instance.constructor = Universe;
*/
}
function createPerson(name, age) {
var o = new Object();
o.name = name;
o.age = age;
return o;
}
function Person(name, age) {
this.name = name;
this.age = age;
}
new Person('Tuan', 32);
new
operator.
prototype
property gets added.[[Prototype]]
property, __proto__
.function User(name){
if (!(this instanceof User)) {
return new User(name);
}
this.name = name;
}
function User(name){
var self = this instanceof User
? this
: Object.create(User.prototype);
self.name = name;
return self;
}
Suppose we have the following:
function Parent(){
this.name = name || 'Adam';
}
Parent.prototype.sayName = function(){}
function Child(){}
Child.prototype = new Parent();
function Child(a, b, c, d){
Parent.apply(this, arguments);
}
function Child(){
Parent.apply(this, arguments);
}
Child.prototype = new Parent();
Child.prototype = Parent.prototype
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.uber = Parent.prototype; // store the super class
Child.prototype.constructor = Child; // restore constructor
function Parent(){
//....
}
var parent = new Parent();
// Inheritance here:
function F(){} // empty function
F.prototype = parent;
var child = new F();
var child = Object.create(parent)
parent
is in instance, parent's own properties are now on child's instancevar child = Object.create(Parent.prototype)
var publisher = {
subscribers: {
any: [] // any is 'event'
},
subscribe: function(fn, type) {
type = type || 'any';
this.subscribers[type].push(fn); // add callback to the event
},
unsubscribe: function(){},
publish: function(publication, type) {
this.visitSubscribers('publish', publication, type);
},
visitSubscribers: function(action, arg, type) {
// iterate thru the subscribers for a given 'type'
var subscribers = this.subscribers[type];
subscribers.forEach(function(element, index, array){
element(arg);
});
}
}
define(function(require){
var lib = require( "package/lib" );
// behaviour for our module
function foo(){
lib.log( "hello world!" );
}
// export (expose) foo for other modules
return {
foobar: foo
};
});
// -- Consuming the module
require(["foobar", "baz"], function ( foobar, baz ) {
// rest of your code here
foobar.doSomething();
});
// -- foobar.js ------------------
var lib = require( "package/lib" );
// behaviour for our module
function foo(){
lib.log( "hello world!" );
}
// export (expose) foo to other modules
exports.foo = foo;
// -- Consuming the module -------
var foobar = require("./foobar.js").foobar,
test = new foobar();