DEV Community

Cover image for JavaScript Interview Question #42: How Math.max works in JS
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

9 2

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

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

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay