0

I am trying to understand how the following java script code works. I have global variable called color that stores 'blue'; I am calling printColor() that simple prints the color. What i don't understand is why the color is undefined when i am defining a new local variable called color in the function. If you uncomment the local color variable declaration below, the color is undefined.

var color = 'blue';

printColor();

function printColor(){
  document.write(color);
  //var color = "green";
}
2
  • 1
    Variable hoisting: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Why would you use the variable before you define it? If you uncomment that line, your function's code is effectively: var color; document.write(color); color = "green";. You're redefining a local color variable, and it's being hoisted Commented Jun 27, 2014 at 4:46
  • Sure, when that var color = "green"; line is commented out. That's fine, when document.write(color) executes, it looks in the current scope and doesn't find a color variable. So it looks up the scope chain and finds it in the parent scope, so it can print "blue". When you redeclare a local variable by the same name, it shadows the parent scope's variable, and hoisting is causing problems. I edited my last comment with more stuff too Commented Jun 27, 2014 at 4:50

2 Answers 2

3

you are re-declaring variable color inside your printColor() function, since the declaration is actually hoisted to the top it overwrites it at the start of the function, hence you see undefined

var color = 'blue';

function printColor(){
  document.write(color);
  //var color = "green";
}
printColor();

but if you do:

function printColor(){
    document.write(color); //undefined
    var color = "green";
    console.log(color); //shows green
}
Sign up to request clarification or add additional context in comments.

3 Comments

I thought in java script, a function doesn't need to be defined before it gets called.
@user2383728 That's why this answer is wrong and irrelevant
@user2383728 updated my answer to actual reason
0

When you var color = 'green' in your printColor function, any reference to color variable in the function will refer to the local color variable, no matter where it sit in the function.

You were trying to write a local variable in your case. That's why it undefined. It's the way js work. I have no idea why it was made like that.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.