function greet(name) {
let hours = 11;
let time = "";
if (hours >= 4 && hours < 12) {
time = "Good Morning";
} else {
time = "hi";
}
return `${time}, ${name}`;
}
greet("Ali");
The output is correct. It output is "Good morning, Ali"
But when I change the the return statement, just like below. It returns " , Ali"
.
function greet(name) {
let hours = 11;
let time = "";
let result = `${time}, ${name}`;
if (hours >= 4 && hours < 12) {
time = "Good Morning";
} else {
time = "hi";
}
return result;
}
greet("Ali");
Could anyone please explain this?
2
Answers
The difference is when you use the variable
time
(the naming of which is somewhat ironic in this case). Look at the first code:Now look at the second example:
See how you’re using the value before you’ve set the value? You’ve reversed those two steps. Un-reverse them:
If your expectation is that the use of a variable will automatically re-calculate itself if that variable ever changes, that expectation is false. This line of code executes once:
After it’s executed, the result is stored in the variable
result
. Iftime
orname
ever change, the system isn’t going to go back to this line of code and execute it again. The value inresult
never changes.The reason for the different outputs in your two versions of the
greet
function is the order of your code execution and the way JavaScript works.In the first version, you set the
time
variable based on thehours
condition before creating theresult
variable. So, when you return${time}, ${name}
, it correctly evaluates thetime
variable to "Good Morning" and then combines it withname
.In the second version, you set the
result
variable before you set thetime
variable. Therefore,time
is still an empty string when you createresult
, and it stays that way because the conditional statement that setstime
to "Good Morning" or "hi" only happens afterresult
has been assigned. As a result,result
is initialized with an empty string followed byname
, which is why you get " , Ali."To fix this issue in the second version, you should move the creation of
result
after the conditional statement that sets thetime
variable to "Good Morning" or "hi." This way, thetime
variable will have the correct value before you createresult
, resulting in the desired output of "Good Morning, Ali."