Search This Blog

2024/03/24

Javascript:Operations on Uninitialized Variables

When JavaScript variables are declared, they have an initial value of undefined.

If you do a mathematical operation on an undefined variable your result will be
NaN which means "Not a Number".

If you concatenate a string with an undefined variable, you will get a literal
string of "undefined".

consider following code snippet

Code:
x++
console.log(x);
var x = 21;

output:
NaN


Here at first line x is undefined any after mathematical operation it becomes
NaN.


consider another code snippet

Code:
x = x + 'my data'
console.log(x);
var x = "original data";

Output:
undefinedmy data

Here again x at first line is undefined when we concat it,its to toString() is
called first then latter part concatenated.

No comments:

Post a Comment