-1

How does the fruit variable gets overwritten in the if block, but the color variable doesn't gets overwritten in the function block ?

var fruit = "apple";

if(fruit){
    var fruit = "mango";
    console.log(fruit); // mango
}

console.log(fruit); // mango

var color = "blue";

function displayColor(){
    var color = "red";
    console.log(color);
}

displayColor(); // red

console.log(color);  // blue

1 Answers1

1

The difference is the function creates a local scope. So it creates a variable in the function scope and discards it when the function is done, leaving the GLOBAL color variable untouched.

If statements dont make a scope, so your just redefining the fruit variable in global scope.

Trevor Blythe
  • 153
  • 1
  • 8