The tricky “falsy” values of Javascript
Because setting default values in Javascript can seem very simple… until you realise something’s wrong!
When you write code, you want your variables to have clearly defined values — you want to know what they are equal to at any given point in your program. The easy case is when you explicitly set a variable: if you say that a = 2
, then the value of a
is 2 (obviously). But what about variables you haven't explicitly set? (Or haven't explicitly set yet?) Those variables still have their default value.
The problem
There are various ways of initialising a variable and plenty of articles on the net to give you some shorthands. In Javascript, a well-known technique is to use the logical “or” operator, ||
, to override the default value when you initialise a variable. This is particularly neat when you have some default configuration and you want to override it with user-specific options.
For example, let’s say I’m writing a program to display geometric shapes. The idea is to show a square, a triangle and a circle on a row, either black or red, that are evenly spaced out. I have two settings I can tweak: the spacing
between the shapes and a useBlack
flag to tell whether to draw black or red shapes.