JavaScript – Checking against NaN

NaN stands for Not-a-Number in JavaScript. Sometimes when writing JavaScript codes, you might need to check whether a variable is a number or not. For example, you declare a variable foo and assign NaN to the variable, i.e let foo = NaN;. Then you might think checking can be done this way: let foo =... » read more

JavaScript – How to get response from an asynchronous call

Promise in JavaScript is very handy for asynchronous task such as fetching a URL. Developers who use Promise a lot, often will have to call then() with 1 callback function in it. promise.then((result) => {}); promise.then(function(result){}); Prior to Promise, developers tend to use callback functions to handle asynchronous call in JavaScript. However, callback functions have... » read more

JavaScript – How to remove a particular element from an array

To remove an element from an array. First, we need to find the index of the element you wish to remove. var array = [100, 200, 300]; var index = array.indexOf(300); if (index > -1) { array.splice(index, 1); } console.log(array); Then remove it with splice() Output (2) [100, 200]

JavaScript – How to get current Date

To get current date. Use new Date() to generate a new Date object containing the current date and time. var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd < 10) { dd = '0'+dd } if(mm < 10) { mm = '0'+mm }... » read more

JavaScript – How do I loop through an object

Given an object as following: var o = { "k1": "value1", "k2": "value2", "k3": "value3" }; To loop through it, then do following: for (var key in o) { if (o.hasOwnProperty(key)) { console.log(key + " - " + JSON.stringify(o[key])); } } Output k1 - "value1" k2 - "value2" k3 - "value3" References: MDN Web Docs... » read more

JavaScript – How to check whether a string contains a sub-string

1. String indexOf() String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1. var haystack = "foo", needle = "oo"; haystack.indexOf(needle) !== -1; //Output: true 2. String includes() Starting from ES6, includes() determines whether one string may be found within another string, returning true or false as... » read more