Ten things you probably do not know about JS(keep updating)


1. we need to understand scope chain and understand what outer execution we are referring to.

function a()

{

var v = 2;

b();

}

function b()

{

console.log(v);

}

var v = 1;

a();

 

result would be 1 instead of 2 because b and a and global variable are in the same execution context stack so function b is referring to global valuable var v = 1;

if we put function b inside of function a, we will have value 2 instead of 1 because function b is referring to the execution context of a.

 

2. Immediately Invoked function expression: run the function immediately when i create it using ()

var greeting = function(name){

return “Hi”+ name;

}(“Leo”);

javascript engine knows that inside a parenthesis is a expression. so we can write a function expression inside of parenthesis without naming it.

 

3. Functional statement and Functional expression

There are two different phrases.

Creation phrase is to put function and your variable which set to be undefined into memory.

When it executes, if you want to invoke your method, there exists a function in memory already so it does not matter that you invoke that above your function or below your function.

But it’s different to your variable because when it is in execution context, it will set it values you want replacing undefined with your value. So you cannot use that variable anywhere you want because you will have undefined when you use that variable above your valuable setting.

Same happens to function expression because it is a valuable of an object.

 

4. JavaScript Closure

function a(){

var arr = [];

for (var i = 0; i < 3; i++) {

arr.push(function(){

console.log(i);

});

}

return arr;

}

var fs = a();

fs[0]();

This example is a typical javascript closure.

when we assign function a to var fs, the function inside of for loop is executed. We are not executing the function inside of for loop because we are not calling it. so when we want to execute it, the value of I will be three, staying in memory after assigning function a to fs. (that is a feature of closure)

function a(){

var arr = [];

for (var i = 0; i < 3; i++) {

arr.push((function(j){

return function(){

console.log(j);

}

 

})(i));

}

return arr;

}

var fs = a();

fs[0]();

fs[1]();

fs[2]();

If we want to print zero, one, two, we need to create its own scope. Use immediately invoked expression because we lock the value of I inside of for loop and we pass i to j while for loop is running. Creating its own execution context is a best solution.

Social Media


Categories



All Posts



Contact Info