indexOf vs. find for Arrays

Both indexOf() and find() are used for finding a pattern within an array. How are they different? indexOf requires the exact string to search within array. const nums = [1, 3, 5, 7, 9]; console.log(nums.indexOf(3)); // 1 indexOf behaves very much like its string counterpart which helps to search a substring within a string. You cannot do anything more complicated than that. You can provide super powers to your ’locating an element’ quest using find and findIndex. ...

Use variable value for object prop

How do you set a variable as the prop of an object? Consider the below code - const earth = { name: "earth" }; If we have a dynamic prop for earth, we can do - let lifeExists = "life"; const earth = { name: "earth" }; earth[lifeExists] = true; console.log(earth); // { name: 'earth', life: true } To define a new, dynamic prop - First we define the variable - lifeExists We then use that variable value as a prop and set the prop value earth[lifeExists] = true. Note that we cannot use earth.lifeExists = ... since we are not interested in lifeExists as a string literal, but only in its value (life) So, why use a dynamic prop? Because props may be set within our code or from the data retrieved from database. Javascript by itself will not be aware of all possible props for our object. ...

Create Null Object in Javascript

Creating a null object is simple, but not in the way you may think. Consider the below code - const earth = {}; earth is empty but not null. See - console.log(Object.toString(earth)); // function Object() { [native code] } console.log(earth.__proto__); // {} console.log(earth.hasOwnProperty()); // false console.log(Object.getOwnPropertyDescriptors(earth)); // {} If you want a truly empty object, you would want to do this - const nullEarth = Object.create(null); Now the previously tested code yields different results - console.log(Object.toString(nullEarth)); // function Object() { [native code] } console.log(nullEarth.__proto__); // undefined console.log(nullEarth.hasOwnProperty()); // error: nullEarth.hasOwnProperty is not a function console.log(Object.getOwnPropertyDescriptors(nullEarth)); // {} The new object is an object all right, but does not have a property and inherits from undefined rather than an empty object.

Swap values between two variables

Swapping variables is simple enough, but can it be any simpler? Consider the below code - let x = 1; let y = 3; To swap values - let z = x; x = y; y = z; console.log(x, y); // 3 1 Applying our earlier knowledge about destructuring objects(/destructuring-assignments-in-javascript/), we can instead do - let x = 1; let y = 3; [x, y] = [y, x]; console.log(x, y); // 3 1 Beautiful, isn’t it?

Simple type conversion in arrays using map

Type conversion is a big deal, but not anymore? Just use maps against a given array and them conversion shortcuts to simplify type conversion in Javascript. Consider the below array - const nums = [1, 3, 5, 7, 9]; We can convert the type to string using a map. const nums = [1, 3, 5, 7, 9]; const numsStr = nums.map(val => String(val)); console.log("numsStr: ", numsStr); // [ '1', '3', '5', '7', '9' ] Since String by itself is a function, we can simplify the code further. const nums = [1, 3, 5, 7, 9]; const numsStr = nums.map(String); console.log(numsStr); // [ '1', '3', '5', '7', '9' ] Similarly, we can convert an array of strings to array of numbers. ...

Name thy variables while destructuring arguments

Destructuring is useful but what if you have conflicts with the variable names provided by the object being imported? Consider the following example where we destructure arguments of a function. const getSum = nums => { let { x, y } = { ...nums }; return x + y; }; console.log(getSum({ x: 1, y: 9 })); //10 We can get into a pickle if the function already has a variable x. Well, not exactly in the above example but in a real world program that tends to have a hundred lines of code, and interact with a thousand other components. ...

A simple way to specify required function arguments

Specifying one or more arguments as required is one of the common patterns in Javascript. We will see one of the ways in which we can (arguably) make it more simple. Consider the function below - function getSum(x, y) { return x + y; } console.log(getSum()); // NaN We typically check arguments within function where necessary .. function getSum(x, y) { if (!x || !y) throw "Either x or y is empty. Provide valid values."; return x + y; } console.log(getSum()); // Either x or y is empty. Provide valid values. A simpler way to accomplish the same result - ...

Simplify Conditionals Using Objects in Javascript

Conditional statements and objects - are we talking about the same thing here? Do they have anything in common? Not quite similar, but you could simplify your conditional statements using objects. Consider the below tax rate calculation logic - const incomeLevel = "high"; let taxRate; if (incomeLevel == "very low") { taxRate = income * 0.1; } else if (incomeLevel == "low") { tax = income * 0.3; } else if (incomeLevel == "medium") { taxRate = income * 0.4; } else taxRate = 0; console.log("tax rate:", taxRate); // 0 The multiple ifs can be avoided by using a simple object - const incomeLevel = "very low"; const taxRateRef = { "very low": 0.1, low: 0.3, medium: 0.4, high: 0 }; const taxRate = taxRateRef[incomeLevel]; console.log("tax:", taxRate); // 0.1 Both objects and arrays alike find a lot of use in real-world scenarios to avoid complex loops. They also keep code simple, readable and maintainable.

Map vs. Object in Javascript

When should use maps? What are maps anyway? Using an object is cool. We do it all the time - const earth = { name: "earth", position: 3 }; What if we do not have all props at once, but rather incrementally assign props. const earth = { name: "earth", position: 3 }; for (ele in earth) { console.log(ele); } /* output name position */ The order of elements in an object is not guaranteed to be the same as provided in input. This is where a map comes in. Although technically a map is just an instance of an object, it differs in that a map maintains the input order of its elements. ...

Break and Continue in Javascript

Javascript does not have goto - thankfully. But it has continue and break that more or less perform the same function. If for any reason you want to jump out of a loop, here’s how you can do that - for (let i = 0; i < 10; i++) { console.log("i is", i); if (i > 1) break; } But, what if you want to jump to a particular statement? That’s where break can help. outerloop: for (let i = 0; i < 10; i++) { console.log("i is", i); innerloop: for (let j = 0; j < 10; j++) { console.log("j is", j); if (j > 1) break outerloop; } } /* output i is 0 j is 0 j is 1 j is 2 */ Similar to break, you can use continue to continue loop. ...