Please help me find out what is the problem.
In JavaScript, when all the variables declared with var
, will have the default value of undefined
unless explicitly something is assigned.
In your case,
var color = "Royal " + color;
you are using color
to define the variable color
itself. So,
"Royal " + color
will become
"Royal " + undefined
That is why the result is `Royal undefined.
Basically, the variable color
declared within the reality
shadows the variable, declared outside the scope of that function. So, you need to choose a different name.
var color = "Blue";
function reality() {
var realityColor = "Royal " + color;
console.log(realityColor);
}
reality();
will print
Royal Blue
Note: If you actually meant to modify the color
variable declared outside, then you should not define a variable called color
in reality
and instead, you should access it directly, like this
var color = "Blue";
function reality() {
color = "Royal " + color;
console.log(color);
}
reality();
But, this function doesn't return anything. To make it better, you can return the value and assign it the variable, like this
var color = "Blue";
function reality() {
return "Royal " + color;
}
color = reality();
console.log(color);