DEV Community

James L
James L

Posted on

Undeclared, undefined and null in Javascript

What is an undeclared variable?

  • An undeclared variable is created when you assign a value to an identifier which has not been previously created using var, let or const.
  • Are defined globally outside of the current scope.
  • Can only occur outside of strict mode. If enabled, strict mode will throw a ReferenceError instead.
// undeclared variable
// assigned global scope
x = 1;

console.log(x) // 1
Enter fullscreen mode Exit fullscreen mode
'use strict'

// Throws ReferenceError: x is not defined
x = 1;
Enter fullscreen mode Exit fullscreen mode

What is an undefined variable?

  • An undefined variable in Javascript is a variable which has been declared but has no value assigned to it.
  • It has the type undefined.
var x;

console.log(x) // undefined
Enter fullscreen mode Exit fullscreen mode

What is the difference between null and undefined?

  • undefined is the value of a variable which has not been assigned a value.
  • null has to be assigned to a variable.
  • null has the type Object
var x; // x is undefined
var y = null; // y is null

console.log(x == y); // true
console.log(x === y); // false
Enter fullscreen mode Exit fullscreen mode
  • Using the abstract equality operator ==, null and undefined will be equal.
  • Using the strict equality operator, ===, null and undefined are not equal as x is of type undefined and y is of type Object.

Top comments (0)