0

Why this works, I don't know. And I can't figure out any combination of words to describe what it is, so I can hardly Google it.

apple = 
banana = 
orange = true;

console.log(banana); //true

What is this weird JavaScript shorthand and why does it work?

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 1
    Might help to put all assignments in just one line. – Hanlet Escaño Nov 10 '14 at 04:49
  • @CuriousProgrammer: Then why did you put "this" in quotes? – Bergi Nov 10 '14 at 04:53
  • @Bergi Could you re-title my question appropriately? From these answers I see that it isn't short-hand, but I'm unsure how to best title it for others looking for it to find the answer. –  Nov 10 '14 at 05:02

4 Answers4

1

An assignment is just an expression in javascript, and yields the right-hand-side value. So your snippet is parsed as

(apple = (banana = (orange = (true))));

and has (approximately1) the same effect as

orange = true;
banana = true;
apple = true;
// (since the literal `true` has no side effects when being evaluated)

There's nothing special about the value being boolean.

1: Well, it's not exactly the same. The edge cases are insignificant however.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

Edited after clarification

apple = banana = orange = true;

As far as I understand value true is assigned to orange, value of orange is assigned to banana, value of banana is assigned to apple.

Kamal
  • 161
  • 5
0

What you're doing is assigning multiple variables to the same value. It pretty much just says "apple is equal to banana, which is equal to orange, which is equal to true".

This works because of the way assignments are defined in ECMA Script (#11.13.1). To simplify it a lot, assigning a variable (an AssignmentExpression) needs to be of the form:

LeftHandSide = AssignmentExpression

Since it has another AssignmentExpression at the end, that can be expanded to give you

LeftHandSide = LeftHandSide = AssignmentExpression

This is known as a Recursive Grammar Definition. This is within the field of language and context-free grammar definition. If you study compilers, this comes up as well.

southrop
  • 699
  • 8
  • 17
-1

This is called semicolon insertion in java script ,there are sevaral rules which javascript uses to check the line is a valied js statement. you can read more here.. For example ,

function multiply(a, b) {
    return
    a * b;
}

returns undefined because "return" is a valid js statement. so it becomes ,

function multiply(a, b) {
    return;
    a * b;
}

But your code is similer to

apple = banana = orange = true;

Even though they are in different lines

Jayantha Lal Sirisena
  • 20,611
  • 10
  • 65
  • 90