What is the behavior of the variables here, i.e. closure. The output is "undefined" which I don't understand.
var x = 21;
var test = function () {
console.log(x); // output: undefined
var x = 20;
};
test();
Javascript creates a global execution context initially and a new execution context every time a function is pushed on the call stack. This happens in two phases: it first creates a variable environment where every variable is stored in a key, value pair of variable_name: undefined (whereas the functions are stored with the function definitions). It then starts executing the code line by line.
If I were to walk through this example: Global execution context: Variable Environment { x: undefined, test: function definition for test }
Then the code is executed line by line and 21 replaces undefined for the value of x. Now test is called, so a new execution context is created
Test's execution context: { x: undefined }
Now, when it starts executing the code, it looks for x within this execution context and sees the value is undefined, and logs it. If x wasn't present in test, it would have looked at the function's parent's execution context, which happens to be the global execution context, and would have logged 21.
Read up on execution context: https://www.javascripttutorial.net/javascript-execution-context/ Then read up on lexical scope to understand this behavior.
Javascript engine will explain your code like this:
var x = 21;
var test = function () {
var x;
console.log(x); // output: undefined
x = 20;
};
test();
You forget to put parameter in function test the code should be like this:-
var x = 21;
var test = function (x) { //here u should put parameter "x"
console.log(x); // The output from calling method
var x = 20; //last "x"
//if u want to get the value of last "x" should call
console.log(x); // the value of of last "x"
};
test(x); //here u should put parameter "x"
in code i explain every thing 😉
Notes:- Variables defined with let cannot be Redeclared. Variables defined with let must be Declared before use. Variables defined with let have Block Scope. Redeclaring a variable with let, in another block, IS allowed but with var Not-allowed