JS TutorialLesson #105
JavaScript undefined
In JavaScript, a variable without a value has the value undefined.
In JavaScript, a variable without a value has the value undefined.
The type is also undefined.
Share
Undefined Variables
A variable declared without a value will automatically have the value undefined.
Example
Example Code
javascriptlet car;
document.getElementById("demo").innerHTML = car;The Type of undefined
You can use typeof to check if a variable is undefined.
Example
Example Code
javascriptlet car;
document.getElementById("demo").innerHTML = typeof car;Empty Values
An empty string has a value and a type.
It is not the same as undefined.
Example
Example Code
javascriptlet text = "";
document.getElementById("demo").innerHTML =
text + " " + typeof text;Objects and undefined
Accessing a non-existing object property returns undefined.
Example
Example Code
javascriptconst person = {firstName:"John", lastName:"Doe"};
document.getElementById("demo").innerHTML = person.age;Functions and undefined
A function without a return value returns undefined.
Example
Example Code
javascriptfunction myFunction() {
let x = 5;
}
document.getElementById("demo").innerHTML = myFunction();You Can Empty an Object
Objects can be emptied by setting the value to undefined.
Example
Example Code
javascriptconst person = {firstName:"John", lastName:"Doe"};
person = undefined;Objects can also be emptied by setting the value to null.
Note
undefined is a JavaScript value.
It means that a variable has been declared, but no value has been assigned.
Interactive Code Examples
JS Example 1
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 2
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 3
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 4
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 5
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 6
javascriptJavaScript syntax and algorithm demonstration.
const person = {firstName:"John", lastName:"Doe"};
person = undefined;