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

javascript
Try it Yourself
let car;

document.getElementById("demo").innerHTML = car;

The Type of undefined

You can use typeof to check if a variable is undefined.

Example

Example Code

javascript
Try it Yourself
let 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

javascript
Try it Yourself
let text = "";

document.getElementById("demo").innerHTML =

text + " " + typeof text;

Objects and undefined

Accessing a non-existing object property returns undefined.

Example

Example Code

javascript
Try it Yourself
const 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

javascript
Try it Yourself
function 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

javascript
Try it Yourself
const 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

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 2

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 3

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 4

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 5

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const person = {firstName:"John", lastName:"Doe"};



person = undefined;