6. Hoisting
var x = 3;
function print(){
console.log("Value",x);
var x=2;
}
print();
//Works for ‘var’, class, function etc only. ‘Let’ or ‘const’ not hoisted
7. F() expressions vs declarations// Function declaration
function add(num1, num2) {
return num1 + num2;
}
// Function expression do not hoist
var add = function (num1, num2) {
return num1 + num2;
};
8. Scope// Global Scope
function someFunction() {
// Local Scope #1
function someOtherFunction() {
// Local Scope #2
}
}
// Global Scope
function anotherFunction() {
// Local Scope #3
}
9. Closures
function greet() {
name = 'Hammad';
counter = 0;
return function () {
console.log('Hi ' + name);
}
}
greet(); // nothing happens, no errors
// the returned function from greet() gets saved in greetLetter
greetLetter = greet();
// calling greetLetter calls the returned function from the greet()
function
greetLetter();
10. The “this”
function foo () {
'use strict';
console.log("Simple function call")
console.log(”value of this from foo”,this);
}
let user = {
count: 10,
foo: foo,
foo1: function() {
console.log(‘value of this from
foo1’,this);
}
}
user.foo() // now “this” refers to user
object instead of global object.
let fun1 = user.foo1;
fun1() // Refers global object as this
method is invoked as a simple function.
user.foo1() // Prints user ref on console
as foo1 is invoked as a object’s method
11. Context changing with call()
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name: ${this.first_name}
${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John
Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul
Adams
person.displayName.call(person2); // Here we
are setting value of this to be person2 object
//Prints Name: Paul Adams
12. Call vs Apply
function introduce(name, interest) {
console.log('Hi! I'm '+ name +' and I like '+ interest +'.');
console.log('The value of this is '+ this +'.')
}
introduce('Hammad', 'Coding'); // the way you usually call it
introduce.call(window, 'Batman', 'to save Gotham'); // pass the arguments one by one after the
context
introduce.apply('Hi', ['Bruce Wayne', 'businesses']); // pass the arguments in an array after
the context
13. Context binding with bind()
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name:
${this.first_name} ${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul
Adams
let person2Display =
person.displayName.bind(person2); // Creates
new function with value of “this” equals to
person2 object
person2Display(); // Prints Name: Paul Adams