JavaSript ignores simple function in CodePen

I put a simple code in JS, in CodePen. JavaSript ignores the function. Output of the console.log is always 2 when it should be 3. Sometimes, there is no output at all.

Why is this happening?

Many thanks in advance.

My code


var x=2;

function test(x) {
    return x=x+1;
}
console.log(x);

//output should be 3. However, it is 2

Did you call the function?

I tried with:
test.call(x);
Output is again 2 where it should be 3.

I don’t see anywhere that this syntax would make sense.

If you define a function as

then you should call it as

test(x)

Though, I don’t think that it will do the assignment in the way that you think it will. The function argument x shadows the global variable x, so you will be incrementing the variable x inside of the function test() rather than the global variable x.

1 Like
  1. In the code you’ve included above, you are not calling the function test()
  2. Calling the function test() will not change the global x value.
var x=2;

function test(x) {
    return x=x+1;
}
console.log(x); // 2
console.log(test(x)); // 3
console.log(x); // 2
2 Likes

Thank you!
I can not beleive I got stuck this easy! Suppouse it is part of learning. :sweat_smile:

There’s nothing wrong with getting stuck. It’s a normal part of the process. Happy coding!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.