Js: On Click Function Add Number To Variable - Gives Nan
Solution 1:
Because you are are declaring same variable (xx) two times
See fiddle: https://jsfiddle.net/1beo7mgw/2/
So, why it is returning NaN?
Because on this line var xx = xx + 10; variable xx is defined again but not initialized with any value followed by the addition of 10.
So var xx will hold undefined and adding 10 on undefined will return not a number (NaN)
Solution 2:
You could skip the var statement inside of the function. Then the global variable xx will be used.
$('div').click(function() {
xx = xx + 10;
//^ without varalert(xx);
});
Solution 3:
In your code because your using same name to define variable in the global scope and function scope the problem occurs. In this code at function level - var xx = xx + 10; you try to redefine the xx variable with var but forgot to reinitialize it so default it will be undefined for variables without initialization and you add 10 to it where undefined + 10 will be not a numver (NAN)
There are two approaches,
- Best approach is using ES6 version of Javascript, It has added two features
letandconsteliminatingvar.constare immutable, even if u try to mutate it after initializing it give error.letonly gets valid within the scope it gets defined, for e.g. if you define a let variable within a loop it belongs to the loop only outsiders cannot access it. Below code i have changed50value initialization as aconstand i have usedletin the addition process
const xx = 50;
$('div').click(function(){
let yy = xx + 10;
alert(yy)
});<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>
click
</div>- Simply change the variable name and make-sure you have two different variable names defined in both places below code shows that illustration
var xx = 50;
$('div').click(function(){
var yy = xx + 10;
alert(yy)
});<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>
click
</div>Solution 4:
window.xx = 50;
$('div').click(function(){
window.xx = window.xx + 10;
alert(window.xx)
});<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>click</div>However, you should be careful with the global variables to avoid conflicts, http://www.javascripttoolbox.com/bestpractices/#namespace
Solution 5:
Read up on variable "scope":
https://www.w3schools.com/js/js_scope.asp
The global scope is outside of your function, so declaring "xx" outside the function means anything in your code can see it. The local scope is inside your function, so declaring "xx" inside the function means anything inside your function can see it. However since you've declared it globally and locally, the local one overrides the global one, inside the function.
Post a Comment for "Js: On Click Function Add Number To Variable - Gives Nan"