0

Why an assigned variable in JS is undefined when inspected in dev tools?

for example,

var x = 5;

results in undefined in devtools.

Django102
  • 523
  • 1
  • 4
  • 8
  • 1
    no it doesn't - you're probably doing something wrong - hard to tell how you could with a single line of code though – Jaromanda X Aug 04 '18 at 02:54
  • please try at console @Jaromanda var x =5; returns undefined. – Django102 Aug 04 '18 at 02:56
  • This statement `var x = 5;` doesn't return anything. But it does assign the variable x. Try this instead: `var x = 5; x;` – Mark Aug 04 '18 at 03:08
  • oh, I thought you meant variable `x` was `undefined` when you `inspected` it - that was your word, `inspected` - and since you can inspect (or watch) in the dev tools I assumed that's what you were referring to – Jaromanda X Aug 04 '18 at 03:44

3 Answers3

2

console does not evaluate the value of x, but it evaluates the expression itself,expressions are always undefined in javascript.

djangoscholar
  • 133
  • 2
  • 11
  • I think maybe your mixing up expressions and statements. Compare the console output of the *statement* `var x = 3;` with the *expression* `x = 2` – Mark Aug 04 '18 at 03:23
1

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
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
0
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.
shehzad lakhani
  • 495
  • 5
  • 14