1

Possible Duplicate:
In Javascript, what does it mean when there is a logical operator in a variable declaration?

Just a quick question. When I declare a variable like this:

    var ballctx = ctx['ballctx'] || createCanvas('game-screen', 'ballctx');

Does it try the left first or the right first? I want it to create a new canvas if ctx of ballctx does not exist. If it does, it use that instead.

Community
  • 1
  • 1
  • it tries the left first, if it doesn't exist the right one is used. like `var ballctx = (ctx['ballctx']?ctx['ballctx']:createCanvas('game-screen','ballctx')` – Moritz Roessler Sep 10 '12 at 12:43

6 Answers6

5

The left first. || uses what is called short-circuit evaluation, also known as minimal evaluation, meaning it will only evaluate the right side of the expression, if the left side is false.

From the ECMAScript Language Specification:

11.11. Binary Logical Operators

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalORExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is true, return lval.
  4. Let rref be the result of evaluating LogicalANDExpression.
  5. Return GetValue(rref).

Thus, in your expression:

ctx['ballctx'] || createCanvas('game-screen', 'ballctx');
^-- lval          ^-- rval

If lval evaluates to true, rval won't be evaluated. In other words, you'll only create a new canvas if ctx['ballctx'] evaluates to false, so your code is correct.

João Silva
  • 89,303
  • 29
  • 152
  • 158
2

Left first. If the implicit cast to boolean fails then right.

Newton
  • 31
  • 4
1

It tries the left one, if its true it will not execute the function on the right.

1

If ctx['ballctx'] is truthy then

  • createCanvas('game-screen', 'ballctx') does not get evaluated
  • ctx['ballctx'] is assigned to ballctx

otherwise

  • createCanvas('game-screen', 'ballctx') is evaluated
  • whatever createCanvas returns gets assigned to ballctx
codebox
  • 19,927
  • 9
  • 63
  • 81
1

The value of the left expression is taken if approximately equal to true, otherwise the value of the right expression is taken regardless of value. In some older browsers, as per the well outdated JavaScript 1.1 spec, only true or false is returned.

See MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators#Summary

lpd
  • 2,151
  • 21
  • 29
0

Left first. If left is false or undefined then only function will be executed.