Another WTF Javascript Moment

0 min read 137 words

Javascript is a powerful language, but sometimes it doesn’t always do what you expect it to.

Take the following expression for example. It’s a simple if statement that checks to see if true and then runs the code within the block.

Running the code results in the block being executed, however, when we directly compare the statement’s comparison against a false value, we can see that it is in fact, not actually true.

// The code:
if ([]) {
    console.log('hi');
}

// The result:
// `hi`

Ok, this clearly means that [] equates to true, so let’s double-check:

// The code:
[] == false

// The result:
// `true`

Turns out that while it actually is false, it is happy to report true when run through an expression.

How did this false value evaluate to being true?

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags