InterviewSolution
| 1. |
What Is The Difference Between Undefined And Not Defined In Javascript? |
|
Answer» In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop EXECUTING. However, if you use typeof undeclared_variable, then it will RETURN undefined. Before getting further into this, let's first understand the difference between declaration and definition. Let's say var x is a declaration because you have not defined what value it HOLDS yet, but you have declared its existence and the need for memory allocation. > var x; // DECLARING x Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called HOISTING. The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined. var x; // Declaration If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined. > console.log(y); // Output: ReferenceError: y is not defined In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined. Before getting further into this, let's first understand the difference between declaration and definition. Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation. > var x; // declaring x Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting. The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined. var x; // Declaration If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined. > console.log(y); // Output: ReferenceError: y is not defined |
|