Narbhakshi
Narbhakshi

Reputation: 392

Why function is executed first in console.log?

Have a look at this snippet:

let first = 1;

function second() {
  console.log(2);
}

console.log(first, second()); // 2 1

I expect it to print 1 2 in order instead of 2 1. Why function second is executed first? I observe if both the arguments to console.log are functions, the order in which they are passed is preserved(see below example)

function first() {
  console.log(1);
}

function second() {
  console.log(2);
}

console.log(first(), second()); // 1 2

Please explain this behavior with relevant resources.

Upvotes: 3

Views: 1513

Answers (2)

suspectus
suspectus

Reputation: 17288

The post is a bit misleading because the comment suggests the output is 2 1.

console.log(first, second()); // 2 1

But what is actually output is:

2
1 undefined

We get 2 output first, because console.log(first, second()) calls second() and this outputs 2 in console.log.

Note that the function second() returns nothing. If a return value is omitted from a function, undefined is returned instead.

Then console.log(first, undefined) is evaluated and we get the output

1 undefined

Note that if second() returned a value (say 3 for example):

let first = 1;
function second() {
   console.log(2);
   return 3;
} 
console.log(first, second());

Then the output is

2
1 3

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371069

All arguments in an argument list are evaluated before the function containing the argument list is called. So

someFn(first(), second());

will always call first, then call second (along with any other arguments), until it comes up with intermediate values like

someFn(firstResultExpression, secondResultExpression);

at which point someFn will be called with those (now resolved) expressions.

In this case, someFn happens to be console.log. So if first() and second() log anything themselves, those logs will always appear first, before the last someFn starts doing anything.

Upvotes: 5

Related Questions