Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Difference between undefined and null in javascript

Difference between undefined and null in javascript

In this article, we will study  what is the difference between undefined and null in javascript with examples, let’s look at the definition of

What is undefined in Javascript?

  1. In javascript undefined is also treated as a primitive value.
  2. That means it is a global property.
  3. It says that the variable has been declared and value is not been assigned yet.
  4. When javascript starts evaluating your code and if an assigned value is not available for declared variable then undefined will be returned.

Let us consider a below example for the understanding the difference between undefined and null in javascript properly

function person(name) {
    if (name === undefined) {
    
    return 'Undefined value!';
}
    return name;
}

var personName;

console.log(person(personName));
// output
// Undefined value!

What is NULL in Javascript?

In javascript,

  1. NULL is also treated as a primitive value.
  2. Null shows the absence of value in any object.
  3. A null value can be assigned by the developer itself, it will not be created automatically like undefined

Let us consider the below example.

function person(name) { 
    if (name === null) {
    
    return 'Null value!';
}
    return name;
}

var personName=null;

console.log(person(personName));
// output
// Null value!

In other words, the major difference between undefined and null in javascript is that NULL represents that variable points to no object or not assigned value.

Now create some variables and try to access

var Name;
console.log(Name);
// output 
// undefined

As we can see in the above example, the name is been set to the undefined. Now let us create null value

var Name =null;
console.log(Name);
// output 
// null

 

Also, read the Difference between var and let in javascript?