skip to Main Content

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


  1. fun() has to be fully evaluated before its return value can be passed back to the calling function.

    Since fun() includes console.log(m), m is logged first.

    Login or Signup to reply.
  2. When console.log('hello', fun()); is executed, both arguments need to be evaluated before console.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 to console.log. Only after this is the second log actually printed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search