JavaScript undefined


What is undefined?

In JavaScript, undefined means:

  • A variable has been declared but no value has been assigned yet.
  • It also appears when functions do not return anything.
  • undefined is a primitive type in JavaScript.

When Does undefined Happen?

Here are the main cases:


1. Declared but Not Assigned

let a;
console.log(a); // Output: undefined

Here, a is declared but no value is given, so it's automatically undefined.


2. Function Without a Return Value

function greet() {
console.log("Hello!");
}
let result = greet();
console.log(result); // Output: undefined
  • greet() prints "Hello!".
  • But because it does not return anything, result becomes undefined.

3. Missing Function Parameters

If a function expects parameters, but you don't pass them:

function add(x, y) {
console.log(x + y);
}
add(5); // Output: NaN (because 5 + undefined = NaN)
  • y is undefined because it was not provided.

4. Accessing Non-Existing Object Properties

let person = { name: "Alice" };
console.log(person.age); // Output: undefined
  • age does not exist in person, so it returns undefined.

undefined Type

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

Difference Between undefined and null

Feature undefined null
Meaning Value not assigned Intentional absence of value
Type "undefined" "object"
Created by JavaScript Developer

Example:

let a;
let b = null;
console.log(a); // Output: undefined
console.log(b); // Output: null
console.log(typeof a); // Output: "undefined"
console.log(typeof b); // Output: "object"

Checking for undefined

You can check if a variable is undefined:

let value;
if (value === undefined) {
console.log("Value is undefined");
}
// Output: Value is undefined

Or using typeof:

if (typeof value ===
"undefined") {
console.log("Value is undefined");
}

Using typeof is safer because it doesn't throw an error even if the variable was never declared.


How to Avoid undefined Issues?

  • Always initialize variables when declaring them.
  • Check function arguments before using them.
  • Always return something from a function if a value is expected.

Quick Recap

  • undefined is a primitive type.
  • It means a variable has no assigned value yet.
  • Functions without a return value automatically return undefined.
  • undefined is different from null.

Example Summary

let a;
console.log(a); // undefined
function test() {}
console.log(test()); // undefined
let obj = {name: "Tom"};
console.log(obj.age); // undefined