Home >Web Front-end >JS Tutorial >undefined case
JavaScript uses the undefined
value in two slightly different ways.
The first way it is used is to indicate that a declared variable (var foo
) has no value assigned. The second way of use is to indicate that the object property you are trying to access has not been defined (not even named) and cannot be found in the prototype chain.
In the example below, I checked two uses of undefined
via JavaScript.
Example: sample62.html
<!DOCTYPE html><html lang="en"><body><script> var initializedVariable; // Declare variable. console.log(initializedVariable); // Logs undefined. console.log(typeof initializedVariable); // Confirm that JavaScript returns undefined. var foo = {}; console.log(foo.bar); // Logs undefined, no bar property in foo object. console.log(typeof foo.bar); // Confirm that JavaScript returns undefined. </script></body></html>
It is considered good practice to allow JavaScript to be used alone undefined
. You should never find yourself setting a value to undefined
, as in foo = undefined
. Conversely, if you specify a property or variable value that is not available, null
should be used.
Undefined
VariableUnlike previous versions, JavaScript ECMA-262 Edition 3 (and later) declares a global variable named undefined
in the global scope. Because the variable is declared and not assigned a value, an undefined variable is set to undefined
.
Example: sample63.html
<!DOCTYPE html><html lang="en"><body><script> // Confirm that undefined is a property of the global scope. console.log(undefined in this); // Logs true. </script></body></html>
When working with JavaScript, it is critical to fully understand undefined
values.
The above is the detailed content of undefined case. For more information, please follow other related articles on the PHP Chinese website!