javascript interview question #42

How exactly Math.max works in JavaScript? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In JavaScript, the function Math.max() accepts variable number of arguments and returns the biggest of them.

If you pass a couple of arrays into Math.max they will be first converted to strings and then into numbers:

console.log(Math.max([ 0 ], [ 1 ])); // 1
console.log(Math.max("0", "1"));     // 1
console.log(Math.max(0, 1));         // 1

Booleans will be also converted to numbers. true becomes one and false becomes zero:

console.log(Math.max(true, false));  // 1
console.log(Math.max(0, 1));         // 1

Now the condition inside of an if statement can be simplified and we can make sure we’re getting into the else branch:

if (1 > 1) { // false
  console.log('array won');
} else {
  console.log('array lost');
}

ANSWER: The string array lost will be logged to the console.