Javascript Brain Teaser


Brain Teaser related to javascript scope

If code above is executed, what is the console output?

var text = 'outside';

function logIt(){
    console.log(text);
    var text = 'inside';
};
logIt();

Answer:

If your answer is 'outside' or 'inside' then your answer is wrong. The correct answer is 'undefined'.

Just to make sure, if your answer is the answer is ~Error~, then your answer is also wrong, because an error is not the same with 'undefined'

So how does this happen?

It is because javascript split the declaration and initialization of variables, then it raised the declaration to the top of current scope.

So this kind of code:
function logIt(){
    console.log(text);
    var text = 'inside';
};

If we split the the declaration and hoisted it, The code will be translated to:
function logIt(){
    var text;
    console.log(text);
    text = 'inside';
};
Now if you at the code, the console.log(text) will be executed right after the variable declaration. That is why you get 'undefined'

Aditya

Computer Science Student. I have just graduated from Binus University. Currently pursuing master degree from Harbin Institute of Technology Shenzhen Graduate School.

0 comments: