Closure(Script) implementation in JavaScript called "wisp" has this snippet:
(get [1 2 3] 1) ; => ([1, 2, 3] || 0)[0]
which means that the wisp code compiles to this in JavaScript:
([1, 2, 3] || 0)[0]
But why is || 0
part there?
Closure(Script) implementation in JavaScript called "wisp" has this snippet:
(get [1 2 3] 1) ; => ([1, 2, 3] || 0)[0]
which means that the wisp code compiles to this in JavaScript:
([1, 2, 3] || 0)[0]
But why is || 0
part there?
My guess is that instead of writing a literal array, you can send it a variable:
(get x 1) ;
So the || 0
is used in case x
is null
or undefined
.
In JavaScript, ||
does not return a boolean, it returns the 1st value if it's "truthy" and the 2nd if the 1st is "falsy".
0[0]
returns undefined
just like [][0]
does. 0
is one less character than []
, so that's probably why they did || 0
instead of || []
.
Normally it would be used to specify a default value if the first part is null/undefined/false.
For example, consider the following code:
var a = 1;
var b;
var x = a || 0;//if a is true use a, otherwise use 0
var y = b || 0;//if b is true use b, otherwise use 0
The value of x
will be 1
, because 1
is a truthy value and therefore becomes the value that is used. whereas y
will be 0
because the value of b
is undefined (a falsey value) so the 0
is used instead.
In your example however it is pointless, as [1, 2, 3]
will always be true. But if you was using a variable then is would be possible for the variable to not be assigned, so the default value would then apply.
Here is an example that shows how different types would apply
I don't believe that the || 0
does anything. The ||
operator checks for a null, undefined etc, and if found will return the right hand side of the expression.
In this example [1, 2, 3]
is never null so 0
will never be returned.