A few things I’ve learned about javascript

Aysha Williams
1 min readJun 28, 2019

--

Mostly that it’s weird and amazing!

true && 15

A few months ago, I worked on a piece of code that was something like:

isRaining() && getCalendarYear()

The first part of the condition evaluated to either true or false and the second half of the condition evaluated to a number.

My assumption was that due to the truthy/falsely evaluation of javascript, the result would be true, but it was a number!

So, true && 15 will return 15.

To return true, as I was expecting, I coerced the number returned by getCalendarYear() into a boolean by using double bangs:

isRaining() && !!getCalendarYear() 
// try true && !!15 and see what you get

[“”].join() == [“”]

This statement will evaluate to true, and so will "" == [""]. And also,
[“hi”, “hello”].join() == [“hi,hello”].

I forgot the context around this piece of code, but the expectation was for this statement to return false. An array isn’t a string after all (calling .join() on an array converts the elements in the array into a string delimited by commas).

Triple equals is here to the rescue! Triple equals will do a strict comparison, returning false as expected: [""].join() === [""].

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Aysha Williams
Aysha Williams

No responses yet

Write a response