Null, Undefined and Delete in Javascript

Last Updated on: October 10, 2022

Unlike most other programming languages, you can use both undefined and null values in JavaScript.

This can confuse someone who comes to JavaScript from another programming language.

When an object is undefined, it means that it still has to be declared or has been declared and not given a value.

Null is a special value that means an object has no value, and JavaScript deals with null as an object.

These two values are different types. They are considered equal by the equality == operator but not the identity === operator.

alert(typeof i);  // Returns undefined
var x = null;
alert(typeof x); // Returns object
var j;
alert(typeof j);  // Also Returns undefined

The JavaScript delete operator will remove a property definition. This can be useful if you apply it to object properties and array members. It is possible to delete any variable that you declare implicitly, but you cannot delete variables that you declare with var.

var obj = {
  val: 'Some string'
alert(obj.val); // displays 'Some string'

delete obj.val;
alert(obj.val); // displays 'undefined'

There are several ways to check whether a value is null or undefined. These examples all show ways to check the status of a variable:

if (myval == null) // Checks for null with casting
if (myval === null) // Checks for null without casting
if (typeof myval != ‘undefined’) // Any scope
if (window[‘varname’] != undefined) // Global scope
if (myval != undefined) // Myval exists but don’t know the value

It is essential to know the difference between these different values and use them properly. Otherwise, you could unintentionally introduce errors into your code.

Get notified of new posts:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *