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.

Access an array in reverse in Javascript

Access an array in reverse. Consider the array in the code block below - const nums = [1, 2, 3]; Accessing the array is easy enough. console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); /* 1 2 3 */ But, what if you want to access the array from the last element? Use pop We have seen one of the ways to do that using pop. console.log(nums.pop()); console.log(nums.pop()); console.log(nums.pop()); /* 3 2 1 */ But, this changes the array. console.log(nums); // [] Use slice If you want to just access the array from the last element, but not change the array - ...

Optional arguments using spread while calling functions

How about using the spread operator for handling optional arguments, or for null arguments? Consider this code - function sum(x, y, z) { return x + y + z; } We can choose to pass ‘z’ or not, but ignoring ‘y’ returns an error. console.log(sum(1, 2, 3)); // 6 console.log(sum(1, 2)); // NaN console.log(sum(1, , 3)); // error: Unexpected token , Sure, you can use a null or undefined in the middle and get away with it. But, you could also replace that with the spread operator like so - ...

Console.log function for easier debugging

Encapsulate a console.log() in a function and use it anywhere - even within the most complex expressions. The most typical console.log - console.log("hello world"); // hello world Change it to - function logThis(expr) { console.log(expr); return expr; } logThis("hello world"); // hello Why the circus? Well, consider you are debugging this really serious planet array marked for destruction. const planets = [ { name: "mercury", position: 1 }, { name: "venus", position: 2 }, { name: "earth", position: 3 } ]; console.log(planets.sort().filter(planet => planet.position == 3)); Sure, you can unchain the chain and debug. console.log(planets); console.log(planets.sort()); console.log(planets.sort().filter(planet => planet.position == 3)); But, there is no joy in the above code (and in the destruction task I might add). Is there? ...

True comparison using Object.is()

Object.is() provides a true comparison for any object. Start using it today if you have missed out so far..! Consider the code below - console.log("abc" == "abc"); // true console.log(null == null); // true console.log(1 == 1); // true // break console.log(0 == false); // true console.log("" == false); // true While we are ok with the statements above break, the statements below can cause a problem. Typically this is overcome by using strict comparison - console.log("abc" === "abc"); // true console.log(null === null); // true console.log(1 === 1); // true console.log(0 === false); // false console.log("" === false); // false But, what about the only edge case that is so.. so.. so important - ...

Tagged Templates in Javascript

Tagged templates allow our beloved template literals to be taken to a whole new level. The typical use of a template literal is below - let x = 1; let y = 5; console.log(`x is ${x}, y is ${y}`); // x is 1, y is 5 Template literals allow us to avoid stupid statements like this - console.log("x is " + x + ", y is " + y); // x is 1, y is 5 Template literals are cool. Tagged templates take the above function in a different way - ...