2

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?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 1
    You want to understand the syntax of it or the logic? – matewka Feb 21 '14 at 15:34
  • possible duplicate of [What does the || operator do?](http://stackoverflow.com/questions/830618/what-does-the-operator-do) – cookie monster Feb 21 '14 at 15:36
  • 1
    It's just how the translation from Wisp syntax into JavaScript works to prevent runtime exceptions. If the expression were `(get x 1)` and the value of `x` were `undefined`, that would be an error in JavaScript, but not in ClojureScript (Wisp). – Pointy Feb 21 '14 at 15:37
  • I thought so. Then I can't explain it to you :) There's no purpose to `OR` a `[1,2,3]` array – matewka Feb 21 '14 at 15:37

3 Answers3

5

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 || [].

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • `||, does not return a boolean, it returns the 1st value` this just knocked me out right now – exebook Feb 21 '14 at 15:41
  • 1
    Yeah, that's one of the weird things about JavaScript (here are the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators). If you do `'abc' || 'xyz'`, you'll get `'abc'`. – gen_Eric Feb 21 '14 at 15:44
2

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

Here is more information on Truthy and Falsey vaues

musefan
  • 47,875
  • 21
  • 135
  • 185
1

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.

Ian
  • 33,605
  • 26
  • 118
  • 198