Ask coding questions

← Back to all posts
Can anyone help me?? I am confused
StrayLove (5)

A variable is accidently created instead of updated can you spot the mistake and fix it
var word1 = "a";
var word2 = word1 + "b";
var word1 = word2;

I can tell already that word1 has been declared. But I am not getting how to fix it. I have tried to fix it but I don't think I am getting it. Can anyone help?? This is supposed to be simplest way to put it I was told. Lol.

vedprad1 (864)

The answer is very simple.
For each variable, you can only use the keyword var once, when you are creating it. You should remove the var keyword at line 3.

Actually, in recent versions of JavaScript, the extra keyword would be fine. The problem is only in older versions of JavaScript.

The final answer would look like this:

var word1 = 'a';
var word2 = word1 + 'b';
word1 = word2;

But wait. Why would you do it like this? You are creating the variable word2 for no reason. It would be way quicker if you do it this way:

var word1 = 'a';
word1 += 'b';

If this answers your question, please check the checkmark on the left side of this message. Thanks and Good Luck!