kota's memex

type conversion

The type conversion rules and as stupid as they are complex.

console.log(8 * null)
// 0
console.log("5" - 1)
// 4
console.log("5" + 1)
// 51
console.log("five" * 2)
//NaN
console.log(false == 0)
// true
console.log(null == undefined)
// true
console.log(null == 0)
// false

In the first example null is converted to 0, then "5" is converted to 5, but in the next one the + instead causes the 1 to be converted to a string and concatenated. The last two examples are important because null or undefined will always produce false tested against any other value EXCEPT if they're tested against themselves. This is actually useful becuase you can compare a value with != null to see if it's a real value.

===

The triple equals is used to check if something is REALLY equal. Expressions like "" == false are true, but using "" === false will test if they are precisely equal. It's basically a good idea to always use the triple equal version.

logic operators

Operators || and && behave in strange ways during type conversions.

console.log(null || "user")
// user
console.log("Anges" || "user")
// Anges

The || operator will return the value to its left when that value can be converted to true and will return the value on its right otherwise. This functionality is often used to fall back on a default value. If you have a value that might be empty, you can put || after it with a replacement value.

The && is similar but the other way around. Then the value on its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.

Another strange property is that the value on the right is ONLY evaluated when necesarry. In the case of true || X where X crashes the program or something, it will simply return true without processing X. The same happens with false && X, if the first part is false the right side is ignored.