I was doing the lessons of Javascript. Here is the link: 6.Practice Good Scoping (Lesson- Scope).
In this piece of code the output should be as follows:
Northern Lights
Moonlight
undefined
but the output is:
Northern Lights
Moonlight
Therefore I want to know what is the reason behind such an output as in the previous it was told that if we don’t use the return statement we will get undefined
as one the output as the function is not returning any output.
THANK YOU
Assuming your code from the lesson looks similar to this:
const logVisibleLightWaves = () => {
const lightWaves = 'Moonlight';
let region = 'The Arctic';
// Add if statement here:
if (region === 'The Arctic'){
let lightWaves = 'Northern Lights';
console.log(lightWaves);
};
console.log(lightWaves);
};
logVisibleLightWaves(); //This is where the function is called
When the function is called the values you have shown as output are logged to the console by the function. The value ‘undefined’ is returned to the caller. The caller in this case is the line of code that invoked or called the function (see my comment in the code above). Since the caller does nothing with the return value, we don’t see it. If you wanted to see the return value logged to the console, you could change the caller to this:
console.log(logVisibleLightWaves());
This will invoke the function which will log the values to the console, and then return ‘undefined’ to the caller which will then also be logged to the console. Hope that made sense.
1 Like