Posts

Showing posts from August, 2020

Null, undefined and empty checks in JavaScript

Whenever you are writing code in Javascript, the Most common point comes where you and your code reviewer comes to a point to write fail-safe code. When we are talking about fail-safety, the prominent use case comes to check null, undefined, and empty text values. It is very important to handle these values in order not to come across a code failure at runtime. If there are use cases where your variables attain null or undefined you will be in a position to understand and handle it. In JavaScript, the state with no value is represented by  null   or  undefined . It is one of the  primitive values . The most common way to handle the null value is to just put the variable in if condition check. var myVariable = null; //typeof null is "object" and treated falsy if(myVariable){ //resolves to false as value is null console.log(‘I will not print if the value is null.’); } Similar to null, undefined is also treated as falsy. The difference between undefined and null...