Why an assigned variable in JS is undefined when inspected in dev tools?
for example,
var x = 5;
results in undefined in devtools.
Why an assigned variable in JS is undefined when inspected in dev tools?
for example,
var x = 5;
results in undefined in devtools.
console does not evaluate the value of x, but it evaluates the expression itself,expressions are always undefined in javascript.
Example 1 =>
var x = 55; // undefined
It declares the variable x and assigns it the value of undefined. That is the value we get back as feedback on the console.
Then, it finally assigns the value of 55 to x. At this time the console has already returned a value so we don't get to see the value 55 as feedback when we declare and assign a variable at once.
On the other hand, if we reassign variable x to a different value at a later time, we will get the new value as feedback instead of undefined:
Example 2 =>
x = 57; //57
We are declaring a variable but of which type it does not define (like string, int, or boolean) that's why it displays undefined as a first statement. after it assigns a value to a variable and decides the type of variable in Javascript.
like var a=10; // undefined as first time when var is created.
typeof(a) // "number" in second statement
-- IN addition for the function in Javascript ---------------
(function (){return("OK")})()
(function (){})()
Undefined is about the return value of a function call.
You only see something useful when a function returns value.
If nothing is returned then you see undefined.