Why this code do not work ?
var text = '';
var text += 'How ';
var text += 'are ';
var text += 'you ';
var text += 'today ?';
alert(text);
I'm trying to alert() : How are you today ?
This is a voluntary basic code.
Thanks.
Because you are re-declaring text variable each time instead of just updating its value. You should do:
var text = '';
text += 'How ';
text += 'are ';
text += 'you ';
text += 'today ?';
alert(text);
Each time you use var text, you are re-declaring the variable.
var text = '';
text += 'How ';
text += 'are ';
text += 'you ';
text += 'today ?';
alert(text);
Here's a different approach, using an array:
var text = [];
text.push('How');
text.push('are');
text.push('you');
text.push('today');
alert( text.join(' ') );
I'll answer in a bit more depth.
The var keyword could be considered a constructor. What a constructor does is creates something, of a class, with all default values. By default, values constructed with the var keyword are null.
With that in mind, what you are doing in reality is redeclaring the text variable as null, and then assigning it your next value, but you are doing this each time you want to add something, therefore appending your new value onto nothing, meaning it is assigned to that value, and that value alone.
This is your solution: (don't redeclare)
var text = "Hello",
name = "Josh";
text += " World";
text += ", My name is ";
text += name;
You cannot use += while declaring a variable in JavaScript.
Also, you are making multiple declarations of the same variable.
Try this instead -
https://jsfiddle.net/abto5aLj/
var text = '';
text += 'How ';
text += 'are ';
text += 'you ';
text += 'today ?';
alert(text);
Because you are redefining the variable text every time our are trying to add a new piece of string.
You have to use the variable statement var only the first time you are defining a new variable (text in your case).
Here the complete example with the correction:
var text = '';
text += 'How ';
text += 'are ';
text += 'you ';
text += 'today ?';
alert(text);
textonce, kill thevarin front of text after the first one