angelahe Posted September 16, 2018 Share Posted September 16, 2018 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 More sharing options...
Ingolme Posted September 16, 2018 Share Posted September 16, 2018 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 More sharing options...
dsonesuk Posted September 16, 2018 Share Posted September 16, 2018 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 More sharing options...
ishan_shah Posted February 20, 2020 Share Posted February 20, 2020 for your questions : var can not use var i=+5 at a time, To do that you have to first declare that variable and after that you can perform that operation like var i=0 i=+5; Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now