Property Descriptors in Javascript

Property descriptors define property behaviour. They are attributes of the property. Everything is an object in Javascript. Yes, I know - except those pesky things called primitives on which objects are built. We saw some (quick discussions on objects and properties)[/objects-and-props-in-javascript/] before - but I wanted to outline the descriptors further. You can see it yourself using a simple statement. let apple = { color: "red", size: "big" }; console.log(Object.getOwnPropertyDescriptor(apple, "color")); // { value: 'red', writable: true, enumerable: true, configurable: true } This is telling me what I could potentially do with color property other than seeing the value. ...

Currying in Javascript

Currying is a technique of splitting functions with one or more arguments into a sequence of functions that are invokable with predefined arguments. In other words, you can split fn (a,b,c) into fn(a)(b)(c). That was not quite helpful - let us see an example. let getSquared = (x, y) => { return x * y; }; let getSquared = getProduct.curry(2); console.log(getDouble(3)); // 9 Before you rush to your editor to introduce this in your project know this - it may not work as-is in your JS installation. Either you need to install a package that supports currying or write one yourself. ...

Comma operator in Javascript

Did you know how to use comma operator in Javascript? A simple , can separate expressions in the same statement, evaluate left-to-right in the expression, pick the right most valid value as the result, and confuse other developers - all within the blink of an eye. We have discussed about operators when discussing operator precedence. But the no. of uncommon operators are more than the typical bunch. Oh, and btw, comma has the lowest precedence amongst all operators. ...

Javascript `typeof` issues and what to do about them

typeof is useful but has inherent issues. There are gaps between what a developer expects in terms of consistency and what typeof delivers. Let us look at a few examples - const i = 1; console.log(typeof i); // number typeof is a unary operator, and does not require brackets. If you indeed put the brackets around the input, they just group the input and nothing more. More examples - console.log(typeof (1 + 2)); // number console.log(typeof ""); // string console.log(typeof undefined); // undefined console.log(typeof { fruit: "apple" }); // object console.log(typeof ["apple"]); // object console.log(typeof new Date()); // object console.log(typeof null); // object You may observe that - ...

Array `copyWithin` - what's the point?

You must have seen the copyWithin() method for an array, and surely wondered what it can do. copywithin copies elements from one position to another position in the same array. (Just kidding about the wondering thing - no one ‘wonders’ today, they just Google). const fruits = ["apple", "orange", "grapes", "banana"]; fruits.copyWithin(2, 0, 2); // copy 2 ele from [0] to [2] console.log("fruits: ", fruits); // [ 'apple', 'orange', 'apple', 'orange' ] copyWithin has the below syntax. array.copyWithin(target, start, end) It copies the elements from start to end to the target position. ...

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 ...