Hi guys! What's the difference between the 2 scenarios ("Undefined" and "a is not defined"): >> Scenario 1: // a is declared but not assigned a value var a; console.log(a); => Undefined >> Scenario 2: // a is not declared at all console.log(a); => UncaughtReferenceError: a is not defined
8/28/2020 12:51:12 PM👑 Tchybooxuur![Inactive]
15 AnswersNew Answer
Using the var key word you initialise the variable a and it is always initialised to undefined. If the system doesn't find any variable a in the storage then it shows an error that it cannot find any variable named a. In the scenario 1, the output is not an error In the scenario 2, it shows the error (as told above) That is why it is good to declare the variables using the var keyword at the beginning itself! In code example: if (5 > 6) var a = 10; console.log(a); Output is an error! But, if you had already initialised the variable (before the if block) then it wouldn't have shown an error
Think of variables like boxes with labels. In first scenario you have created a box, and put a label titled "a" on it. But you haven't stored anything in the box, and so the content of the box is said to be "undefined". In second scenario you force someone (named "console") to open a box labeled "a", and show its content. But there is no such thing as "a" box. You haven't created that box labeled "a" yet. The second scenario is worse than the first, not only the box content is undefined, the box itself does not even exist.
Lord Krishna, Namit Jain, Ipang & 🔫 Rick Grimes: Thanks Guys...
undefined is an actual value when you do not assign any value to any declared variable. But if you try to access it without definition the error says "abc variable is undefined", here undefined is used as word from english which means not defined(un-defined)
In the first case the type of object is not specified in the latter the object itself does not exist 🤔
1) Variable have no value 2) Variable do not exists
Undefined is applied when a variable has not datatype or it's incompatible. This occur cause it exists a function could not return a value or it is not instantiated. For example, when you consume a web service. a is not defined occur when you have not declared, it is almost equivalent with a difference in the context. Scenario 1 indicate you declared your variable a, but you didn't define a datatype, in consequence you have to assign a value, and automatically this one already a datatype. In the case of Scenario 2, you don't declare variable a, for this reason it get it out a not defined.
In the first scenario , we get output as undefined because we did not intialise it. But in second scenario we get an error. In Js First we should declare the varaible and should use it.
var a; is the same as var a = undefined;
Var do not exists