AppDividend
Latest Code Tutorials

Javascript Null, Undefined and NaN Example

0

Javascript null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value, or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not a legitimate number. 

History of null in Programming languages

If you are working with another programming language like Java, then you have seen the Null pointer that does not point to anything. The null is often defined to be 0 in those languages, but in Javascript, null is a primitive value.

None in Python

There is no null in Python; instead, there is None object.

data = None

 Null In Java

myVariable = null;

If you need to evaluate a variable in the if condition, you may check this as follows in Java.

if(myVariable == null) 
{ 
   System.out.println(”Some output”); 
}

Null In PHP

$myVar = NULL;

Understanding null in Javascript

The value null is written with a literal: null. The null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that variable points to no object. In APIs, null is often retrieved in a place where an object can be expected, but no object is relevant. In short, In JavaScript, the data type of null is an object.

Let’s see some examples of null.

// app.js

const marvel = null
console.log(marvel)

The output is null.

Now, let’s remove the first line from the above code and see the output.

// app.js

console.log(marvel)

Now, run the file in the node environment and see the output.

Javascript null Tutorial With Example

See, it throws an error. So when we assign the null value, it gives the null in return.

Proof that null is an object in Javascript

What if we want to check the type of null? Well, we have a function called typeof() that checks the type of any object or value. So, let’s check the typeof() null.

// app.js

let marvel = null
console.log(typeof(marvel))

See the output.

Javascript Null, Undefined and NaN Tutorial With Example

So, null is an object in Javascript.

The null is falsy

In Javascript, null is the falsy value (i.e. “it evaluates to false if coerced to a boolean)”. The easiest way to check for null is to know that null evaluates to false in conditionals or if coerced to the boolean value.

const notSureifNull = null
if (notSureifNull) {
  console.log("Not null")
}
else {
  console.log("It could be null")
} // Could be null

for (let i = 0; null; i++) {
  console.log("It won't run")
}

notSureifNull ? console.log("truthy value") : console.log("Falsy value")

Output

Could be null
Falsy value

When you run the above file, you will get this output, and of course, that does not comprehend null from the other falsy values.

Declaring null in Javascript

We can assign a null object to any variable at the time of the declaration. Javascript variables come to life by assignment operator, which helps us to assign the particular value to the variable.

let data = null
console.log(data)

Output

null

In some programming languages, they don’t have to have an initial value assigned to them. The initial value for some types of variables might be Null.

Using null as part of a comparison

Let’s deep dive in the == or === equality operators to check for null.

Checking null values using Double equality(==) operator

First, we will check null against some of the most returned values in Javascript with (==) operator.

console.log("Is null equal to empty: ", null == "")
console.log("Is null equal to zero: ", null == 0)
console.log("Is null equal to false: ", null == false)
console.log("Is null equal to NaN: ", null == NaN)
console.log("Is null equal to 0n: ", null == 0n)
console.log("Is null equal to null: ", null == null)
console.log("Is null equal to undefined: ", null == undefined)

Output

Is null equal to empty:  false
Is null equal to zero:  false
Is null equal to false:  false
Is null equal to NaN:  false
Is null equal to 0n:  false
Is null equal to null:  true
Is null equal to undefined:  true

In the above example, we have checked the null value against some of the most unexpected and erroneous values, and we have got the output, and some of them are still unexpected to us.

First, null in Javascript is not equal to empty. Then null is not equal to zero, and null is not equal to a false boolean value, although it is a falsy value; it is not equal to false. Despite the hard fact that null is a falsy value (i.e., it evaluates to false if coerced to a boolean), it still is not considered itself loosely equal to any of the other falsy values in JavaScript.

Then we have checked against NaN value, which is not equal to null either. Then 0n, which is not equal.  But when it comes to null == null, it returns true. That means two null values are the same. In fact, the only values that null is loosely equal to are undefined(undefined == null) and itself(null == null) because both returns true.

Checking null values using triple equality(===) operator

If we have to make sure that we have precisely the null value, excluding any undefined values, using a triple equality === operator will do the trick. Now, let’s check all the values above against the null with (===) strict equal to operator.

console.log("Is null strict equal to empty: ", null === "")
console.log("Is null strict equal to zero: ", null === 0)
console.log("Is null strict equal to false: ", null === false)
console.log("Is null strict equal to NaN: ", null === NaN)
console.log("Is null strict equal to 0n: ", null === 0n)
console.log("Is null strict equal to null: ", null === null)
console.log("Is null strict equal to undefined: ", null === undefined)

Output

Is null strict equal to empty:  false
Is null strict equal to zero:  false
Is null strict equal to false:  false
Is null strict equal to NaN:  false
Is null strict equal to 0n:  false
Is null strict equal to null:  true
Is null strict equal to undefined:  false

Now, you can see that null is not strictly equal to undefined. It is a better approach to handle both null and undefined values, as both represent the absence of a value. That means checking for null is one of the few times in JavaScript that using == (double equality operator)is recommended, while otherwise === (strict comparison operator) is generally recommended.

Using null as a Value in Javascript

In Javascript, we can pass null as a valid argument to the function. We can also add null as an item to the array. To provide that, let’s create a function called valueAsNull() and pass the two parameters to that function.

  1. new_element: This is a new element that will be added to the array if we pass an argument at the time of calling the function.
  2. initiali_array: As a default parameter, the inital_array is null, but if we pass any argument explicitly, then it will return that array.

We will see a scenario in which we pass null as new_element and data as initial_array. That should be adding the null value to the initial_array.

function valueAsNull(new_element, initial_arr = null) {
  if (initial_arr == null) {
    initial_arr = []
  }
  if (initial_arr != null) {
    initial_arr.push(new_element)
  }
  return initial_arr
}
data = [1, 2, 3, 4, 5]
console.log(valueAsNull(null, data))

Output

[ 1, 2, 3, 4, 5, null ]

See that means, we can add a null object as value to an array using the push() method.

Javascript null basic math operations

Check out the basic math operations on nullWrite the following code.

// app.js

console.log(null / 7)
console.log(null % 7)
console.log(null - 7)
console.log(null + 7)
console.log(null * 7)

See the output.

Javascript null basic math operations

Understanding undefined in Javascript

The undefined is the property of a global object, i.e., it is the variable in the global scope. An initial value of undefined is the primitive value undefined. A variable that has not been assigned a value is of type undefined. The method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. See the following example.

// app.js

let marvel
console.log(marvel == undefined)

So, if the marvel is undefined, then it will return a true otherwise false. We have not assigned the value to the marvel yet; that is why it returns undefined. The output is following,

Javascript undefined

If you define a function that has a return statement or returns no value, then it returns undefined.

function js_undefined() {

}
console.log(js_null())

Output

node app
undefined

When you call the js_undefined() function, it returns undefined because there is no return statement.  Here in the console, printing it shows undefined shows that we are forcing explicitly to print the output. 

Declaring undefined in Javascript

In some programming languages, you don’t have to have an initial value assigned to them. The initial value for some types of variables might be Null, or in the Javascript case, it is undefined.

So, if you just declare a variable in Javascript and do not assign the initial value, then the value of that variable is automatically undefined.

let data
console.log(data)

Output

undefined

If we don’t define a variable and direct print its value in the console, then we will get ReferenceError.

console.log(data)

Output

console.log(data)
            ^

ReferenceError: data is not defined

All variables in Javascript come into life by the assignment operator. A variable can only start life as undefined if you don’t assign any value to it. If you don’t define a variable and directly try to print in the console, then you will get ReferenceError.

Using undefined as part of a comparison

Let’s deep dive in the == or === equality operators to check for undefined.

Checking null values using double equality(==) operator

console.log("Is undefined same as empty: ", undefined == "")
console.log("Is undefined same as zero: ", undefined == 0)
console.log("Is undefined same as false: ", undefined == false)
console.log("Is undefined same as NaN: ", undefined == NaN)
console.log("Is undefined same as 0n: ", undefined == 0n)
console.log("Is undefined same as null: ", undefined == null)
console.log("Is undefined same as undefined: ", undefined == undefined)

Output

Is undefined same as empty:  false
Is undefined same as zero:  false
Is undefined same as false:  false
Is undefined same as NaN:  false
Is undefined same as 0n:  false
Is undefined same as null:  true
Is undefined same as undefined:  true

In the above example, we have checked the undefined value against some of the most unexpected and erroneous values, and we have got the output, and some of them are still unexpected to us.

First, undefined in Javascript is not equal to empty. Then undefined is not equal to zero, and undefined is not equal to a false boolean value Then we have checked against NaN value, which is not equal to undefined either. Then 0n, which is not equal.  But when it comes to undefined == null, it returns true. That means two null values are the same. In fact, the only values that null is loosely equal to are undefined(undefined == null) returns true, and also itself(undefined == undefined) true. Both returns true.

Checking null values using triple equality(===) operator

console.log("Is undefined strict equal to empty: ", undefined === "")
console.log("Is undefined strict equal to zero: ", undefined === 0)
console.log("Is undefined strict equal to false: ", undefined === false)
console.log("Is undefined strict equal to NaN: ", undefined === NaN)
console.log("Is undefined strict equal to 0n: ", undefined === 0n)
console.log("Is undefined strict equal to undefined: ", undefined === undefined)
console.log("Is undefined strict equal to null: ", undefined === null)

Output

Is undefined strict equal to empty:  false
Is undefined strict equal to zero:  false
Is undefined strict equal to false:  false
Is undefined strict equal to NaN:  false
Is undefined strict equal to 0n:  false
Is undefined strict equal to undefined:  true
Is undefined strict equal to null:  false

As we have checked earlier, undefined is not strictly equal to null. It is a good idea to catch both null and undefined values, as both represent an absence of a value. That means checking for undefined is one of the few times in JavaScript that using == is recommended, while otherwise === (strict comparison operator) is generally recommended.

Checking typeof operator with undefined

See the following code.

// app.js

let marvel
if (typeof marvel === 'undefined') {
   console.log('Marvel is undefined')
}
else {
  console.log('It is not undefined')
}

In the above code, we have compared the undefined with the unassigned variable marvel. So, if the condition is true, it will print the console message.

See the output.

Typeof operator and undefined

Difference between null and undefined in Javascript

The undefined and null are equal in value but different in type.

See the following code.

// app.js

console.log(typeof undefined)
console.log(typeof null)
console.log(null === undefined )
console.log(null == undefined)

See the output.

Difference between null and undefined in Javascript

See, if you compare the value, then they both are same, but if you compare its datatype, then they are different; that is why we get false.

Understanding NaN in Javascript

NaN is a property of the global object. I think the definition is clear enough. JavaScript returns this value when the Number we’re supposed to get isn’t a number. For example, when you’re trying to subtract an “appdividend” from 21 or divide 12 by “KDL”.

See the following example.

// app.js

console.log('Appdividend' - 30)

See the output.

Javascript NaN

The NaN property is the same as the Number.Nan property. We can use the isNaN() global function to check if a value is a NaN value when you’re adding something to the string. If JavaScript sees a + sign and a string, it automatically converts the second element of addition into the string as well.

Now, let’s check the typeof NaN.

// app.js

console.log(typeof NaN)

Run the file and see the output.

typeof NaN Example

So, the datatype of NaN is NumberNot an object or undefined or null.

 If NaN compared to itself returns false, then no matter what we’re going to compare it to, it will always give false. See the following code.

// app.js

console.log(NaN === NaN)
console.log(NaN == NaN)

See the output.

NaN in Javascript

Declaring NaN in Javascript

You can assign a NaN value to any variable using an assignment operator.

let data = NaN
console.log(data)

Output

NaN

Using NaN as part of a comparison

NaN compares unequal (via ==, !=, ===, and !==) to any other value — including to another NaN value. Use Number.isNaN()  to clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

console.log(NaN === NaN);
console.log(Number.NaN === NaN)
console.log(isNaN(NaN))
console.log(isNaN(Number.NaN))

Output

false
false
true
true

We have compared NaN values with itself and other values using triple equality or strict comparison operator. From the output, we can see that NaN is not strictly equal to NaN. Even Number object’s NaN property is not similar to NaN.

Then we have test NaN and Number.NaN values with inbuilt Javascript isNaN() function which returns true.

Difference between isNaN() and Number.isNaN()

Number.isNaN() is almost the same or identical to ES5 global isNaN method. Number.isNaN returns whether the given value equals NaN.

The isNaN() function just checks whether the given value is not a number or cannot be converted to a Number. The Number.isNaN(), on the other side, only checks if the value is equal to NaN (it uses the different algorithm than === though).

The String ‘AppDividend‘, for example, is not a number and cannot be converted into a number, but it is not NaN.

console.log(isNaN('AppDividend'))
console.log(Number.isNaN('AppDividend'))

Output

true
false

 Conclusion

The null is one of JavaScript’s primitive values. The NaN is a property of the global object. The global undefined property represents the primitive value undefined. It is one of JavaScript’s primitive types. Let’s see one by one.

Finally, Javascript null, undefined, and NaN Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.