DEV Community

Julien Dephix
Julien Dephix

Posted on

Quiz: JavaScript

Hello, coders! πŸ’»

Quick quiz for you: what is the output of the code below and why?

const gender = 'M';
console.log("Hello " + gender === 'M' ? "Sir" : "Ma'am")
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
joolsmcfly profile image
Julien Dephix

Hey Luke. Thanks for your comment. As you said there was no bad intention, it was just a code example. I'll be more careful next time.

Above code would be better with template literals indeed but the point of the quiz was to show that codes doesn't always work like you think it will. I think I saw it when doing code review and thought it was worth sharing. :)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

"Hello " + gender != 'M'
The output is "Ma' am"

Collapse
 
joolsmcfly profile image
Julien Dephix

He shoots, he scores! πŸ‘Œ

One must know operator precedence to avoid gotchas like this one.

Collapse
 
frankwisniewski profile image
Frank Wisniewski

Tip:
Use Template strings

Thread Thread
 
joolsmcfly profile image
Julien Dephix

Yes of course, but the point was to question people’s knowledge.

console.log(`Hello ${gender === 'M' ? "Sir" : β€œMa'am"}`)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nombrekeff profile image
Keff

Haahah nice one! I remembered when I encountered this for the first time, took me a bit to wrap my head around it xD

Collapse
 
joolsmcfly profile image
Julien Dephix

Ha ha I can relate :)