JS FAQ Mozilla
JS FAQ Mozilla
1. Object constructor
The simplest way to create an object is to use the Object constructor: view plainprint?
var person = new Object();
person.name = "Diego";
person.getName = function(){
return this.name;
};
2. Literal notation
view plainprint?
var person = {
person.name : "Diego",
person.getName : function(){
return this.name;
}
}
3. Factory function
The Factory function allows to encapsulate and re-use the logic for creating similar objects. It
leverages any of the previous constructs for this. Either: view plainprint?
var newPerson=function(name){
var result = new Object();
result.name = name;
result.getName = function(){
return this.name;
};
return result;
};
var personOne = newPerson("Diego");
var personTwo = newPerson("Gangelo");
console.log(personOne.getName()); // prints Diego
console.log(personTwo.getName()); // prints Gangelo
Or:
view plainprint?
var newPerson=function(name){
return {
person.name : name,
person.getName : function(){
return this.name;
};
};
var personOne = newPerson("Diego");
var personTwo = newPerson("Gangelo");
console.log(personOne.getName()); // prints Diego
console.log(personTwo.getName()); // prints Gangelo
4. Function Constructor
In Javascript it is possible to call any function with the new operator in front of it. Given a function F,
for new F(): a new empty object X is created. X is set as context for F meaning throughout F this
points to X. X is returned as result of F view plainprint?
function Person(name){
Page 1 of 49
this.name = name;
this.getName = function(){
return this.name;
};
};
var personOne = new Person("Diego");
console.log(personOne.getName()); // prints Diego
console.log(personOne instanceOf Person); // prints true
console.log(personOne.constructor === Person); // prints true
console.log(personOne instanceOf Object); // prints true
5. Prototype
Functions are very special in Javascript. They are objects, they can create other objects and they
automatically get a field called prototype. A prototype is a plain object with a single field, called
constructor, pointing to the function itself. What makes it special is that every object created through a
function inherits the function's prototype. view plainprint?
function Person(){};
Person.prototype.name = "Diego";
var personOne = new Person();
var personTwo = new Person();
console.log(personOne.constructor == Person); // prints true
console.log(personOne.name); // prints Diego
console.log(personTwo.constructor == Person); // prints true
console.log(personTwo.name); // prints Diego
6. Function/Prototype combination
The function/prototype combination, as you would imagine, takes advantage of both approaches :)
view plainprint?
function Person(name){
this.name = name;
};
Person.prototype.getName = function(){
return this.name;
};
var personOne = new Person("Diego");
var personTwo = new Person("Filippo");
console.log(personOne.getName()); // prints Diego
console.log(personTwo.getName()); // prints Filippo
console.log(personOne.getName === personTwo.getName) //prints true
7. Singleton
Sometimes, you may want to make sure that only a single instance of a certain class exists. To get a
Singleton in Javascript is as simple as defining and invoking the constructor at the same time: view
plainprint?
var singleton = new function(){
this.name = "ApplicationName";
};
3.
4.
function createInstance() {
5.
6.
return object;
7.
8.
9.
return {
10.
getInstance: function () {
11.
if (!instance) {
12.
instance = createInstance();
13.
14.
return instance;
15.
16.
};
17.
})();
18.
19.
function run() {
20.
21.
22.
23.
24.
25.
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned objected can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonClass.getInstance();
yield i;
yield* anotherGenerator(i);
yield i + 10;
}
var gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
Passing arguments into Generators
function* logGenerator() {
console.log(yield);
console.log(yield);
console.log(yield);
}
var gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next();
gen.next('pretzel'); // pretzel
gen.next('california'); // california
gen.next('mayonnaise'); // mayonnaise
What is iterator in JS
An object is an iterator when it knows how to access items from a collection one at a time, while
keeping track of its current position within that sequence. In JavaScript an iterator is an object that
provides a next() method which returns the next item in the sequence. This method returns an object
with two properties: done and value.
Once created, an iterator object can be used explicitly by repeatedly calling next().
function makeIterator(array){
var nextIndex = 0;
return {
next: function(){
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
}
}
Page 5 of 49
What is iteratable ?
An object is iterable if it defines its iteration behavior, such as what values are looped over in
a for..ofconstruct. Some built-in types, such as Array or Map, have a default iteration behavior, while
other types (such as Object) do not.
In order to be iterable, an object must implement the @@iterator method, meaning that the object
(or one of the objects up its prototype chain) must have a property with a Symbol.iterator key:
User-defined iterables
We can make our own iterables like this:
var myIterable = {}
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable] // [1, 2, 3]
JavaScript
function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
function WorkerBee() {
Employee.call(this);
this.projects = [];
}
WorkerBee.prototype = Object.create(Employee.prototype);
Java
public class Manager extends Employee {
public Employee[] reports = new Employee[0];
}
Page 6 of 49
The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence
from Employee. An object of these types has properties of all the objects above it in the chain. In
addition, these definitions override the inherited value of the dept property with new values specific to
these objects.
JavaScript
function SalesPerson() {
WorkerBee.call(this);
this.dept = "sales";
this.quota = 100;
}
SalesPerson.prototype = Object.create(WorkerBee.prototype);
function Engineer() {
WorkerBee.call(this);
this.dept = "engineering";
this.machine = "";
}
Engineer.prototype = Object.create(WorkerBee.prototype);
Java
public class SalesPerson extends WorkerBee {
public double quota;
public dept = "sales";
public quota = 100.0;
}
public class Engineer extends WorkerBee {
public String machine;
public dept = "engineering";
public machine = "";
}
Using these definitions, you can create instances of these objects that get the default values for their
properties. The next figure illustrates using these JavaScript definitions to create new objects and
shows the property values for the new objects.
The following table shows the Java and JavaScript definitions for these objects.
JavaScript
Java
function Employee (name, dept) {
this.name = name || "";
this.dept = dept || "general";
}
Page 7 of 49
Page 8 of 49
Page 9 of 49
Object creation
Using the Object.create method
Objects can also be created using the Object.create() method. This method can be very useful, because
it allows you to choose the prototype object for the object you want to create, without having to define
a constructor function.
// Animal properties and method encapsulation
var Animal = {
type: "Invertebrates", // Default value of properties
displayType : function() { // Method which will display type of Animal
console.log(this.type);
}
}
// Create new animal type called animal1
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes
Define the object type by writing a constructor function. There is a strong convention, with
good reason, to use a capital initial letter.
2.
Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name, properties, and
methods. For example, suppose you want to create an object type for cars. You want this type of
object to be called car, and you want it to have properties for make, model, and year. To do this, you
would write the following function:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Notice the use of this to assign values to the object's properties based on the values passed to the
function.
Now you can create an object called mycar as follows:
var mycar = new Car("Eagle", "Talon TSi", 1993);
This statement creates mycar and assigns it the specified values for its properties. Then the value
ofmycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.
You can create any number of car objects by calls to new. For example,
var kenscar = new Car("Nissan", "300ZX", 1992);
var vpgscar = new Car("Mazda", "Miata", 1990);
Description
exec
A RegExp method that executes a search for a match in a string. It returns an array of
information.
test
A RegExp method that tests for a match in a string. It returns true or false.
match
A String method that executes a search for a match in a string. It returns an array of
information or null on a mismatch.
search
A String method that tests for a match in a string. It returns the index of the match, or -1 if
the search fails.
replace
A String method that executes a search for a match in a string, and replaces the matched
substring with a replacement substring.
split
A String method that uses a regular expression or a fixed string to break a string into an
array of substrings.
Populating an array
You can populate an array by assigning values to its elements. For example,
var emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.
reverse() transposes the elements of an array: the first array element becomes the last and the last
becomes the first.
var myArray = new Array ("1", "2", "3");
myArray.reverse();
// transposes the array so that myArray = [ "3", "2", "1" ]
sort() sorts the elements of an array.
var myArray = new Array("Wind", "Rain", "Fire");
myArray.sort();
// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ]
sort() can also take a callback function to determine how array elements are compared. The function
compares two values and returns one of three values:
For instance, the following will sort by the last letter of a string:
byte
int8_t
Uint8Array
octet
uint8_t
Uint8ClampedArra
y
octet
uint8_t
Int16Array
short
int16_t
Uint16Array
unsigned short
uint16_t
Int32Array
long
int32_t
Uint32Array
unsigned long
uint32_t
Float32Array
unrestricted
float
float
Float64Array
unrestricted
double
double
Achieving inheritence ?
Page 15 of 49
Below is an example of how to use Object.create() to achieve classical inheritance. This is for single
inheritance, which is all that JavaScript supports.
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'
If you wish to inherit from multiple objects, then mixins are a possibility.
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
MyClass.prototype = Object.create(SuperClass.prototype); // inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin
MyClass.prototype.myMethod = function() {
// do a thing
};
Third, strict mode prohibits some syntax likely to be defined in future versions of
ECMAScript
// Whole-script strict mode syntax
"use strict";
var v = "Hi! I'm a strict mode script!";
function strict1(str){
"use strict";
return eval(str); // str will be treated as strict mode code
}
function strict2(f, str){
"use strict";
return f(str); // not eval(...): str is strict if and only
// if it invokes strict mode
}
function nonstrict(str){
return eval(str); // str is strict if and only
// if it invokes strict mode
}
strict1("'Strict mode code!'");
strict1("'use strict'; 'Strict mode code!'");
strict2(eval, "'Non-strict code.'");
strict2(eval, "'use strict'; 'Strict mode code!'");
nonstrict("'Non-strict code.'");
nonstrict("'use strict'; 'Strict mode code!'");
m: function(b){
return this.a + 1;
}
};
console.log(o.m()); // 3
// When calling o.m in this case, 'this' refers to o
var p = Object.create(o);
// p is an object that inherits from o
p.a = 12; // creates an own property 'a' on p
console.log(p.m()); // 13
// when p.m is called, 'this' refers to p.
// So when p inherits the function m of o,
// 'this.a' means p.a, the own property 'a' of p
What are the different ways to create objects and the resulting prototype chain
Objects created with syntax constructs
var o = {a: 1};
// The newly created object o has Object.prototype as its [[Prototype]]
// o has no own property named 'hasOwnProperty'
// hasOwnProperty is an own property of Object.prototype.
// So o inherits hasOwnProperty from Object.prototype
// Object.prototype has null as its prototype.
// o ---> Object.prototype ---> null
var a = ["yo", "whadup", "?"];
// Arrays inherit from Array.prototype
// (which has methods like indexOf, forEach, etc.)
// The prototype chain looks like:
// a ---> Array.prototype ---> Object.prototype ---> null
function f(){
return 2;
}
// Functions inherit from Function.prototype
// (which has methods like call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null
With a constructor
A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.
function Graph() {
Page 18 of 49
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v){
this.vertices.push(v);
}
};
var g = new Graph();
// g is an object with own properties 'vertices' and 'edges'.
// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
With Object.create
ECMAScript 5 introduced a new method: Object.create(). Calling this method creates a new object.
The prototype of this object is the first argument of the function:
var a = {a: 1};
// a ---> Object.prototype ---> null
var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)
var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null
var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty);
// undefined, because d doesn't inherit from Object.prototype
super(sideLength, sideLength);
}
get area() {
return this.height * this.width;
}
set sideLength(newLength) {
this.height = newLength;
this.width = newLength;
}
}
var square = new Square(2);
Lexical scoping
Consider the following:
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
init() creates a local variable name and then a function called displayName(). displayName() is an
inner function that is defined inside init() and is only available within the body of that
function.displayName() has no local variables of its own, however it has access to the variables of
outer functions and so can use the variable name declared in the parent function.
What is closure ?
Closures are functions that refer to independent (free) variables (variables that are used locally,
but defined in an enclosing scope). In other words, these functions 'remember' the environment
in which they were created.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
If you run this code it will have exactly the same effect as the previous init() example: the string
"Mozilla" will be displayed in a JavaScript alert box. What's different and interesting is that
thedisplayName() inner function was returned from the outer function before being executed
Page 20 of 49
What is ==
var num = 0;
var obj = new String("0");
var str = "0";
var b = false;
console.log(num == num); // true
console.log(obj == obj); // true
console.log(str == str); // true
console.log(num == obj); // true
console.log(num == str); // true
console.log(obj == str); // true
Page 21 of 49
Note: The Object.create() method used above is relatively new. For an alternative method using
closures, please consider the following alternative:
Function.prototype.construct = function(aArgs) {
var fConstructor = this, fNewConstr = function() {
fConstructor.apply(this, aArgs);
};
fNewConstr.prototype = fConstructor.prototype;
return new fNewConstr();
};
Example usage:
function MyConstructor() {
for (var nProp = 0; nProp < arguments.length; nProp++) {
this['property' + nProp] = arguments[nProp];
}
}
var myArray = [4, 'Hello world!', false];
var myInstance = MyConstructor.construct(myArray);
console.log(myInstance.property1);
// logs 'Hello world!'
console.log(myInstance instanceof MyConstructor); // logs 'true'
console.log(myInstance.constructor);
// logs 'MyConstructor'
Note: This non-native Function.construct method will not work with some native constructors
(like Date, for example). In these cases you have to use the Function.prototype.bind method (for
example, imagine having an array like the following, to be used with Date constructor: [2012, 11, 4];
in this case you have to write something like: new (Function.prototype.bind.apply(Date,
[null].concat([2012, 11, 4])))() anyhow this is not the best way to do things and probably should
not be used in any production environment).
Using apply and built-in functions
Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably
would have been written by looping over the array values. As an example here we are going to
useMath.max/Math.min to find out the maximum/minimum value in an array.
// min/max number in an array
var numbers = [5, 6, 2, 3, 7];
// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
// This about equal to Math.max(numbers[0], ...)
// or Math.max(5, 6, ...)
var min = Math.min.apply(null, numbers);
// vs. simple loop based algorithm
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
Page 24 of 49
Page 25 of 49
Page 26 of 49
By default within window.setTimeout(), the this keyword will be set to the window (or global) object.
When working with class methods that require this to refer to class instances, you may explicitly
bindthis to the callback function, in order to maintain the instance.
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom();
// after 1 second, triggers the 'declare' method
Bound functions used as constructors
Warning: This section demonstrates JavaScript capabilities and documents some edge cases of
the bind()method. The methods shown below are not the best way to do things and probably should
not be used in any production environment.
Bound functions are automatically suitable for use with the new operator to construct new instances
created by the target function. When a bound function is used to construct a value, the provided this is
ignored. However, provided arguments are still prepended to the constructor call:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return this.x + ',' + this.y;
};
var p = new Point(1, 2);
p.toString(); // '1,2'
// not supported in the polyfill below,
// works fine with native bind:
var YAxisPoint = Point.bind(null, 0/*x*/);
var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
Page 27 of 49
Note that you need do nothing special to create a bound function for use with new. The corollary is
that you need do nothing special to create a bound function to be called plainly, even if you would
rather require the bound function to only be called using new.
// Example can be run directly in your JavaScript console
// ...continuing from above
// Can still be called as a normal function
// (although usually this is undesired)
YAxisPoint(13);
emptyObj.x + ',' + emptyObj.y;
// > '0,13'
If you wish to support use of a bound function only using new, or only by calling it, the target
function must enforce that restriction.
Creating shortcuts
bind() is also helpful in cases where you want to create a shortcut to a function which requires a
specific this value.
Take Array.prototype.slice, for example, which you want to use for converting an array-like object to
a real array. You could create a shortcut like this:
var slice = Array.prototype.slice;
// ...
slice.apply(arguments);
With bind(), this can be simplified. In the following piece of code, slice is a bound function to
theapply() function of Function.prototype, with the this value set to the slice() function
ofArray.prototype. This means that additional apply() calls can be eliminated:
// same as "slice" in the previous example
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.apply.bind(unboundSlice);
// ...
Page 28 of 49
slice(arguments);
Polyfill
The bind function is an addition to ECMA-262, 5th edition; as such it may not be present in all
browsers. You can partially work around this by inserting the following code at the beginning of your
scripts, allowing use of much of the functionality of bind() in implementations that do not natively
support it.
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
}
What is promise ?
The Promise object is used for asynchronous computations. A Promise represents an operation that
hasn't completed yet, but is expected in the future.
Page 29 of 49
Promise.all(iterable)
Returns a promise that either resolves when all of the promises in the iterable argument have
resolved or rejects as soon as one of the promises in the iterable argument rejects. If the
returned promise resolves, it is resolved with an array of the values from the resolved
promises in the iterable. If the returned promise rejects, it is rejected with the reason from the
promise in the iterable that rejected. This method can be useful for aggregating results of
multiple promises together.
Promise.race(iterable)
Returns a promise that resolves or rejects as soon as one of the promises in the iterable
resolves or rejects, with the value or reason from that promise.
Promise.reject(reason)
Returns a Promise object that is rejected with the given reason.
Promise.resolve(value)
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e.
has athen method), the returned promise will "follow" that thenable, adopting its eventual
state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to
know if a value is a promise or not - Promise.resolve(value) it instead and work with the
return value as a promise.
Creating a Promise
This small example shows the mechanism of a Promise. The testPromise() method is called each time
the <button> is clicked. It creates a promise that will resolve, using window.setTimeout(), to the
promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is
used to create the promise.
The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then(). A few logs
shows how the synchronous part of the method is decoupled of the asynchronous completion of the
promise.
'use strict';
var promiseCount = 0;
function testPromise() {
var thisPromiseCount = ++promiseCount;
var log = document.getElementById('log');
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') Started (<small>Sync code started</small>)<br/>');
// We make a new promise: we promise a numeric count of this promise, starting from 1 (after
waiting 3s)
var p1 = new Promise(
// The resolver function is called with the ability to resolve or
// reject the promise
function(resolve, reject) {
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') Promise started (<small>Async code started</small>)<br/>');
// This is only an example to create asynchronism
window.setTimeout(
function() {
Page 30 of 49
Creating a Promise
This example shows the implementation of a method which uses a Promise to report the success or
failure of an XMLHttpRequest.
'use strict';
// A-> $http function is implemented in order to follow the standard Adapter pattern
function $http(url){
// A small example of object
var core = {
// Method that performs the ajax request
ajax: function (method, url, args) {
// Creating a promise
var promise = new Promise( function (resolve, reject) {
// Instantiates the XMLHttpRequest
var client = new XMLHttpRequest();
var uri = url;
if (args && (method === 'POST' || method === 'PUT')) {
uri += '?';
var argcount = 0;
for (var key in args) {
if (args.hasOwnProperty(key)) {
if (argcount++) {
Page 31 of 49
uri += '&';
}
uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
}
}
}
client.open(method, uri);
client.send();
client.onload = function () {
if (this.status >= 200 && this.status < 300) {
// Performs the function "resolve" when this.status is equal to 2xx
resolve(this.response);
} else {
// Performs the function "reject" when this.status is different than 2xx
reject(this.statusText);
}
};
client.onerror = function () {
reject(this.statusText);
};
});
// Return the promise
return promise;
}
};
// Adapter pattern
return {
'get': function(args) {
return core.ajax('GET', url, args);
},
'post': function(args) {
return core.ajax('POST', url, args);
},
'put': function(args) {
return core.ajax('PUT', url, args);
},
'delete': function(args) {
return core.ajax('DELETE', url, args);
}
};
};
// End A
// B-> Here you define its functions and its payload
var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
var payload = {
'topic' : 'js',
'q' : 'Promise'
};
var callback = {
Page 32 of 49
success: function(data) {
console.log(1, 'success', JSON.parse(data));
},
error: function(data) {
console.log(2, 'error', JSON.parse(data));
}
};
// End B
// Executes the method call
$http(mdnAPI)
.get(payload)
.then(callback.success)
.catch(callback.error);
// Executes the method call but an alternative way (1) to handle Promise Reject case
$http(mdnAPI)
.get(payload)
.then(callback.success, callback.error);
// Executes the method call but an alternative way (2) to handle Promise Reject case
$http(mdnAPI)
.get(payload)
.then(callback.success)
.then(undefined, callback.error);
The for each...in statement iterates a specified variable over all values of object's properties. For
each distinct property, a specified statement is executed.
Using for each...in
Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.
The following snippet iterates over an object's properties, calculating their sum:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
sum += item;
}
console.log(sum); // logs "26", which is 5+13+8
The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each
distinct property, statements can be executed.
The following function takes as its argument an object. It then iterates over all the object's enumerable
properties and returns a string of the property names and their values.
var obj = {a:1, b:2, c:3};
Page 33 of 49
The following function illustrates the use of hasOwnProperty(): the inherited properties are not
displayed.
var triangle = {a:1, b:2, c:3};
function ColoredTriangle() {
this.color = "red";
}
ColoredTriangle.prototype = triangle;
var obj = new ColoredTriangle();
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) {
console.log("obj." + prop + " = " + obj[prop]);
}
}
// Output:
// "obj.color = red"
Page 34 of 49
console.log(value);
}
// 1
// 2
// 3
Iterating over a DOM collection
Iterating over DOM collections like NodeList: the following example adds a read class to paragraphs
that are direct descendants of an article:
// Note: This will only work in platforms that have
// implemented NodeList.prototype[Symbol.iterator]
let articleParagraphs = document.querySelectorAll("article > p");
for (let paragraph of articleParagraphs) {
paragraph.classList.add("read");
}
Iterating over generators
You can also iterate over generators:
function* fibonacci() { // a generator function
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Difference between for...of and for...in
The for...in loop will iterate over all enumerable properties of an object.
The for...of syntax is specific to collections, rather than all objects. It will iterate in this manner over
the elements of any collection that has a [Symbol.iterator] property.
The following example shows the difference between a for...of loop and a for...in loop.
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
Page 36 of 49
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to
function expressions and lexically binds the this value. Arrow functions are always anonymous. See
also this hacks.mozilla.org blog post: "ES6 In Depth: Arrow functions".
Two factors influenced the introduction of arrow functions: shorter functions and lexical this.
Shorter functions
In some functional patterns, shorter functions are welcome. Compare:
var a = [
"Hydrogen",
"Helium",
"Lithium",
"Beryllium"
];
var a2 = a.map(function(s){ return s.length });
var a3 = a.map( s => s.length );
Lexical this
Until arrow functions, every new function defined its own this value (a new object in case of a
constructor, undefined in strict mode function calls, the context object if the function is called as an
"object method", etc.). This proved to be annoying with an object-oriented style of programming.
function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0;
setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
Page 37 of 49
Variable hoisting ?
Another unusual thing about variables in JavaScript is that you can refer to a variable declared later,
without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense
"hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will
return a value of undefined. So even if you declare and initialize after you use or refer to this variable,
it will still return undefined.
/**
* Example 1
*/
console.log(x === undefined); // true
var x = 3;
/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";
Page 38 of 49
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
The above examples will be interpreted the same as:
/**
* Example 1
*/
var x;
console.log(x === undefined); // true
x = 3;
/**
* Example 2
*/
var myvar = "my value";
(function() {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();
Because of hoisting, all var statements in a function should be placed as near to the top of the function
as possible. This best practice increases the clarity of the code.
In JavaScript, undefined means a variable has been declared but has not yet been assigned a
value, such as:
var TestVar;
alert(TestVar); //shows undefined
ccepte alert(typeof TestVar); //shows undefined
d
null is an assignment value. It can be assigned to a variable as a representation of no value:
var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct
types: undefined is a type itself (undefined) while null is an object.
null === undefined // false
null == undefined // true
null === null // true
and
\
Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an
event occurs in an element inside another element, and both elements have registered a handle for that
event. The event propagation mode determines in which order the elements receive the event.
With bubbling, the event is first captured and handled by the innermost element and then propagated
to outer elements.
With capturing, the event is first captured by the outermost element and propagated to the inner
elements.
Capturing is also called "trickling", which helps remember the propagation order:
trickle down, bubble up
We can use the addEventListener(type, listener, useCapture) to register event handlers for in either
bubbling (default) or capturing mode. To use the capturing model pass the third argument as true.
this.width = width;
}
}
A class expression is another way to define a class. Class expressions can be named or unnamed. The
name given to a named class expression is local to the class's body.
// unnamed
var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// named
var Polygon = class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
Class body and method definitions
The body of a class is the part that is in curly brackets {}. This is where you define class members,
such as methods or constructors.
Strict mode
The bodies of class declarations and class expressions are executed in strict mode.
Constructor
The constructor method is a special method for creating and initializing an object created with a class.
There can only be one special method with the name "constructor" in a class. A SyntaxError will be
thrown if the class contains more than one occurrence of a constructor method.
A constructor can use the super keyword to call the constructor of a parent class.
Prototype methods
See also method definitions.
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
Page 41 of 49
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Polygon(10, 10);
console.log(square.area);
Static methods
The static keyword defines a static method for a class. Static methods are called
without instantiatingtheir class and are also not callable when the class is instantiated. Static methods
are often used to create utility functions for an application.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
Sub classing with extends
The extends keyword is used in class declarations or class expressions to create a class as a child of
another class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
Page 42 of 49
}
}
One may also extend traditional function-based "classes":
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.');
}
class Dog extends Animal {
speak() {
super.speak();
console.log(this.name + ' barks.');
}
}
var d = new Dog('Mitzie');
d.speak();
Species
You might want to return Array objects in your derived array class MyArray. The species pattern lets
you override default constructors.
For example, when using methods such as map() that returns the default constructor, you want these
methods to return a parent Array object, instead of the MyArray object. The Symbol.species symbol
lets you do this:
class MyArray extends Array {
// Overwrite species to the parent Array constructor
static get [Symbol.species]() { return Array; }
}
var a = new MyArray(1,2,3);
var mapped = a.map(x => x * x);
console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
Super class calls with super
The super keyword is used to call functions on an object's parent.
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
Page 43 of 49
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
Mix-ins
Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single
superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality
must be provided by the superclass.
A function with a superclass as input and a subclass extending that superclass as output can be used to
implement mix-ins in ECMAScript:
var CalculatorMixin = Base => class extends Base {
calc() { }
};
var RandomizerMixin = Base => class extends Base {
randomize() { }
};
A class that uses these mix-ins can then be written like this:
class Foo { }
class Bar extends CalculatorMixin(RandomizerMixin(Foo)) { }
Specifications
console.log(item, index);
});
// Apple 0
// Banana 1
Add to the end of an Array
var newLength = fruits.push("Orange");
// ["Apple", "Banana", "Orange"]
Remove from the end of an Array
var last = fruits.pop(); // remove Orange (from the end)
// ["Apple", "Banana"];
Remove from the front of an Array
var first = fruits.shift(); // remove Apple from the front
// ["Banana"];
Add to the front of an Array
var newLength = fruits.unshift("Strawberry") // add to the front
// ["Strawberry", "Banana"];
Find the index of an item in the Array
fruits.push("Mango");
// ["Strawberry", "Banana", "Mango"]
var pos = fruits.indexOf("Banana");
// 1
Remove an item by Index Position
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
// ["Strawberry", "Mango"]
Copy an Array
var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]
Page 45 of 49
splice()
slice()
method doesnt
Argument 3n:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array
object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
var array3=[11,12,13,14,15];
console.log(array3.splice(2,1,"Hello","World"));
// shows [13]
console.log(array3);
// shows [11, 12, "Hello", "World", 14, 15]
-5 -4 -3 -2 -1
| | | | |
var array4=[16,17,18,19,20];
| | | | |
0 1 2 3 4
console.log(array4.splice(-2,1,"me"));
// shows [19]
console.log(array4);
// shows [16, 17, 18, "me", 20]
Page 46 of 49
1
2
3
4
5
6
var array5=[21,22,23,24,25];
console.log(array5.splice(NaN,4,"NaN is Treated as 0"));
// shows [21,22,23,24]
console.log(array5);
// shows ["NaN is Treated as 0",25]
1
2
3
4
5
6
7
8
9
10
11
12
var array6=[26,27,28,29,30];
console.log(array6.splice(2,-5,"Hello"));
// shows []
console.log(array6);
// shows [26,27,"Hello",28,29,30]
console.log(array6.splice(3,NaN,"World"));
// shows []
console.log(array6);
// shows [26,27,"Hello","World",28,29,30]
If Argument(1) or Argument(2) is greater than Arrays length, either argument will use the Arrays length.
1
2
3
4
5
6
7
8
9
10
11
12
var array7=[31,32,33,34,35];
console.log(array7.splice(23,3,"Add Me"));
// shows []
console.log(array7);
// shows [31,32,33,34,35,"Add Me"]
console.log(array7.splice(2,34,"Add Me Too"));
// shows [33,34,35,"Add Me"]
console.log(array7);
// shows [31,32,"Add Me Too"]
4. The
slice()
1
2
var array=[1,2,3,4,5]
console.log(array.slice(2));
Page 47 of 49
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
var array3=[11,12,13,14,15];
console.log(array3.slice(NaN,NaN));
// shows []
console.log(array3.slice(NaN,4));
// shows [11,12,13,14]
console.log(array3);
// shows [11,12,13,14,15]
If either argument is greater than the Arrays length, either argument will use the Arrays length
1
2
3
4
5
6
7
8
9
10
11
12
var array4=[16,17,18,19,20];
console.log(array4.slice(23,24));
// shows []
console.log(array4.slice(23,2));
// shows []
console.log(array4.slice(2,23));
// shows [18,19,20]
console.log(array4);
// shows [16,17,18,19,20]
Page 48 of 49
Page 49 of 49