Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal first or second in concatenation?

Tags:

javascript

In JavaScript, is there any circumstance where there is a semantic difference between these two options?

foo.bar + '' 

...and...

'' + foo.bar 

I would've expected the latter to more reliably coerce the result to a string, but I can't find any discussion of this (after much Googling) nor any example where it seems to matter.

like image 240
VoteyDisciple Avatar asked Jul 27 '18 19:07

VoteyDisciple


People also ask

Which is the correct way to concatenate 2 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What is string literal concatenation?

Concatenate string literals in C/C++ A string literal is a sequence of characters, enclosed in double quotation marks (" ") , which is used to represent a null-terminated string in C/C++. If we try to concatenate two string literals using the + operator, it will fail.

Why is string concatenation N 2?

String concatenation It can be a bit surprising, but this code actually runs in O(N2) time. The reason is that in Java strings are immutable, and as a result, each time you append to the string new string object is created.


1 Answers

Both are the same.

There is only a difference if there are other + (on the left or the right). In other words:

1 + 1 + ''                          // results in '2' 

Is not the same as:

'' + 1 + 1                          // results in '11' 
like image 77
ibrahim mahrir Avatar answered Sep 20 '22 16:09

ibrahim mahrir