Using strict mode in Javascript

‘use strict’ is a rather useful statement to have at the beginning of all Javascript modules or functions. It ensures that all code in the module is executed in strict mode. The usage is simple enough. "use strict"; // lot of code You can also enable strict mode to specific functions. function getSum(x, y) { "use strict"; return x + y; } Strict mode has to be at the beginning of files or modules - will not have the desired effect if used anywhere else. ...

Avoid Scope Pollution in Javascript

It is quite easy to pollute global scope by defining variables or functions that impact core functions. const parseInt = val => console.log("int parsed: ", val); parseInt(1); // int parsed: 1 parseInt has transformed into a printer, thanks to the above code. The practice of “overriding” global scope is not useful and should be avoided like the plague (If you are born in the wrong century - “plague is to be avoided at all costs”). Using such declarations - ...

Use Right Syntax for a Map

Map on an array is simple enough - const ran = ["1", "3", "5"].map(val => Number(val)); console.log("ran: ", ran); // ran: [ '1', '3', '5' ] map will specify one element at a time, which is passed to the callback function as val. Let’s say, we ignore the val. const ranToo = ["1", "3", "5"].map(Number); console.log("ranToo: ", ranToo); // [ 1, 3, 5 ] The above code works too. map takes a callback function and runs it on every element, so no problem with the above code. ...

Reusable Memoization Function

Let us see how we could use a reusable function that can ‘memoize’ any given function. Memoization is a technique that can be used in long, recursive code to cache results from previous executions and speed up the overall process. Previously we have seen an overview memoization in JS with an example of generating Fibonacci series using such techniques. But, what if you want to apply that for multiple operations? Say, you are building a super-calculator that outputs Fibonacci series, factorial of a number, sum-product of repeat combinations, etc. ...

Process one or multiple arguments within a function

Let’s say you have to write a function that doubles a given number. You also find out that you may get one number (in which case double that number), or multiple numbers (double all numbers). The first thought that comes to mind is to - use different functions (or) check type of input and process differently Consider the below code - const double = x => { if (typeof x == "object") return x.map(val => val * 2); else return x * 2; }; console.log(double(2)); // 4 console.log(double([2, 3])); // [ 4, 6 ] The given option is workable, but there is a shortcut way to do the same. ...

Shuffle an array in Javascript

Write a simple logic to shuffle a given array. Consider this array - const nums = [1, 2, 3, 4, 5, 6]; You can shuffle this array by using the following code - const nums = [1, 2, 3, 4, 5, 6]; nums.sort(() => Math.random() - Math.random()); console.log(nums); /* [ 1, 4, 5, 2, 6, 3 ] [ 6, 1, 4, 2, 5, 3 ] ... */ Each run of the routine will give you a different array, thanks to Math.random() expression. Subtracting one random number from the other can give you a positive or negative result - so the sort can be totally different and random. ...

Round-off numbers in Javascript

How do you round-off a number in Javascript? The simple way - console.log(Math.round("3.14")); // 3 console.log(Math.round("3.72")); // 4 Then, there are other interesting ways.. Round off to the nearest lower whole number Use Math.floor instead of round. console.log(Math.floor("3.14")); // 3 console.log(Math.floor("3.72")); // 3 Round off to the nearest higher whole number Use ceil. console.log(Math.ceil("3.14")); // 4 console.log(Math.ceil("3.72")); // 4 Just truncate the fraction Use trunc. console.log(Math.trunc("3.14")); // 3 console.log(Math.trunc("3.72")); // 3 Use a simple, fast way using ~~ The double tilde operator has an output like trunc. ...

Memoization in Javascript

What is memoization and where is it useful? Let us do a quick overview and dig into example code. Memoization is a technique that can be used in long, recursive code to cache results from previous executions and speed up the overall process. Consider a long repetitive operation where there is a good possibility that you will have the same arguments for the computation function more than once. What if we could make our program remember what had transpired in the last execution. We could then effectively shave-off cycles that had been done previously and speed up execution. ...

Global variables in async functions

How do global variables impact async functions? Does hoisting have a role to play at all? As many beginners have found out the hard way - yes. for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, 500 * i); } What’s the output you’d expect? // 0 1 2 3 4 What you get - // 5 5 5 5 5 If you have not already figured it out, the behaviour is because of the var used in for loop. ...

Find max and min numbers in array

What is the easiest way to find maximum and minimum of a given set of numbers? Well, that’s easy. console.log(Math.max(1, 3, 5)); console.log(Math.min(1, 3, 5)); // 5 1 How about an array? The first thing that comes to mind.. const nums = [1, 3, 5]; const max = nums.reduce((n, mx) => (n > mx ? n : mx)); console.log("max: ", max); const min = nums.reduce((n, mn) => (n < mn ? n : mn)); console.log("min: ", min); // 5 1 But, an easier solution is right in front of us. console.log(Math.max(...nums)); console.log(Math.min(...nums)); // 5 1 Moral of the story Never trust the first instinct. But, you are not likely to be as naïve as me - so YMMV.