I have created a function that displays a parameter value via console.log() within it, and returns a value as well. So I played a bit, and called another console.log, where I’ve put two parameters, first being a string, and a second parameter being this function that I’ve created that has a console.log() in it. The output confuses me.
let fun = function (m = 5) {
console.log(m);
return 'hi';
};
console.log('hello', fun());
I expected the output to be ‘hello’ followed by 5 and then ‘hi’, but the actual output is 5 followed by ‘hello’ and ‘hi’. Please help, as this doesn’t make sense as it is. Thanks.
2
Answers
fun()
has to be fully evaluated before its return value can be passed back to the calling function.Since
fun()
includesconsole.log(m)
,m
is logged first.When
console.log('hello', fun());
is executed, both arguments need to be evaluated beforeconsole.log
can be called.The evaluation of
fun()
executes the code inside the function.console.log(m)
is called here, so this output is first. The return value ('hi'
) is then used as the second argument toconsole.log
. Only after this is the second log actually printed.