+ All Categories
Home > Documents > JS FAQ Mozilla

JS FAQ Mozilla

Date post: 08-Jul-2016
Category:
Upload: chaitu215
View: 3 times
Download: 3 times
Share this document with a friend
Description:
hi
56
7 ways to create objects in JavaScript : 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; }; }; Page 1 of 56
Transcript
Page 1: JS FAQ Mozilla

7 ways to create objects in JavaScript :

1. Object constructorThe 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 notationview plainprint?

var person = { person.name : "Diego", person.getName : function(){ return this.name; } } 3. Factory functionThe 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 GangeloOr:

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 ConstructorIn 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 44

Page 2: JS FAQ Mozilla

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. PrototypeFunctions 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 combinationThe 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. SingletonSometimes, 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"; };

How to create a singleton class

1. var Singleton = (function () {2. var instance;3.  

Page 2 of 44

Page 3: JS FAQ Mozilla

4. function createInstance() {5. var object = new Object("I am the instance");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. var instance1 = Singleton.getInstance();22. var instance2 = Singleton.getInstance();23.  24. alert("Same instance? " + (instance1 === instance2)); 25. }

var SingletonClass = (function(){ function SingletonClass() { //do stuff } 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();

How to declare a generator in javascript

The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

You can also define generator functions using the GeneratorFunction constructor and a function* expression.

Page 3 of 44

Page 4: JS FAQ Mozilla

Simple example

function* idMaker(){ var index = 0; while(index < 3) yield index++;}

var gen = idMaker();

console.log(gen.next().value); // 0console.log(gen.next().value); // 1console.log(gen.next().value); // 2console.log(gen.next().value); // undefined// ...

Example with yield*

function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3;}

function* generator(i){ yield i; yield* anotherGenerator(i); yield i + 10;}

var gen = generator(10);

console.log(gen.next().value); // 10console.log(gen.next().value); // 11console.log(gen.next().value); // 12console.log(gen.next().value); // 13console.log(gen.next().value); // 20Passing 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 statementgen.next(); gen.next('pretzel'); // pretzelgen.next('california'); // californiagen.next('mayonnaise'); // mayonnaise

Page 4 of 44

Page 5: JS FAQ Mozilla

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}; } }}

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]

How to achieve inheritence in JS and creation of objects

JavaScript

function Manager() { Employee.call(this); this.reports = [];}

Page 5 of 44

Page 6: JS FAQ Mozilla

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];}

public class WorkerBee extends Employee { public String[] projects = new String[0];}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.

Page 6 of 44

Page 7: JS FAQ Mozilla

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";} 

 

 

 

 

public class Employee { public String name; public String dept; public Employee () { this("", "general"); } public Employee (String name) { this(name, "general"); } public Employee (String name, String dept) { this.name = name; this.dept = dept; }}function WorkerBee (projs) { this.projects = projs || [];}WorkerBee.prototype = new Employee; 

 

 

public class WorkerBee extends Employee { public String[] projects; public WorkerBee () { this(new String[0]); } public WorkerBee (String[] projs) {

Page 7 of 44

Page 8: JS FAQ Mozilla

projects = projs; }}function Engineer (mach) { this.dept = "engineering"; this.machine = mach || "";}Engineer.prototype = new WorkerBee; 

 

 

public class Engineer extends WorkerBee { public String machine; public Engineer () { dept = "engineering"; machine = ""; } public Engineer (String mach) { dept = "engineering"; machine = mach; }}

function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || "";}var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");Employee.prototype.specialty = "none";The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || "";}Engineer.prototype = new WorkerBee;var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");Employee.prototype.specialty = "none";Now the value of the jane object's specialty property is "none".Another way of inheriting is by using the call() / apply() methods. Below are equivalent:function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || "";}function Engineer (name, projs, mach) { WorkerBee.call(this, name, "engineering", projs); this.machine = mach || "";

Page 8 of 44

Page 9: JS FAQ Mozilla

}Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

Object creation

Using the Object.create methodObjects 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 encapsulationvar 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 Fishesvar fish = Object.create(Animal);fish.type = "Fishes";fish.displayType(); // Output:Fishes

Using a constructor function

Alternatively, you can create an object with these two steps:

1. 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);

Page 9 of 44

Page 10: JS FAQ Mozilla

var vpgscar = new Car("Mazda", "Miata", 1990);

What are methods in regualr expressions

Methods that use regular expressionsMethod 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.

How do you decalre and iterate a map

var sayings = new Map();sayings.set("dog", "woof");sayings.set("cat", "meow");sayings.set("elephant", "toot");sayings.size; // 3sayings.get("fox"); // undefinedsayings.has("bird"); // falsesayings.delete("dog");

for (var [key, value] of sayings) { console.log(key + " goes " + value);}// "cat goes meow"// "elephant goes toot"

Program for Set

var mySet = new Set();mySet.add(1);mySet.add("some text");mySet.add("foo");

mySet.has(1); // truemySet.delete("foo");mySet.size; // 2

Page 10 of 44

Page 11: JS FAQ Mozilla

for (let item of mySet) console.log(item);// 1// "some text"

How to declaring arrays in javascript

Creating an array

The following statements create equivalent arrays:

var arr = new Array(element0, element1, ..., elementN);var arr = Array(element0, element1, ..., elementN);var arr = [element0, element1, ..., elementN];

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";

You can also populate an array when you create it:

var myArray = new Array("Hello", myVar, 3.14159);var myArray = ["Mango", "Apple", "Orange"]

var arr = ["one", "two", "three"];arr[2]; // threearr["length"]; // 3

Iterating over arrays

A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:

var colors = ['red', 'green', 'blue'];for (var i = 0; i < colors.length; i++) { console.log(colors[i]);}

The forEach() method provides another way of iterating over an array:var colors = ['red', 'green', 'blue'];colors.forEach(function(color) { console.log(color);});

Page 11 of 44

Page 12: JS FAQ Mozilla

var array = ['first', 'second', , 'fourth'];

// returns ['first', 'second', 'fourth'];array.forEach(function(element) { console.log(element);})

if(array[2] === undefined) { console.log('array[2] is undefined'); } // true

var array = ['first', 'second', undefined, 'fourth'];

// returns ['first', 'second', undefined, 'fourth'];array.forEach(function(element) { console.log(element);})

What are method s in arrays ?

Array methods

The Array object has the following methods:concat() joins two arrays and returns a new array.var myArray = new Array("1", "2", "3");myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"]join(deliminator = ',') joins all elements of an array into a string.var myArray = new Array("Wind", "Rain", "Fire");var list = myArray.join(" - "); // list is "Wind - Rain - Fire"push() adds one or more elements to the end of an array and returns the resulting length of the array.var myArray = new Array("1", "2");myArray.push("3"); // myArray is now ["1", "2", "3"]pop() removes the last element from an array and returns that element.var myArray = new Array("1", "2", "3");var last = myArray.pop(); // myArray is now ["1", "2"], last = "3"shift() removes the first element from an array and returns that element.var myArray = new Array ("1", "2", "3");var first = myArray.shift(); // myArray is now ["2", "3"], first is "1"unshift() adds one or more elements to the front of an array and returns the new length of the array.var myArray = new Array ("1", "2", "3");myArray.unshift("4", "5"); // myArray becomes ["4", "5", "1", "2", "3"]slice(start_index, upto_index) extracts a section of an array and returns a new array.var myArray = new Array ("a", "b", "c", "d", "e");myArray = myArray.slice(1, 4); // starts at index 1 and extracts all elements // until index 3, returning [ "b", "c", "d"]splice(index, count_to_remove, addElement1, addElement2, ...) removes elements from an array and (optionally) replaces them.var myArray = new Array ("1", "2", "3", "4", "5");myArray.splice(1, 3, "a", "b", "c", "d"); // myArray is now ["1", "a", "b", "c", "d", "5"]// This code started at index one (or where the "2" was), // removed 3 elements there, and then inserted all consecutive

Page 12 of 44

Page 13: JS FAQ Mozilla

// 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:

var sortFn = function(a, b){ if (a[a.length - 1] < b[b.length - 1]) return -1; if (a[a.length - 1] > b[b.length - 1]) return 1; if (a[a.length - 1] == b[b.length - 1]) return 0;}myArray.sort(sortFn); // sorts the array so that myArray = ["Wind","Fire","Rain"]

if a is less than b by the sorting system, return -1 (or any negative number) if a is greater than b by the sorting system, return 1 (or any positive number) if a and b are considered equivalent, return 0.

indexOf(searchElement[, fromIndex]) searches the array for searchElement and returns the index of the first match.var a = ['a', 'b', 'a', 'b', 'a'];console.log(a.indexOf('b')); // logs 1// Now try again, starting from after the last matchconsole.log(a.indexOf('b', 2)); // logs 3console.log(a.indexOf('z')); // logs -1, because 'z' was not foundlastIndexOf(searchElement[, fromIndex]) works like indexOf, but starts at the end and searches backwards.var a = ['a', 'b', 'c', 'd', 'a', 'b'];console.log(a.lastIndexOf('b')); // logs 5// Now try again, starting from before the last matchconsole.log(a.lastIndexOf('b', 4)); // logs 1console.log(a.lastIndexOf('z')); // logs -1forEach(callback[, thisObject]) executes callback on every array item.var a = ['a', 'b', 'c'];a.forEach(function(element) { console.log(element);} ); // logs each item in turnmap(callback[, thisObject]) returns a new array of the return value from executing callback on every array item.var a1 = ['a', 'b', 'c'];var a2 = a1.map(function(item) { return item.toUpperCase(); });console.log(a2); // logs A,B,Cfilter(callback[, thisObject]) returns a new array containing the items for which callback returned true.var a1 = ['a', 10, 'b', 20, 'c', 30];var a2 = a1.filter(function(item) { return typeof item === 'number'; });console.log(a2); // logs 10,20,30every(callback[, thisObject]) returns true if callback returns true for every item in the array.function isNumber(value){ return typeof value === 'number';}

Page 13 of 44

Page 14: JS FAQ Mozilla

var a1 = [1, 2, 3];console.log(a1.every(isNumber)); // logs truevar a2 = [1, '2', 3];console.log(a2.every(isNumber)); // logs falsesome(callback[, thisObject]) returns true if callback returns true for at least one item in the array.function isNumber(value){ return typeof value === 'number';}var a1 = [1, 2, 3];console.log(a1.some(isNumber)); // logs truevar a2 = [1, '2', 3];console.log(a2.some(isNumber)); // logs truevar a3 = ['1', '2', '3'];console.log(a3.some(isNumber)); // logs false

Typed array views ?

Typed array views have self descriptive names and provide views for all the usual numeric types likeInt8, Uint32, Float64 and so forth. There is one special typed array view, the Uint8ClampedArray. It clamps the values between 0 and 255. This is useful for Canvas data processing, for example.

Type Size in bytes Description Web IDL type Equivalent C

type

Int8Array 1 8-bit two's complement signed integer byte int8_t

Uint8Array 1 8-bit unsigned integer octet uint8_t

Uint8ClampedArray 1 8-bit unsigned integer (clamped) octet uint8_t

Int16Array 2 16-bit two's complement signed integer short int16_t

Uint16Array 2 16-bit unsigned integer unsigned short uint16_t

Int32Array 4 32-bit two's complement signed integer long int32_t

Uint32Array 4 32-bit unsigned integer unsigned long uint32_t

Float32Array 4 32-bit IEEE floating point number

unrestricted float float

Float64Array 8 64-bit IEEE floating point number

unrestricted double double

Achieving inheritence ?

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

Page 14 of 44

Page 15: JS FAQ Mozilla

function Shape() { this.x = 0; this.y = 0;}

// superclass methodShape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.');};

// Rectangle - subclassfunction Rectangle() { Shape.call(this); // call super constructor.}

// subclass extends superclassRectangle.prototype = Object.create(Shape.prototype);Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// trueconsole.log('Is rect an instance of Shape?', rect instanceof Shape);// truerect.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); // inheritmixin(MyClass.prototype, OtherSuperClass.prototype); // mixin

MyClass.prototype.myMethod = function() { // do a thing};

What is strict mode in JS ?

Strict mode makes several changes to normal JavaScript semantics.

First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform

optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.

Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript

// Whole-script strict mode syntax "use strict";

Page 15 of 44

Page 16: JS FAQ Mozilla

var v = "Hi! I'm a strict mode script!";

Strict mode for functions

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.function strict(){ // Function-level strict mode syntax 'use strict'; function nested() { return "And so am I!"; } return "Hi! I'm a strict mode function! " + nested();}function notStrict() { return "I'm not strict."; }

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!'");

How to inherit methods ?

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.var o = { a: 2, 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);

Page 16 of 44

Page 17: JS FAQ Mozilla

// p is an object that inherits from o

p.a = 12; // creates an own property 'a' on pconsole.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() { 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

Page 17 of 44

Page 18: JS FAQ Mozilla

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 ---> nullconsole.log(b.a); // 1 (inherited)

var c = Object.create(b);// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);// d ---> nullconsole.log(d.hasOwnProperty); // undefined, because d doesn't inherit from Object.prototype

With the class keywordECMAScript 6 introduced a new set of keywords implementing classes. Although these constructs look like those familiar to developers of class-based languages, they are not the same. JavaScript remains prototype-based. The new keywords include class, constructor, static, extends, and super."use strict";

class Polygon { constructor(height, width) { this.height = height; this.width = width; }}

class Square extends Polygon { constructor(sideLength) { 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 }

Page 18 of 44

Page 19: JS FAQ Mozilla

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

Here's a slightly more interesting example — a makeAdder function:function makeAdder(x) { return function(y) { return x + y; };}

var add5 = makeAdder(5);var add10 = makeAdder(10);

console.log(add5(2)); // 7console.log(add10(2)); // 12

Strict equality ===

var num = 0;var obj = new String("0");var str = "0";

Page 19 of 44

Page 20: JS FAQ Mozilla

var b = false;

console.log(num === num); // trueconsole.log(obj === obj); // trueconsole.log(str === str); // true

console.log(num === obj); // falseconsole.log(num === str); // falseconsole.log(obj === str); // falseconsole.log(null === undefined); // falseconsole.log(obj === null); // falseconsole.log(obj === undefined); // false

What is ==

var num = 0;var obj = new String("0");var str = "0";var b = false;

console.log(num == num); // trueconsole.log(obj == obj); // trueconsole.log(str == str); // true

console.log(num == obj); // trueconsole.log(num == str); // trueconsole.log(obj == str); // trueconsole.log(null == undefined); // true

// both false, except in rare casesconsole.log(obj == null);console.log(obj == undefined);

What is Call function ?

The call() method calls a function with a given this value and arguments provided individually.

Using call to chain constructors for an objectYou can use call to chain constructors for an object, similar to Java. In the following example, the constructor for the Product object is defined with two parameters, name and price. Two other functionsFood and Toy invoke Product passing this and name and price. Product initializes the properties nameand price, both specialized functions define the category.function Product(name, price) { this.name = name; this.price = price;

if (price < 0) { throw RangeError('Cannot create product ' + this.name + ' with a negative price'); }}

Page 20 of 44

Page 21: JS FAQ Mozilla

function Food(name, price) { Product.call(this, name, price); this.category = 'food';}

function Toy(name, price) { Product.call(this, name, price); this.category = 'toy';}

var cheese = new Food('feta', 5);var fun = new Toy('robot', 40);Using call to invoke an anonymous functionIn this purely constructed example, we create an anonymous function and use call to invoke it on every object in an array. The main purpose of the anonymous function here is to add a print function to every object, which is able to print the right index of the object in the array. Passing the object as thisvalue was not strictly necessary, but is done for explanatory purpose.var animals = [ { species: 'Lion', name: 'King' }, { species: 'Whale', name: 'Fail' }];

for (var i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i);}Using call to invoke a function and specifying the context for 'this'In below example, when we will call greet the value of this will be bind to object i. 

function greet() { var reply = [this.person, 'Is An Awesome', this.role].join(' '); console.log(reply);}

var i = { person: 'Douglas Crockford', role: 'Javascript Developer'};

greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer

Page 21 of 44

Page 22: JS FAQ Mozilla

What is Apply method in function

The apply() method calls a function with a given this value and arguments provided as an array (or anarray-like object).

Using apply to chain constructorsYou can use apply to chain constructors for an object, similar to Java. In the following example we will create a global Function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list.Function.prototype.construct = function (aArgs) { var oNew = Object.create(this.prototype); this.apply(oNew, aArgs); return oNew;};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 functionsClever 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 arrayvar numbers = [5, 6, 2, 3, 7];

// using Math.min/Math.max applyvar max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...)// or Math.max(5, 6, ...)

Page 22 of 44

Page 23: JS FAQ Mozilla

var min = Math.min.apply(null, numbers);

// vs. simple loop based algorithmmax = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; }}But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:function minOfArray(arr) { var min = Infinity; var QUANTUM = 32768;

for (var i = 0, len = arr.length; i < len; i += QUANTUM) { var submin = Math.min.apply(null, arr.slice(i, Math.min(i+QUANTUM, len))); min = Math.min(submin, min); }

return min;}

var min = minOfArray([5, 6, 2, 3, 7]);Using apply in "monkey-patching"

Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Givensomeobject.foo function, you can modify the function in a somewhat hacky way, like so:var originalfoo = someobject.foo;someobject.foo = function() { // Do stuff before calling function console.log(arguments); // Call the function as it would have been called normally: originalfoo.apply(this, arguments); // Run stuff after, here.}

What is bind parameter in function ?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Page 23 of 44

Page 24: JS FAQ Mozilla

Creating a bound function

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:this.x = 9; var module = { x: 81, getX: function() { return this.x; }};

module.getX(); // 81

var retrieveX = module.getX;retrieveX(); // returns 9 - The function gets invoked at the global scope

// Create a new function with 'this' bound to module// New programmers might confuse the// global var x with module's property xvar boundGetX = retrieveX.bind(module);boundGetX(); // 81Partially applied functions

The next simplest use of bind() is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.function list() { return Array.prototype.slice.call(arguments);}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argumentvar leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]

var list3 = leadingThirtysevenList(1, 2, 3);// [37, 1, 2, 3]With setTimeout

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 secondLateBloomer.prototype.bloom = function() {

Page 24 of 44

Page 25: JS FAQ Mozilla

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' methodBound 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*/);

var axisPoint = new YAxisPoint(5);axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // trueaxisPoint instanceof YAxisPoint; // truenew Point(17, 42) instanceof YAxisPoint; // true

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

Page 25 of 44

Page 26: JS FAQ Mozilla

// (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 examplevar unboundSlice = Array.prototype.slice;var slice = Function.prototype.apply.bind(unboundSlice);

// ...

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))); };

Page 26 of 44

Page 27: JS FAQ Mozilla

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.

A Promise is in one of these states: pending: initial state, not fulfilled or rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed.

As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained—an operation called composition.

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.

Page 27 of 44

Page 28: JS FAQ Mozilla

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() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); } );

// We define what to do when the promise is resolved/fulfilled with the then() call, // and the catch() method defines what to do if the promise is rejected. p1.then( // Log the fulfillment value function(val) { log.insertAdjacentHTML('beforeend', val + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); }) .catch( // Log the rejection reason function(reason) { console.log('Handle rejected promise ('+reason+') here.'); });

log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise made (<small>Sync code terminated</small>)<br/>');}

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';

Page 28 of 44

Page 29: JS FAQ Mozilla

// A-> $http function is implemented in order to follow the standard Adapter patternfunction $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++) { 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);

Page 29 of 44

Page 30: JS FAQ Mozilla

}, '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 payloadvar mdnAPI = 'https://developer.mozilla.org/en-US/search.json';var payload = { 'topic' : 'js', 'q' : 'Promise'};

var callback = { 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...inWarning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

Page 30 of 44

Page 31: JS FAQ Mozilla

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}; for (var prop in obj) { console.log("obj." + prop + " = " + obj[prop]);}

// Output:// "obj.a = 1"// "obj.b = 2"// "obj.c = 3"

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 31 of 44

Page 32: JS FAQ Mozilla

The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, String,TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Iterating over an Array:let iterable = [10, 20, 30];

for (let value of iterable) { console.log(value);}// 10// 20// 30You can use const instead of let too, if you don't modify the variable inside the block.let iterable = [10, 20, 30];

for (const value of iterable) { console.log(value);}// 10// 20// 30Iterating over a String:let iterable = "boo";

for (let value of iterable) { console.log(value);}// "b"// "o"// "o"Iterating over a TypedArray:let iterable = new Uint8Array([0x00, 0xff]);

for (let value of iterable) { console.log(value);}// 0// 255Iterating over a Map:let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let entry of iterable) { console.log(entry);}// [a, 1]// [b, 2]// [c, 3]

for (let [key, value] of iterable) { console.log(value);}// 1

Page 32 of 44

Page 33: JS FAQ Mozilla

// 2// 3Iterating over a Set:let iterable = new Set([1, 1, 2, 2, 3, 3]);

for (let value of iterable) { console.log(value);}// 1// 2// 3Iterating 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 () {};

let iterable = [3, 5, 7];iterable.foo = "hello";

for (let i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"}

Page 33 of 44

Page 34: JS FAQ Mozilla

for (let i of iterable) { console.log(i); // logs 3, 5, 7}

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 thisUntil 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);}

var p = new Person();In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.function Person() { var self = this; // Some choose `that` instead of `self`. // Choose one and be consistent. self.age = 0;

setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000);

Page 34 of 44

Page 35: JS FAQ Mozilla

}Alternatively, a bound function could be created so that the proper this value would be passed to thegrowUp() function.Arrow functions capture the this value of the enclosing context, so the following code works as expected.function Person(){ this.age = 0;

setInterval(() => { this.age++; // |this| properly refers to the person object }, 1000);}

var p = new Person();

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); // truevar x = 3;

/** * Example 2 */// will return a value of undefinedvar myvar = "my value"; (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); // truex = 3; /** * Example 2 */var myvar = "my value"; (function() { var myvar;

Page 35 of 44

Page 36: JS FAQ Mozilla

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.

\

ccepted

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 alert(typeof TestVar); //shows undefinednull 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 objectFrom 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 // trueand

null = 'value' // ReferenceError undefined = 'value' // 'value'

Q )Difference between call and apply ?

We can differentiate call and apply methods as below

CALL : A function with argument provide individually. If you know the arguments to be passed or there are no argument to pass you can use call.

APPLY : Call a function with argument provided as an array. You can use apply if you don't know how many argument are going to pass to the function.

There is a advantage of using apply over call, we don't need to change the number of argument only we can change a array that is passed.

There is not big difference in performance. But we can say call is bit faster as compare to apply because an array need to evaluate in apply method.

Event Bubling and Capturing in JS

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.

Page 36 of 44

Page 37: JS FAQ Mozilla

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.

How to define a class ?

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Polygon" here).class Polygon { constructor(height, width) { this.height = height; 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.// unnamedvar Polygon = class { constructor(height, width) { this.height = height; this.width = width; }};

// namedvar 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

Page 37 of 44

Page 38: JS FAQ Mozilla

See also method definitions.class Polygon { constructor(height, width) { this.height = height; this.width = width; } get area() { 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 extendsThe 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.'); }}

Page 38 of 44

Page 39: JS FAQ Mozilla

class Dog extends Animal { speak() { console.log(this.name + ' barks.'); }}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); // falseconsole.log(mapped instanceof Array); // trueSuper class calls with superThe 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 { speak() { super.speak(); console.log(this.name + ' roars.');

Page 39 of 44

Page 40: JS FAQ Mozilla

}}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

Arrays and methods

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.Create an Arrayvar fruits = ["Apple", "Banana"];

console.log(fruits.length);// 2Access (index into) an Array itemvar first = fruits[0];// Apple

var last = fruits[fruits.length - 1];// BananaLoop over an Arrayfruits.forEach(function (item, index, array) { console.log(item, index);});// Apple 0// Banana 1Add to the end of an Arrayvar newLength = fruits.push("Orange");// ["Apple", "Banana", "Orange"]Remove from the end of an Arrayvar last = fruits.pop(); // remove Orange (from the end)// ["Apple", "Banana"];Remove from the front of an Arrayvar first = fruits.shift(); // remove Apple from the front// ["Banana"];

Page 40 of 44

Page 41: JS FAQ Mozilla

Add to the front of an Arrayvar newLength = fruits.unshift("Strawberry") // add to the front// ["Strawberry", "Banana"];Find the index of an item in the Arrayfruits.push("Mango");// ["Strawberry", "Banana", "Mango"]

var pos = fruits.indexOf("Banana");// 1Remove an item by Index Positionvar removedItem = fruits.splice(pos, 1); // this is how to remove an item// ["Strawberry", "Mango"]Copy an Arrayvar shallowCopy = fruits.slice(); // this is how to make a copy// ["Strawberry", "Mango"]

What is difference between splice and slice ?

1. The splice() method returns the removed item(s) in an array and slice() method returns the

selected element(s) in an array, as a new array object.

2. The splice() method changes the original array and slice() method doesn’t change the original array.

3. The splice() method can take n number of arguments:

Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

Argument 3…n: Optional. The new item(s) to be added to the array.

123456789101112

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.

Page 41 of 44

Page 42: JS FAQ Mozilla

1314151617181920212223242526272829303132333435

 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]

If Argument(1) is NaN, it is treated as if it were 0.

123456

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]

If Argument(2) is less than 0 or equal to NaN, it is treated as if it were 0.

123456789101112

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 Array’s length, either argument will use the Array’s length.

Page 42 of 44

Page 43: JS FAQ Mozilla

123456789101112

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() method can take 2 arguments:

Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

123456789101112131415161718192021

var array=[1,2,3,4,5]console.log(array.slice(2));// shows [3, 4, 5], returned selected element(s). console.log(array.slice(-2));// shows [4, 5], returned selected element(s).console.log(array);// shows [1, 2, 3, 4, 5], original array remains intact. var array2=[6,7,8,9,0];console.log(array2.slice(2,4));// shows [8, 9] console.log(array2.slice(-2,4));// shows [9] console.log(array2.slice(-3,-1));// shows [8, 9] console.log(array2);// shows [6, 7, 8, 9, 0]

If either argument is NaN, it is treated as if it were 0.

123

var array3=[11,12,13,14,15];console.log(array3.slice(NaN,NaN));// shows [] 

Page 43 of 44

Page 44: JS FAQ Mozilla

456789

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 Array’s length, either argument will use the Array’s length

123456789101112

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]

I hope it helps, feel free to ask if you have any queries.

Page 44 of 44


Recommended