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 

Delivering two talks at Devfest Gandhinagar 2019

Ahmadabad is always very close to me as I did my first public speaking in this city back on 24 July 2010.  Since then I have been trying to do at least one workshop or talk each year here, so continuing the ritual, I am again coming to Ahmadabad/Gandhinagar on 13th October to speak in   Devfest Gandhinagar 2019

You can follow all happening of the conference here or follow them on twitter here

a

I am excited to deliver two talks. They are as follows:

Talk 1: JavaScript Interview Questions Made Simpler

Usually they ask these questions in a JavaScript interview.

  1. What is the value of ‘this’?
  2. What are the invocation patterns?
  3. Various ways to pass parameters to a function?
  4. Explain Hoisting?
  5. How to make objects properties read only?
  6. How to make objects properties private?
  7. Explain constructor and prototype
  8. What is __proto__
  9. How will you create inheritance in JavaScript?
  10. ES2015
    1. Arrow functions
    2. REST parameters
    3. Spread operator
    4. Default parameters etc.

I will try to simplify 5-7 topics from the above listed topic in a simpler and entertaining way.  This talk is for everyone and your main take away from this session would be at least that you will never forget what is value of ‘this’ 😉

Talk 2:  Simplifying RxJS in Angular for everyone

We all use subscribe() method in an Angular application to fetch data from the API. However, very rarely know beyond that, I will try to take you beyond obvious.  In this talk, I will start from the beginning of RxJS in Angular and then end at the best practices of using it.

  1. Using of, from creational functions
  2. Sharing data between two unrelated components
  3. Fetching data from the API
  4. Using async pipe
  5. Using other operators such as a map, forkJoin etc.

This talk is for the developers who are already working on the Angular.

I am excited to see you in both of my talks.  When you see me in the event, do not hesitate to say Hi and take a selfie together.

I wish to thank Yatendrasinh Joddha, Parth Jansari, Arif Khoja  , Bhavesh Valand, and the whole team of GDG Gandhinagar for inviting me. I hope to meet the expectation of audiences and teach them a few things.

Simplifying Maps in the JavaScript

t3

Maps is a data structure, which stores the key/value pair in an ordered way.  Since the inception of the JavaScript, objects are primarily used for the map.  Consider the below code listing:



var foo = {
    id:1,
    color : 'Red'
}

console.log(foo['id']); // 1 
console.log(foo.color); // Red

 


To store two key/value pairs, we have created an object foo and using the keys such as id and color to retrieve the values. It is straightforward, however using an object for the map has two major challenges,

  1. It is unordered, means it does not remember the original insertion order of the keys
  2. The only string can be used as the key

There is a challenge in using only string as the key. Let us consider the code listed below,



var z = {};

var x  = { id : 1};
    y  = { id : 1};

z[x]= 'foo';
z[y] = 'bar';

console.log(z[x]); // bar 
console.log(z[y]); // bar


Surprisingly bar is printed twice because,

  1. Objects can have an only string as the key
  2. Since x and y both are an object JavaScript is converting them to string  value ‘[object, Object]’
  3. For the z object, there is only one key ‘[object, object]’ is set

You can verify that there is only one key is set for the object z as shown below,



console.log(Object.keys(z)); // [ '[object Object]' ]


These are the problems in using an object as a map. You can solve it by using the Map object introduced in ES6.



var z = new Map();

var x  = { id : 1};
    y  = { id : 1};

z.set(x,"foo");
z.set(y,"bar");
console.log(z.get(x)); // foo 
console.log(z.get(y)); // bar


Instead of using square brackets, you use set() for write and get() for reading operations in the Map. The other essentials methods with Map objects are

  1. The delete(key) method – to delete a key
  2. The size() method – return the total number of keys
  3. The clear() method – delete all keys from the Map

These methods can be used as shown in the code listing below,



console.log(z.size); // 2
z.delete(x); // returns true
console.log(z.size); // 1
z.clear(); 
console.log(z.get(y)); // undefined
console.log(z.size); // 0


One important thing is delete method of the Map object is different from the delete operator, which is used to delete the object’s properties.

Reading values from the Map

You can read values from the Map using the values() method. It returns an iterator object that contains values for all the keys. It returns values in the order they were added to the Map.  You can use values() method as shown below,



var z = new Map();

var x  = { id : 1};
    y  = { id : 1};

z.set(x,"foo");
z.set(y,"bar");
z.set('range', 30);
let zvalues = z.values();
console.log(zvalues);


 

The values method return an iterator as shown in the below image,

t1

You can convert an iterator to an array using the spread operator or Array.from as shown in the below code listing:



let zvalues = z.values();
let zvaluesarray = [...zvalues];
let zvaluesarray1 = Array.from(z.values());
console.log(zvaluesarray); // ['foo','bar',30]
console.log(zvaluesarray1); // ['foo','bar',30]

 


 

Reading keys from the Map

You can read the keys from the map using the keys() method.



let zkeys = z.keys();
let zkeyaarray = [...zkeys];
console.log(zkeyaarray); 


 

You get an output as shown in the below image. Like values(,) method, the keys() method also returns an iterable, and you can use the spread operator to convert it to an array.

t2

You can use has() method to check whether a particular key exists or not, it returns true if the key exists otherwise false.



var z = new Map();
var x  = { id : 1};
    y  = { id : 1};

z.set(x,"foo");
z.set('range', 30);

console.log(z.has(x)); // true 
console.log(z.has(y)); // false 

 


 

The has() method returns false for y as it is not part of the map z.

Initializing Map with the Arrays

The Map constructor can optionally take an iterable object or an array as the parameter. You can pass an array as the parameter to the Map constructor as shown below,



const fooarray = [
    ['1', 'One'],
    ['2', 'Two'],
    ['3', 'Three'],
  ];

var z = new Map(fooarray);
console.log(z.get('1')); // 1
let zvalues = z.values();
let zvaluesarray = [...zvalues];
console.log(zvaluesarray); // [ 'One', 'Two', 'Three' ]


 

The Object and the Map

As we saw that objects could be used to work with key/value pair, however, there are substantial differences between using the object and the Map,

  • You can use functions and objects besides other primitive types as the key in the Map, whereas for the Object only string or Symbols can be used.
  • The keys in the Map are ordered, whereas Keys in the Object are unordered.
  • You can use the size method to find the size of the Map, whereas to find several properties in the Object, you have to do manually
  • A Map is iterable, whereas an Object is not, you need to fetch the keys and then iterate over them manually
  • Each Object has a prototype and its default properties, so you need to make sure that map keys name does not collide with the properties name from the prototype.

 

One more important factor is frequent read and write operations on a Map could be faster than of an Object.

WeakMaps

If you use an object as a key in a Map, and all the references of the object are removed, still object is not eligible for the Garbage Collection until its entry is not deleted from the Map itself.  Therefore, if a Map uses an object as a key, you will have to remove it from the Map to make it eligible for the Garbage Collection.  The other solution is to use the WeakMap; they are better suitable for the Garbage Collection.

In the context of Garbage Collection, Some of the characteristics of the WeakMaps are,

  1. It takes only objects as the key
  2. Objects are held weakly in the map
  3. If the reference of the object is removed, it is available for the GC and will also be deleted from the map
  4. If the object is garbage collected, the WeakMap will have no reference for it.

 

You can use a WeakMap almost in the same way as a Map. However, keep in mind that all the methods of the Map are not available with the WeakMap.  A WeakMap can be created, as shown below:



var z = new WeakMap();
var x  = { id : 1};
    y  = { id : 1};
    m  = { id:1 };

z.set(x,"foo");
z.set(y,'bar');

console.log(z.has(x)); // true 
console.log(z.has(y)); // true  
console.log(z.has(m)); // false 

 


Keep in mind that the WeakMap does not have methods such as:

  • values()
  • size()
  • clear()
  • keys()
  • entries()

If you perform these operations on the WeakMap, JavaScript will throw an error.

Summary

As you learned in this post that the Map object makes it simpler to work with a key/value pair in JavaScript. It has a rich API and should be used over an object.  I hope you like this post. Thanks for reading.

For any training or consulting need to reach me at debugmode@outlook.com or follow me on twitter @debug_mode, or if you prefer to let us connect on LinkedIn

Why you need Proxy objects in JavaScript

JavaScript is not truly Object Oriented language, hence implementing requirements as stated below could be challenging. For example,

  • Throw an error if the setting value of a property does not satisfy a particular condition
  • If the property does not exist on set some default value instead of undefined
  • If the property does not exist on reading operation throw TypeError
  • Create a private property on the object
  • Enforce property value validation
  • Enforcing value correct on the property

There are many ways some of the above stated problems can be solved, such that by using setter or getter to set default value or throwing an error or using an object’s methods such that isExtensible(), preventExtension(, etc to avoid adding dynamic properties etc. However, the more convenient way to handle the above problems is by using the Proxy object.

You can watch video on the proxy object here:

The Proxy object is a virtualizing interface to control the behavior of the object.  To understand the proxy in a better way, let us consider Product object as shown in below code listing:


let Product = {
    id:1,
    price : 78
  }

 

The Product object has two properties id and price. Now let us say that you want to run a business logic that price should not be less than 50, or reading value of the property, which does not exist, should throw error, etc.

You can solve most of the above problems by running custom logic while performing property lookup, set, get, and enumeration operations on the object. JavaScript proxy object exactly helps here. It allows you to add custom behavior to the fundamental operations on a JavaScript object.

po

 

The syntax to create a Proxy object is as shown in the below image:

po1

You create a proxy object using the Proxy constructor and passing two parameters in it.

  1. Target
  2. Handler

Target is the object, which proxy virtualizes and adds custom behavior to it. In our example, the Product object is the target as we are adding custom behavior to it.

The handler is the object, in which you write the custom behavior. In more technical words, the handler object contains the trap.

The traps are the methods, which gives the target object’s property access inside the handler object. Traps are optional, and if not provided target object’s default methods are used.   There are traps such as to get, set, has, setPrototypeOf, isExtensible, defineProperty, etc. You can use all of these traps in the handler do define custom behavior for the target object.

Let us apply a custom behavior on the Product object that, a read operation on the property that does not exist should throw an error.  You can create a proxy for that as shown in the below code listing :


var ProductHandler = {
      get:function(obj,prop){
          return prop in obj ?
          obj[prop] : new TypeError(prop + ' - property does not exist');
      }
  };

var productProxy = new Proxy(Product,ProductHandler);

 

Let us walk through the code; we created a proxy called productProxy using the Proxy constructor and in the Proxy constructor passing,

  1. The Product object as the target
  2. The ProductHanlder object as the handler.

The ProductHandler is using the get trap, in which it is checking if property exists in the object or not. If it does not exist, return a TypeError with the message.  Now read properties value as shown in code listed below:


console.log(productProxy.price);
console.log(productProxy.color); 

 

Since price property exists, you get 78 value printed, however when you try to read property color, which does not exist, JavaScript throws you an error as shown in the image below:

po3.png

The better use case of proxy is in validation. Using the proxy, a validation can be enforced on the property value.  Let us consider the code listed below,


let Product = {
    id:1,
    price : 78
  }

Product.price = -10; 
console.log(Product.price); // -10

We can set prices to a negative value. Using the proxy, we can avoid it by enforcing value validations, as shown in the code listed below:


var ProductHandler = {
    set : function(obj, prop,value){
        if(prop == 'price'){
            if( !Number.isInteger(value)){
                throw new TypeError('passed value is not a number');
            }
            if(value < 50){
                obj[prop]= 50;
                return true; 
            }
        }
        obj[prop]= value;
        return true; 
    }
};

var productProxy = new Proxy(Product,ProductHandler);

 

To enforce value validation handler object is using the set trap, in which it is

  1. Checking for the property price
  2. Verifying whether the passed value is an integer or not
  3. If the passed value is for property price is less than 50, setting the value to 50

Now when you set price to a negative value due to defined custom behavior in the proxy object JavaScript will not allow that, and you will get 50 printed for second read operation as shown in code listed below,


console.log(productProxy.price); // 78
productProxy.price = -10; 
console.log(productProxy.price); // 50

 

You can enforce id as the private property of the Product object as shown in the code listed below:


var ProductHandler = {
    get:function(obj,prop){

        if(prop == 'id'){
            throw new Error('Cannot access private property : id!');
        }
        else {
            return prop in obj ?
            obj[prop] : new TypeError (prop + ' - property does not exist');
        }
    }
};

var productProxy = new Proxy(Product,ProductHandler);

 

Here, in the get trap of the handler, we check if the property being accessed is the id property, and if so, handler throws an error. Otherwise, it returns the value as usual.

JavaScript Proxy objects are useful and allow us to add custom behavior to a normal object.  You can use it for various purposes such as validation, creating access modifier, setting default values, etc.  I hope you find this post useful. Thanks for reading.

For any Training or Consulting reach me at debugmode[at]outlook.com 

Step by Step implementing Two-Way Data Binding in Vanilla JavaScript

Data Binding is one of the most important features of all the frameworks. It ensures that the data model and the views are in sync with each other. It is very fundamental feature of any MV* frameworks such that Model-View-Controller, Mode-View-ViewModel, and Model-View-Presenter, etc.

Popular JavaScript based frameworks such that React, Angular have their way to implement it. However, it is a good idea to know how a basic two-way data binding can be implemented using vanilla JavaScript.  That would give you an overview of how much heavy lifting is done by the framework when you use features like data binding.

To get most of this post, you should have a basic understanding of following JavaScript features

  • Creating an object as literal
  • Adding a property with Object.defineProperty
  • Using setter and getter
  • forEach statement

 

You can refresh about JavaScript object creation in this video on geek97. Let us get started,

On the HTML, we have put one input text box and two span elements.  Whenever the user enters a value in the text box, data in <span> element should get updated.

We are going to write JavaScript for data binding in the databinding.js file, so we also added a reference to that in the HTML.

To start with databinding.js file contains an Immediately Invoked Function Expression (IIFE). We write all the codes inside this function,

At this point, on launching the application, you should get below output. Right now, if you enter anything in the Name field nothing would be affected.

cd1

Note: If you are using Visual Studio Code, install the extension Live Server, and run the HTML in the browser, right click on the file and from the context menu select “Open with Live Server” to launch the application.

Our first task is to select all the elements which have [data-geek97-bind] attribute set, and also check for their type. Right now, as we are creating binding only for input type text, so we can make a selection of elements and type checking as shown below,

We have created an empty object called dbrepo, which would maintain the state between the data bound elements. The dbrepo object would make sure that all DOM elements with [data-geek97-bind] attribute set to value ‘name’ is in sync and have the same value.

To achieve that, what all we need to do is to add a property dynamically to the dbrepo object for each unique value of [data-geek97-bind] attribute in the DOM elements. For that, let us create a function called addToScope. In the function, we check whether a particular property exists or not, if not then using the Object.defineProperty() method adds a property to the dbrepo object.

Using the hasOwnProperty() method, determining whether property already exists or not, if not then add it using the Object.defineProperty() method. You can learn more about property descriptor and Object.defineProperty() here

We need to do some work in the setter function.

  • First, find all the elements with data-geek97-bind attribute set to the same value.
  • If the element type is text, set its value, otherwise set innerHtml of the element

Above two tasks can be performed in the setter function as below,

Putting everything together, code to perform two-way data binding is as below:

If you want to change the value in the code by just rewriting the value of the property in the dbrepo object,

At this point, on launching the application you should get below output. Right now, if you enter anything in the Name field, the other two spans would be affected.

cd2

Still, there is scope for much improvement in this code,

  1. Instead of rewriting the innerHtml, append the next text
  2. Extend it for other types than text.

I hope you find this post useful. Thanks for reading.

 

Type of Undeclared Variable in JavaScript: What is it?

 

Have you ever thought, what is type of undeclared variable in JavaScript? I know, the first thing that might come to mind is: how can an undeclared variable have a type? Yes, in JavaScript it is possible.

To understand it, let us start with understanding types in JavaScript. There are seven built in types in JavaScript. They are as follows:

  1. null
  2. undefined
  3. boolean
  4. number
  5. string
  6. object
  7. symbol (added on ES6)

Each variable with assigned value has a type. Let us consider the code listed below:

As you can see in the above snippet, if there is no value assigned then type of variable is undefined.

So far so good, we saw that variable with no assigned value is undefined.  Let us consider the next code snippet:

We have created a variable koo and have not assigned any value to it.  Now both value and type of koo are set to undefined.

Read full article on the Infragistics blog

Presented in ng-India 2019

ng-India is India’s largest conference on Angular and JavaScript. It happened on 23 Feb in Gurgaon, India and was attended by around 350 developers around India. There were speakers from all across world teaching on various topics such as Ivy rendering, Webpack, RxJS, Change Detection in Angular, Directives, ViewEncapsulation, ngRx etc.

I also had an opportunity to deliver a 30 min talk on “You do not know about JavaScript object “. You can find recording of my talk here: https://www.youtube.com/watch?v=h9eW0zSiFaw&t=9s

 

I also did welcome note for the conference, which can be find here:

https://www.youtube.com/watch?v=1CEWDQyCrmc&t=1s

 

You can find all talks from ng-India 2019, on geek97 YouTube channel

https://www.youtube.com/channel/UC9qYCj-KbQYJ_1fmnuULr4Q/videos

 

Thanks for watching my talk. Let me know your feedback.