Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

this is my code

var text = "";
var text += "function "+ funcName + "(){";
var text += "\n";

and this is the error:

**Uncaught SyntaxError: Unexpected token += **

How can I solve it?

share|improve this question
6  
Get rid of var on the lines after the first; it's completely unnecessary and it's causing your problem. –  Pointy 13 hours ago
2  
Every time you use var it's like you're re-declaring the variable. –  MelanciaUK 13 hours ago
    
Once you've declared a variable with var in a particular lexical context, you don't need to do it again. –  Pointy 13 hours ago
1  
@FabrícioMatté so += is valid in a var initializer clause? –  Pointy 13 hours ago
2  
I'll just note that @MelanciaUK's comment is not really clear. var declarations are parsed and their identifiers are added as properties of the Environment Record object in the entering phase of the execution context. That means a var re-declaration is redundant and does not re-initialize a variable. Try: var a=1; var a; alert(a); alerts 1. However, += is not valid a token after the identifier of a variable declaration, hence the syntax error. –  Fabrício Matté 13 hours ago

4 Answers 4

up vote 3 down vote accepted

You are redeclaring an already declared variable. Instead, you should have:

var text = "";
text += "function "+ funcName + "(){";
text += "\n";

You can't += a variable that hasn't been assigned a value yet, since there is not an initial value to be incrementing.

share|improve this answer
    
The correct answer is in Fabrício Matté's comment. –  RobG 12 hours ago

You just need to declare your variables once.

var funcName = "myFunction";
var text = "";
text += "function " + funcName + "(){";
text += "\n";

http://jsfiddle.net/66d0t7k0/3/

share|improve this answer

The += operator appends text to an existing variable -- it is a syntax error to use it in a new variable declaration. So you need either (which is syntactically correct but nonsense):

var text = "";
var text = "function "+ funcName + "(){";
var text = "\n";

Or:

var text = "";
text += "function "+ funcName + "(){";
text += "\n";
share|improve this answer

Remove the var from the second line and third line, you are declaring a new variable from every line.

var text = "";
    text += "function "+ funcName + "(){";
    text += "\n";
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.