Jump to content
angelahe

"var" keyword not used with =+ operator?

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!

 

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...