Jump to content

"var" keyword not used with =+ operator?


angelahe

Recommended Posts

In "JavaScript Operator", I noticed that the "var" keyword is not used when the += operator is used; for example:

<p id="demo"></p>

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

And I tested the result of adding "var" before the statement x += 5, so: var x += 5, everything else uchanged. Then, it won't display 15; in fact, it displays nothing.

However, if using x = x + 5 instead, adding or not adding "var", it always runs and displays 15. 

So, my questions are:

(1) Why "var" cannot be used with += operator?

(2) Why "var" seems to be operational when used with "x = x + 5"?

Thank you!

 

Link to comment
Share on other sites

You declare a variable only once, then use it as many times as you need to.

Using the var keyword creates a new variable. It doesn't make sense to create a variable that already exists.

Link to comment
Share on other sites

A 'var' defines a identifier as a variable

var x=10; //define variable and its value
var x = x + 5; //redefine variable but new 'x' value will now be the previous defined value plus 5

additional var definition of the the same identifier means that x default value will now be the current value calculated, overriding the previous.

It can be seen using

var y=0
var x = 10;
var y = x+5;
document.getElementById("demo_x").innerHTML = x;
document.getElementById("demo_y").innerHTML = y;

swap 'y' to 'x' in third line.

As 'y,' its default value is from now on, will be 15 (as below if 'x') , while 'x' will remain as 10.

As 'x' its default value is from now on, will be 15, while 'y' will remain as 0.

var x+=5;

Its not doing nothing, its produces a syntax error, and the script will fail from that point as its not valid, hit f12 on keyboard to view console to see this error.

Link to comment
Share on other sites

  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...