A few things I’ve learned about javascript
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() === [""]
.