Quiz: JavaScript
Julien Dephix

Julien Dephix @joolsmcfly

About: Been programming for over 20 years and loving it!

Location:
France
Joined:
Jun 24, 2022

Quiz: JavaScript

Publish Date: Jun 28 '22
2 9

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

Comments 9 total

  • Frank Wisniewski
    Frank WisniewskiJun 28, 2022

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

    • Julien Dephix
      Julien DephixJun 28, 2022

      He shoots, he scores! 👌

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

      • Frank Wisniewski
        Frank WisniewskiJun 28, 2022

        Tip:
        Use Template strings

        • Julien Dephix
          Julien DephixJun 28, 2022

          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
  • Keff
    KeffJun 28, 2022

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

  • Julien Dephix
    Julien DephixJun 29, 2022

    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. :)

Add comment