Tutorial by Examples

(Note: All examples using let are also valid for const) var is available in all versions of JavaScript, while let and const are part of ECMAScript 6 and only available in some newer browsers. var is scoped to the containing function or the global space, depending when it is declared: var x = 4; /...
When a function is declared, variables in the context of its declaration are captured in its scope. For example, in the code below, the variable x is bound to a value in the outer scope, and then the reference to x is captured in the context of bar: var x = 4; // declaration in outer scope funct...
What is hoisting? Hoisting is a mechanism which moves all variable and function declarations to the top of their scope. However, variable assignments still happen where they originally were. For example, consider the following code: console.log(foo); // → undefined var foo = 42; console.log(fo...
Let's say we need to add a button for each piece of loadedData array (for instance, each button should be a slider showing the data; for the sake of simplicity, we'll just alert a message). One may try something like this: for(var i = 0; i < loadedData.length; i++) jQuery("#container&q...
Invoking a function as a method of an object the value of this will be that object. var obj = { name: "Foo", print: function () { console.log(this.name) } } We can now invoke print as a method of obj. this will be obj obj.print(); This will thus log: Foo...
Invoking a function as an anonymous function, this will be the global object (self in the browser). function func() { return this; } func() === window; // true 5 In ECMAScript 5's strict mode, this will be undefined if the function is invoked anonymously. (function () { "use...
When a function is invoked as a constructor with the new keyword this takes the value of the object being constructed function Obj(name) { this.name = name; } var obj = new Obj("Foo"); console.log(obj); This will log { name: "Foo" }
6 When using arrow functions this takes the value from the enclosing execution context's this (that is, this in arrow functions has lexical scope rather than the usual dynamic scope). In global code (code that doesn't belong to any function) it would be the global object. And it keeps that way, eve...
The apply and call methods in every function allow it to provide a custom value for this. function print() { console.log(this.toPrint); } print.apply({ toPrint: "Foo" }); // >> "Foo" print.call({ toPrint: "Foo" }); // >> "Foo" You mig...
The bind method of every function allows you to create new version of that function with the context strictly bound to a specific object. It is specially useful to force a function to be called as a method of an object. var obj = { foo: 'bar' }; function foo() { return this.foo; } fooOb...

Page 1 of 1