JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is undefined in JavaScript?

In JavaScript, undefined represents absence of value. Undefined also represents a variable or property that does not exist in the JavaScript code.

Undefined is a primitive data type in JavaScript.

Note: The typeof operator returns "undefined" for undefined value.

typeof variable; //"undefined"

You will see undefined in six situations in JavaScript:

1) If you declare a variable but do not initialize it, in that case, that variable has an undefined value. In simple terms, undefined is the default value of an uninitialized variable.

let x;
console.log(x); //undefined
console.log(typeof x); //"undefined"

2) If a variable does not exist in the code, then the typeof operator returns "undefined" for that undeclared variable.

console.log(typeof y); //"undefined"
console.log(y); //"ReferenceError: y is not defined"

The variable y is not declared in the program and when you access it, you will get ReferenceError, but the typeof operator returns "undefined".

3) When you access a property that does not exist in an object, then you get undefined.

let pdt = {
  name: "Google Pixel 6"
};
console.log(pdt.price); //undefined

In this example, you can see that the object pdt has no price property. Therefore, on accessing the price property, you get undefined.

If you want to verify whether an object has a particular property or not, then visit this page How to check if a property exists in an object or not.

4) JavaScript returns undefined if you access an index that does not exist in an array.

let numbers = [1, 2, 3, 4, 5];
console.log(numbers[5]); //undefined

In this example, the numbers array has five elements, so it has index values from 0 to 4. Therefore, if you access an index that is greater than 4, you will give undefined.

5) A function that does not use a return keyword to return a value always returns undefined.

function add(a, b){
  let c;
  c = a + b;
}

console.log(add(1, 2)); //undefined

In this example, you can see that the add() function does not return anything, so it implicitly returns undefined.

6) When you call a function and do not pass an argument for a function parameter, then that parameter has an undefined value.

In the following example, the show() function accepts two parameters, a and b. It means you can pass two arguments to the function while calling it.

function show(a, b){
  console.log(a);
  console.log(b);
}

show(1, 2);

Output

1
2

Suppose you passed a single argument to the show() function. In that case, the parameter b becomes undefined.

show(1);

Output

1
undefined

To solve this issue, you can set the default value to the function parameters using the ES6 default parameters feature.

function show(a, b=10){
  console.log(a);
  console.log(b);
}

show(1);

Output

1
10

Recommended Posts