JavaScript code error

var x = 1;
function add Two(){
var x = x +2;

add Two();
x = x+1;

I am getting an error when i run the code ? I think the answer is 1. Can someone please help ?

Hi @aditikochhar and welcome to the community!

There are several things going on here that is will cause errors:

  • You cannot use spaces in function names. Try renaming your function to¬† addTwo instead of¬† add<space>Two.
  • You re-define¬† x inside your function by using the¬† var keyword. That way, the¬† x¬† inside your function is a different¬† x than the¬† x in the first line.

This should fix the errors mostly, however I also do recommend to pass the variable that needs the addition as a function argument as well as giving the variable of the product a different name (for clarity). Your code will look something like this then:

var x = 1;
function addTwo(number) {
  return number + 2;

var y = addTwo(x);
y = y + 1;
console.log(y); // Should print the number 4 (1 + 2 + 1)

Again, these last changes are optional but do improve the quality of the code (at least in my opinion). Please let us know if you have any more questions.

PS: next time, please choose a title that fits the topic and put your code in a code block.