DEV Community

loading...
Cover image for JavaScript Interview Question #42: How Math.max works in JS

JavaScript Interview Question #42: How Math.max works in JS

Coderslang: Become a Software Engineer
Teaching you to code at js.coderslang.com - JavaScript, HTML, CSS, Node.js, React.js, React Native
Originally published at learn.coderslang.com ・1 min read

coderslang 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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

Read more JavaScript Tutorials or Learn Full-Stack JavaScript

Discussion (0)