1

why is el+ = v[i] different from el+=v[i] ? i thought javascript doesn't care about spacing. thanks, Any answers are appreciated it. and please don't put my question on hold. i'm here trying to learn.

var v = ['a','b','c','d','e'];
var el="";

for(i=0; i<v.length; i++){
    el+ = v[i]; // not working because of spaces, but why?
    // el+=v[i]; // working
}
document.write(el);
4
  • 1
    I am confused as to why you would think it would work. What are your trying to do? el+ is not a valid variable name and has not been defined. The NOT WORKING looks like you are trying to assign v[i] to el+ Commented Feb 23, 2014 at 18:24
  • el+=v[i];// will return abcde, but el + = v[i] won't work Commented Feb 23, 2014 at 18:26
  • i gave it spaces so it's easy to read. never thought, javascript read it differently. Commented Feb 23, 2014 at 18:28
  • 2
    Well that would be like trying to give a word spaces to make it easier to read. "A q u i c k f o x" is not easer to read than "A quick fox" As discussed below + = is not the same as +=. If you want to make it easier to read do it like this: el += v[i]; that would be allowed Commented Feb 23, 2014 at 18:30

4 Answers 4

5

+= is an operator. It is not a combination of + and =.

Sign up to request clarification or add additional context in comments.

Comments

3

Because += is an augmented (or compound) assignment operator, not + =. Similarly, i++ is fine, but i+ + causes a syntax error.

Comments

2
el+ =

it's illegal operator.

+=
-=
/=
*=

are available for instance

for your case. I will suggest even avoid for loop and do instead :

var el = v.join('');

1 Comment

= is a valid assignment operator the problem lies more in the fact that el+ is not a valid variable name :-)
2

The JavaScript engine interprets "+ =" differently from "+=". That's just the way it is written.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.