0

Possible Duplicate:
Overloading Arithmetic Operators in JavaScript?

Is it possible to add Javascript Objects in a custom way? Javascript allows you to use the + symbol to merge Strings together as well as add Numbers together.

I am wondering if you could define new ways for things to be merged such as adding arrays. What I'm looking for is something like this:

var output = [0,1,2] + [3,4,5];
console.log(output);
//I want this to log [3,5,7]

I know I could easily do this with some addArray() function but I was wondering if it can be done by using the + symbol.

Community
  • 1
  • 1
Evan Kennedy
  • 3,975
  • 1
  • 25
  • 31
  • Wow, I can't believe I wrote it as that. – Evan Kennedy Sep 02 '12 at 22:50
  • This sort of thing is more common in functional languages or math packages, which Javascript is neither. In this case, for an imperative language, I think that the expected behavior of `+` is array concatenation. – Waleed Khan Sep 02 '12 at 22:51
  • `I was wondering if it can be done by using the + symbol` Seems like you already ran this in the console, so you probably have the answer to your question already, no? – Fabrício Matté Sep 02 '12 at 22:51

2 Answers2

3

No, Javascript does not support operator overloading and there is no built-in functionality to do this.

Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
1

Is it possible to add Javascript Objects in a custom way?

Yes, you can write your own addObject function.

Javascript allows you to use the + symbol to [concatenate] Strings together as well as add Numbers together.

ECMA-262 defines whether the '+' punctuator is treated as a unary or addition operator in expressions. As Mat says, you can't overload it. Even if you could, it doesn't seem like a good idea to change its behaviour since it's already used for 3 different things and has a specified behaviour for "adding" arrays like [1,2] + [3,4].

RobG
  • 142,382
  • 31
  • 172
  • 209