Reputation: 3
In JavaScript the execution of code takes in 2 phases. In first step it is read and the space is reserved for variables(given value undefined
initially) and functions. In the second phase it is executed line by line.
And also I read that the variables declared without var
keyword are set as Global
variables.
So if I print a variable before defining it inside a function, it should print undefined
. Like in the code below:
b();
console.log(a);
console.log(d);
var a = 'Hello World!';
function b() {
console.log(c);
console.log('Called b!');
var c = "variable c is printed";
console.log(c);
console.log(d);
d = "Variable d is printed";
}
I expect the output to be:
undefined
Called b!
variable c is printed
undefined
Variable d is printed
But I get the below output:
undefined
Called b!
variable c is printed
Uncaught ReferenceError: d is not defined
at b (app.js:12)
at app.js:1
So my doubt is, when function b
is called, then in the first phase of code execution, variable d
should be given space and value undefined
initially. And then the execution should begin line by line in the second phase.
Upvotes: 0
Views: 81
Reputation: 300
In first Phase When try to set space for Variables Find them by Keywords:
var/let/const
When you don't use it in second Phase crashed variables pointer where not exist space for them, In function scope d don't have any space and its a crash point.
this code show what happened:
console.log(a);
a = 'Some Value For A Variable';
to solve it two solution:
1- use Keywords
console.log(a);
var a = 'Some Value For A Variable';
2- Initializing First
a = 'Some Value For A Variable';
console.log(a);
The Best Clear Code is Complex of two Solution: * use keywords * call variables after definition
var a = 'Some Value For A Variable';
console.log(a);
Good Luck
Upvotes: 0
Reputation: 138267
And also I read that the variables declared without var keyword are set as Global variables.
Yes, kind of. What happens is that if you do an assignment, like
d = 1;
The engine goes up through all environment records (the place were values of variables are stored at runtime), so in your case it first goes to b
s record, and then to the global record. If it finds a variable binding (name -> value) in one of those records (which were created when execution starts, just as you said), it then stores the value there. However if it reaches the global record, and does not find a binding along the way (the variable is undeclared), it just creates a new binding at that global record.
So by the time you do console.log(d)
, no binding for d
exists, and accessing d
fails.
Upvotes: 3