user3231622 user3231622 - 5 months ago 12x
Javascript Question

Javascript construct in concatenating strings

Below a simple piece of javascript is displayed:

var mystring = ("random","ignored","text","h") + ("ello world")

This string results in hello world. I have two questions:

  • how is the ("random","ignored","text","h") construct called (its not
    an array, because an array has different kind of brackets?)

  • Can someone technically explain why this string results in hello world? (i.e. why is only the "h" character in the construct taken into account?)


You're running into the little-known comma operator!

The parentheses and comma operator create a group of expressions that are evaluated in order, then return the last one. So ('foo', 'bar') will evaluate to just 'bar'. However, because each expression is evaluated, (foo(), bar()) will call both foo() and bar() before returning the value returned by bar().

Step by step, your code runs as:

var mystring = ("random","ignored","text","h") + ("ello world")
var mystring = "h" + ("ello world")
var mystring = "h" + "ello world"
var mystring = "hello world"

Many (or even most) languages have this operator, but it's rarely used. It can be helpful when using ES6 lambdas as the body of a reduce, like when you're turning an array into an object:

[{key: 'a', value: 1}, {key: 'b', value: 2}].reduce((p, c) => (p[c.key] = c.value, p), {})

I wouldn't necessarily suggest you use it often, since it can be confusing and there's often a more clear (if more verbose) way to do the same thing.