Skip to content

Another WTF Javascript Moment

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`
Code language: JavaScript (javascript)

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

// The code: [] == false // The result: // `true`
Code language: JavaScript (javascript)

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?

See also  How to Format Numbers by Prepending 0 to single-digit numbers in Javascript
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x