JavaScript Interview Series – All about NaN

nan1In JavaScript, NaN is one of the most confusing concepts; hence, it is often asked in the interview. You may have come across questions such as,

  • What is NaN
  • What is the type of NaN
  • How to check for the NaN
  • What is the difference between isNaN() and Number.isNaN()

In this post, let us learn the answer to the above questions one by one.

For me, The NaN is an error value in the JavaScript. However, technically it is the property of the global object. You get NaN when the value cannot be computed or as a result of attempted number coercion (type conversion) of non-numeric value (such that undefined) for which primitive numeric value is not available.NaN2

For example, for an arithmetic operation in which one of the operands is a missing value (read it undefined), JavaScript returns NaN. However, there are some other non-computational scenarios, such that divide by zero; instead of NaN you get Infinity value.



const foo = 7 + undefined; 
const too  = 7/0; 
console.log(foo); // NaN
console.log(too); // Infinity 


NaN3

You get value NaN in the following scenarios,

  • If one of the operands in an arithmetic operation is undefined
  • If one of the operands in an arithmetic operation is NaN
  • Dividing Zero by Zero
  • Dividing Infinity by Infinity
  • Multiplying zero with Infinity


let foo = 7 + undefined; // NaN
let koo = undefined - 7 ; // NaN 
let loo = NaN + NaN ; // NaN 
let hoo = NaN - NaN; // NaN 
let noo = 7 + NaN // NaN
let too = NaN * NaN // NaN
let poo = NaN % NaN // NaN
let roo = NaN % NaN // NaN
let zoo = 0 / 0 // NaN 
let qoo = 0 * Infinity; // NaN


NaN stands for Not a Number, and interestingly its type is number



console.log(typeof NaN); // number


NaN4

JavaScript treats NaN like any real number and can be used in any number type operations. The NaN is a property of the global object, and its other equivalent is Number.NaN.

NaN5

Keep in mind that both are the same.


console.log(NaN); // NaN
console.log(Number.NaN); // NaN 


The property attributes of NaN property are set to false. That means you cannot write, enumerate, or configure NaN property.



const NaNProp = Object.getOwnPropertyDescriptor(Number,'NaN');

/*Output 
{ value: NaN,
    writable: false,
    enumerable: false,
    configurable: false } */

console.log(NaNProp); 


Also, to use NaN property, you do not have to create the Number object, as it is a static property.

Check for NaN

In JavaScript, NaN is a value that is not strictly equal to itself, which makes it tricky to check for the NaN.

NaN8

It is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false.



const foo = NaN; 
console.log(NaN === foo) // false 
console.log(NaN === NaN) // false 
console.log(NaN == foo) // false 
console.log(NaN == NaN) // false 


As you cannot use equality operator to check for the NaN value, JavaScript provides other ways to check value for NaN,

  1. isNaN() function
  2. isNaN()
  3. is(foo,NaN)

The Number.isNaN() method determines whether the value of the passed parameter is NaN and also its type is number.



const foo = NaN; 
console.log(Number.isNaN(foo)) // true 
const too = 'NaN';
console.log(Number.isNaN(too)) // false 


The Number.isNaN() method checks for both

  1. Whether the value is NaN
  2. Whether the type is number

As it checks for both types and the value, it always returns the expected result.


const foo = NaN;
console.log(Object.is(foo,NaN)); // true 
console.log(Object.is('NaN','NaN')); // true 
console.log(Object.is('NaN',foo)); // false


 

You can also use the Object.is() method to check for the value of NaN.



const foo = NaN;
console.log(Object.is(foo,NaN)); // true 
console.log(Object.is('NaN','NaN')); // true 
console.log(Object.is('NaN',foo)); // false


The Object.is() method determines whether two values are the same value or not. It checks for both equality and strict equality.  So you can also use the Object.is() method for the value of NaN.

How about isNaN()

The isNaN()  function also determines whether a value is NaN or not. Before checking for the value NaN, it tries to covert value to be tested as a number resulting in many unexpected results.



const foo = NaN;
console.log(isNaN(NaN)); // true 
console.log(isNaN(foo)); // true 
console.log(isNaN(undefined)); // true
console.log(isNaN(null)); // false 
console.log(isNaN(0/0)); // true
console.log(isNaN({})); // true
console.log(isNaN(false)); // false
console.log(isNaN(1234)); // false


In the above example, for many cases such that isNaN({}),  JavaScript is not able to do coercion of the passed value as a number, hence returns true.

Let us consider when you pass undefined in to check for the value of NaN in isNaN() function and JavaScript is not able to convert undefined to a valid real number; hence, it converts it to NaN, and as a result, you get true.

Starting ECMA 2O15, it is advisable to use Number.isNaN() method to check for the value of NaN.

NaN9

As a summary, JavaScript returns NaN for the value which can not be computed, and you should use Number.isNaN() to check whether a value is NaN or not.

I hope now you can answer about JavaScript NaN confidently in the interview.  Thanks for reading and any training or consulting need reach out to me at debugmode[at]outlook[dot]com 

Announced- geek97 step by step Angular Bootcamp on 5-6 October in Gurgaon

To attend register here: https://forms.gle/JSbp3yknZ7scr9BP7

Many of you asked me to host a Bootcamp in Delhi/NCR. I got motivated by your constant request, hence decided to give a try. For geek97, I am hosting the next Bootcamp in Gurgaon on 5-6 October.

Details

b1

To attend register here: https://forms.gle/JSbp3yknZ7scr9BP7  and for any clarification send me a mail at debugmode[at]outlook.com

Agenda of the training is as below,

Lecture 1: Getting started and Data Binding – 1.5 Hrs

  • Interpolation
  • Event Binding
  • Property Binding
  • Two-way data binding
  • Using directives such as *ngFor, *ngIf
  • Using inbuilt type
  • Creating a custom search pipe

Lab – Displaying Data in a table from local JSON array using *ngFor

Lecture 2: Component Communications – 2 Hrs

  • @Input
  • @Output and EventEmitter
  • Temp Ref Variable
  • Understanding Life Cycle Hook when the component has @Input decorated properties
  • Introducing Change Detector

Lab:  Master – Details Application using component communication

Lecture 3:  Services and Providers – 1.5 Hrs

  • Creating first service
  • Understanding Dependency Injection
  • Using @useclass, @useexisting, @usevalue, @usefactory
  • Understanding injector tokens
  • Share data between two unrelated components

Lab:  creating global variable and inject to whole application

Lecture 4:   Custom Attribute Binding – 0.5 Hrs

  • Custom Binding
  • @HostBinding
  • @HostListener

Lecture 5:  Reactive Forms – 1.5 Hrs

  • Template Forms and Reactive Forms
  • Creating Reactive Forms
    • FormControl
    • FormGroup
    • FormBuilder
    • FormArray
  • Custom Validators
  • Conditional Validators
  • setValue and patchValue

Lecture 6:   Introducing RxJS – 2.5 Hrs

  • What is reactive way of thinking
  • Observables and subscribe
  • RxJS operators
    • Tap
    • Map
    • Take
  • Different types of subjects
  • Fetching data using observable – subscribe
  • Async pipe
  • Handling errors
  • Declarative Pattern of Data Retrieval

Lecture 7:  Change Detection – 1 Hrs

  • Different strategy
  • How to optimize CD for better performance

Lecture 8:  Routing basics and Lazy Loading – 1.5 Hrs

  • Adding Routing modules
  • Adding feature modules
  • Lazy loading modules
  • Passing value from one route to another route
  • Route Guards

Final Project – Creating End to End CRUD operation using REST API – 3 Hrs

  • Creating Main Modules and Feature Modules
  • Adding service to perform
    • Create
    • Update
    • Read
    • Delete
    • Handling Error
  • Using service in various components
    • Add product
    • Delete Product
    • Product Details
    • Update Product
  • Adding authentication
  • Discussing how we can make this application architecture better

Closure – 1 Hrs

  • Discussion and doubts
  • Angular 8 features
  • Deciding the learning path

At the end, everyone will get a geek97 certificate.

b2

If required we can help you finding better opportunities also on basis of this training. We keep getting requirements, and on your approval, we will recommend you.

To attend register here: https://forms.gle/JSbp3yknZ7scr9BP7  and for any clarification send me a mail at debugmode[at]outlook.com

If you can not afford 4000 INR and really need training contact me at 9717098666 . I will see, how can I help.