user3231622
user3231622

Reputation: 341

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:

Upvotes: 4

Views: 54

Answers (1)

ssube
ssube

Reputation: 48337

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.

Upvotes: 9

Related Questions