Find Difference Between Arrays in Javascript

Use set and filter to find the difference between two arrays. let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; let difFruits = [...new Set(fruits1)].filter((item) => !fruits2.includes(item)); console.log(difFruits); // [ 'orange', 'grapes' ] Similarly if you want to find the elements common in both arrays, you could employ a slightly different strategy. let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; let commonFruits = [...new Set(fruits1)].filter((item) => fruits2.includes(item) ); console.log(commonFruits); // [ 'apple' ] Traditionally, you would have executed two loops to find differences between arrays. Something like - let fruits1 = ["apple", "orange", "grapes"]; let fruits2 = ["banana", "mango", "apple"]; const difFruits = []; for (fruitOne of fruits1) { let found = false; for (fruitTwo of fruits2) { if (fruitTwo == fruitOne) { found = true; break; } } // fruits2 loop if (!found) difFruits.push(fruitOne); } // fruits1 loop console.log(difFruits); // [ 'orange', 'grapes' ] We live in exciting times for sure.

Initiate Arrays with Data in Javascript

Create arrays and initiate data in a single statement. Traditionally you would do the below to initiate the array and fill it with values - let planets = ["mercury", "venus", "earth"]; This is a-ok if you know the values, but what if you want array to have fixed elements with pre-defaulted values? This is where fill (an ES6 feature) steps in. let planets = new Array(3).fill(""); console.log("planets: ", planets); // [ '', '', '' ] You could also instantiate only certain elements of the array as well. ...

Empty and reset objects in Javascript

Is emptying objects akin to destroying them? Is destroying of objects easier than creating them? Let’s find out. Initiate an object. let apple = { name: "apple", color: "red" }; console.log("apple: ", apple); // { name: 'apple', color: 'red' } Reset value // the easy way to reset apple apple = {}; console.log("apple: ", apple); // {} The above piece of code will reset apple object. Upon initiation memory was allocated to the defined object. Then, the variable apple was made to refer to the specific memory location where the object was stored. ...

Sleep Function in Javascript

Sleep holds off your function execution for specified time. This is super useful whenever you want to hold off something for ‘x’ time. Here are two ways in which you can get your program to sleep for a while. setTimeOut function sleep() { console.log("trying to sleep.."); setTimeout(() => { console.log(".. woke up after 3s"); }, 3000); } /* output trying to sleep.. .. woke up after 3s */ sleep(); Promise / async-await You could async the whole function to make it cleaner but there is no visible change to how your program executes :) ...

Template Literals in Javascript

Template literals provide an easily readable way to embed expressions within string literals. For example - const thirdSmartPlanet = "earth"; const fact = `${thirdSmartPlanet} is flat`; console.log("fact: ", fact); // fact: earth is flat Earlier, you had to combine strings and variable like so - const fact = thirdSmartPlanet + " is flat"; Hope you observed the backtick (’`’)? Not only that - You can output on multiple lines without breaking a sweat const statement = `dogs are our best friends`; console.log(statement); /* output dogs are our best friends */ Evaluate expressions ...

Destructuring Variable Assignments in Javascript

Destructuring assignment feature provides an easy, readable way to handle object and array assignments. ES6 introduced assignment destructuring, which provides a clean and more readable way to assign variables. The old way - const fruits = { apple: { color: "red" }, orange: { color: "orange" } }; const appleTheFruit = fruits["apple"]; console.log("color of apple: ", appleTheFruit.color); // red The new way.. const fruits = { apple: { color: "red" }, orange: { color: "orange" } }; const { apple } = fruits; // or also include orange: const { apple, orange } = fruits; console.log("color of apple: ", apple.color); // red The new syntax gives us a quick and easy way to get named props within an object. ...

Arrow Functions and `this` in Javascript

Arrow functions have made our life much much easier. You can now refer to this without fearing the bogeyman. How did we write functions in the dark ages? Here’s a typical function. function getSum(i, j) { // or const getSum = function(i,j) { return i + j; } console.log(getSum(3, 2)); // 5 The same functionality as arrow function - const getSum = (i, j) => i + j; console.log(getSum(3, 2)); // 5 Right off the bat you will see that arrow functions are assigned to variables, have an implicit return and structure wise do not different all that much from normal functions. ...

MeteorJS - Getting Started

Meteor is quite an easy Javascript framework to pick up and I have been fascinated getting back to where I left off a couple of years ago. There are quite a few things that you could do in the first week itself, and could even target to complete real-world projects. However, be aware - MeteorJS is a ghost town of sorts. The usage has declined rapidly over the past three years, and most of the content that you will find is outdated. Students of the framework will find older tutorials that do not quite work. For all my hubris, I still ended up spending time on debugging silly problems that should not have existed in the first place. ...

Generate Random Strings in Javascript

Generate random strings in multiple ways in Javascript. Use crypto The quickest and easiest way to generate random strings. const crypto = require("crypto"); var txt = crypto.randomBytes(10).toString("hex"); console.log("txt: ", txt); // a3f4ac84da8da6bf172b Crypto library is available in node. On the client side, use window.crypto. Use random Use Math.random() to generate a string of random set of characters and numbers. let a = Math.random().toString(36).substring(2, 15); console.log(a); // yzcjf8welj The above code converts a random number to to its base-36 form (toString(36)) and outputs the string after removing the prefix. ...

Handle Exceptions in Javascript

Get a quick-start on using try/catch to handle errors and exceptions. Consider the below example that expects name to be provided to the program. If name is provided you will go ahead and store record. let name = ""; if (name) { // store record } The big problem with the above code is absence of any kind of feedback to the caller (or user). You can do this to manage that error and notify the caller. ...