1

I am trying to understand some javascript code but didn't understand what is causing this behavior.

My code is simple:

test ="s" + ("locomotion","maintenance","ave");
alert(test);

When I execute the above code, the string returned is "save" in alert box. What is the significance of the above code? Why does joining strings take the last string with "s"?

What is this called and how does java-script select "ave" to join with "s"?

Thanks.

ahelpyguy
  • 45
  • 4
  • What are you actually trying to do? That's not how you join strings in JS, parenthesis just represent an expression to be evaluated. – skyline3000 Sep 21 '16 at 15:26
  • I found this code in one of the sample. When I am trying to test this using alert, it is returning "save" in alert box. So I want to understand how it used s + ave to return the string "save". why not first 1 or second string along with "s" ? – ahelpyguy Sep 21 '16 at 15:28

4 Answers4

1

The MDN says:

"The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

In your case the last operand was "ave"

Community
  • 1
  • 1
O_Z
  • 1,515
  • 9
  • 11
0

Your code works as expected. In the alert you get save and that is because you are joining the s and ave using the + operator.

In your expresion ("locomotion","maintenance","ave"), ave is selected, so you the operation you are performing is test = "s" + "ave", so you get save on the alert

Iván Rodríguez Torres
  • 4,293
  • 3
  • 31
  • 47
0

Here is how test is calculated:

"s" concatenated with ("locomotion", "maintenance", "ave");

"locomotion", "maintenance" is evaluated to "maintenance"
"maintenance", "ave" is evaluated to "ave"
("ave") is evaluated to "ave"

"s" + "ave" is evaluated to "save"

It happens because the , is an operator that take two parameters. It evaluated both operands and return the value of the second.

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

It's just a comma operator that returns the value of the last string as per your question. Please refer to this document as mentioned by Andreas.

Comma Operation

Neophile
  • 5,660
  • 14
  • 61
  • 107