-1

I want to know what is happening behind the scenes with the + operator.

console.log(1 + 2);
console.log(1 + "s");

In the above two example, addition and concatenation are both happening using a single (+) operator.

As I've found, JavaScript doesn't support operator overloading. So how is JavaScript handling it?

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
Sasikumar
  • 828
  • 12
  • 25
  • 2
    Possible duplicate of [How : operator works in Javascript](https://stackoverflow.com/questions/29742909/how-operator-works-in-javascript) – Nikola Lukic Jun 22 '18 at 13:00
  • You can check the mozilla documents for clarification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment – Krishna Prashatt Jun 22 '18 at 13:02
  • Please read the questions carefully. I have edited it for more clarity. – Sasikumar Jun 22 '18 at 17:59
  • The question is not a duplicate Nikola Lukic. How operator overloading happens with + operator is the question. – Sasikumar Jun 25 '18 at 09:40

2 Answers2

0
// Number + Number -> addition
1 + 2 // 3

// Boolean + Number -> addition
true + 1 // 2

// Boolean + Boolean -> addition
false + false // 0

// Number + String -> concatenation
5 + 'foo' // "5foo"

// String + Boolean -> concatenation
'foo' + false // "foofalse"

// String + String -> concatenation
'foo' + 'bar' // "foobar"

All examples from MDN

Damian Peralta
  • 1,846
  • 7
  • 11
  • 1
    The question is about how the operator(+) overloading happens in javascript? – Sasikumar Jun 25 '18 at 09:34
  • Check these threads: https://stackoverflow.com/questions/19620667/javascript-operator-overloading, and https://stackoverflow.com/questions/1634341/overloading-arithmetic-operators-in-javascript – Damian Peralta Jun 25 '18 at 10:54
-1

The reason is that variables will be cast to whichever type is appropriate.

When you add 1 + "s", 1 is converted to string, so you have "1" + "s". Since + is a concatenation operator with strings the results will be "1s".

There are weirder examples:

var result =  'b' + 'a' + + 'a' + 'a';

will give:

>> baNaNa

Adding arrays can give unexpected results too:

var result = [1, 2, 3] + [4, 5, 6];
console.log(result);

will give

>> '1,2,34,5,6'

There are some more really interesting examples here: https://github.com/denysdovhan/wtfjs

Javascript is a language full of quirks, it's well worth understanding at least some of them.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40