0
var x = 3;

if(1==1){
    if(2==2){
        var x= 5;       
    }
}

document.write(x); // outputs 5

So I was running some tests to understand the concept of local and global scope better. I thought declaring x with keyword var creates a local variable and ignores any variable with the same name in the parent scope. By ignore, I mean how I can change the variable x without affecting the same variable in the scope above it. But apparently my understanding of the definition of js variables is wrong. could please explain why it behaves so?

3
  • You understanding is correct, but since you are inside a if and not inside a function, both of your x have the same scope Commented Apr 25, 2018 at 15:31
  • conditions with if, and loops like for or while don't create their own scope in JS Commented Apr 25, 2018 at 15:32
  • w3schools.com/js/js_scope.asp Commented Apr 25, 2018 at 15:32

2 Answers 2

2

var declares a local variable inside a function. For block-scope local variables, use let.

var x = 3;
if(1==1){
    if(2==2){
        let x = 5;
    }
}
console.log(x); // prints 3
Sign up to request clarification or add additional context in comments.

Comments

0

Curly braces ({...}) does not create scope for var in JavaScript. So when you declare any variable (x) with the same name (x) in side {...} it does not create any new variable but actually override the previously declared variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.