-3

I'm learning programming with JavaScript, and I just don't know what's happening here:

let myVar = ('Hello','World!');
console.log(myVar);

The output is:

World!

2 Answers2

4

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

This means that the expression 'Hello','World!' evaluates to 'World!'

spender
  • 117,338
  • 33
  • 229
  • 351
  • One more thing to note: JavaScript doesn't use parentheses to as the literal syntax for any type of collection, so putting parentheses around that just ensures that it will be grouped as a single expression. – jirassimok Sep 26 '19 at 00:38
0

You're setting the variable to the string "Hello", then setting it to "World". The same thing happens if you set a list of variables inside a parenthetical.

const myVar = (1,2,3,4,5,6);
console.log(myVar);
//6

Where as I think what you were trying to do was use a grouping operator like +.

const myVar = ("Hello, " + "World")
console.log(myVar)
//"Hello, World"
technicallynick
  • 1,562
  • 8
  • 15