Quickly Initiate Objects in Javascript

Initializing objects can be a pain. You may end up with multiple checks if you are trying to set a specific prop in the object path to a pre-defined value. For e.g. set color of a Kawasaki bike to ‘blue’. To do this we have to traverse through the object path from the root through color. This may be made more difficult if you may or may not get a partial array from an external function or a third party system. ...

Use Filter to Eliminate Duplicates in Javascript Array

Use array filters to remove duplicates in an array. We have seen how we could use sets or an intermediate object in a loop to eliminate duplicates within array.There always is a better way of doing things. Why not use filter to make the code more readable and not use set at the same time :) ? Consider this array - const nums = [1, 5, 0, 1, 2, 3]; The below code will create a unique array. const uniqueNums = nums.filter((num, index) => { return nums.indexOf(num) == index; }); console.log(uniqueNums); // [ 1, 5, 0, 2, 3 ] Why will this work? Well, because nums.indexOf(num) always returns the first index of a particular element. ...

Search using Array.find() in Javascript

Are you doing array search using the old school for-loops? Time to change, kid. Consider this array - const fruits = [ { name: "apple", color: "red" }, { name: "orange", color: "orange" }, { name: "pear", color: "green" } ]; To search for a specific value - console.log(fruits.find(val => val.name == "pear")); // { name: 'pear', color: 'green' } console.log(fruits.find(val => val.name == "grapes")); // undefined We use the Array.find method to retrieve search results. The argument for find takes a function which has the condition for find. In our case we pass a val which represents each item in the array, and compare the name prop to the given value. find returns the matched item or undefined. ...

GroupBy in Array using Reduce in Javascript

There is a really cool way to do group by in an array using reduce. The problem statement - you have an array of objects and need to create different arrays based on similar attributes. This is very similar to the SQL group by statement. Consider the example array - const fruits = [ (apple = { color: "red", shape: "round" }), (watermelon = { color: "green", shape: "square" }), (orange = { color: "orange", shape: "round" }), (pear = { color: "green", shape: "pear" }) ]; We have to group by color - all reds in one array, greens in next array and so forth. This can of course be done with a multiple, nested for loops. Or, you can push the array through a reduce statement that is fed an interesting function. ...

Manage Client Side Secrets in Javascript

How do you maintain secrets on the client-side? In one sentence - there are no secrets client-side. If you don’t want anyone to know about the secret, you should not send it to the client. The need for secrets Client may need user ids/passwords, API keys, API secrets etc. None of them can be trusted to the client. Your cookies can be read by a user or a client-program, your local storage is readable by users or third party sites, and your code is accessible by users. ...

Convert Strings to Numbers in Javascript

There are multiple ways to convert a given string to a number - so, which one to use and where? You would have also seen the more generic post on how to cast value from one type to another. But it may not be so apparent on which option to pick when you need to get numbers from a given string. The first approach is my preferred one. console.log(Number("hello")); // NaN console.log(Number("abc123")); // NaN console.log(Number("123abc")); // NaN console.log(Number("123")); // 123 console.log(Number("123.12")); // 123.12 The values returned by Number evaluate to true or false as expected. You could easily check for valid numbers and abandon operation if the string is not a number. ...

Default Function Arguments in Javascript

You can easily introduce default values for the arguments passed to a function. Consider this function - function sayHello(name) { return `hello ${name}`; } Calling this function without arguments will provide a not-so-pretty string. console.log(sayHello()); // hello undefined Even if someone had an existential crisis, I doubt they will like to be called ‘undefined’. So - let us change that. function sayHello(name) { name = name || "world"; return `hello ${name}`; } The ‘or’ statement will - retain name value if provided assign ‘world’ to name if name is falsy The results are more pleasing. ...

Convert String to Title Case in Javascript

We have a string.toLowerCase() and string.toUpperCase() in Javascript, but no out of the box function to convert to title case. Fear not if you are in that pickle - it is quite easy. function ConvertTitleCase(str) { const strArr = str.toLowerCase().split(" "); for (let i = 0; i < strArr.length; i++) { strArr[i] = strArr[i][0].toUpperCase() + strArr[i].slice(1); } return strArr.join(" "); } console.log(ConvertTitleCase("hello world")); // Hello World ConvertTitleCase takes one argument, which is a string. The string is split into distinct word array (split at ‘space’), and each word is then converted to initial cap. ...

Universal Apps and MeteorJS in 2019

I was a MeteorJS fan. MeteorJS was an excellent tool to quickly create universal apps. I was not quite a professional developer back in the day (circa 2016-17) but I could recognize the power of Meteor in developing complex web applications that could potentially deployed for multiple devices. There was a time when I was flabbergasted as I, rather alarmingly, saw people moving from Meteor to different platforms. I could not quite understand why. ...

For Loop Performance in Javascript

There are many types of for loops for an array - which should you use? How will you balance performance vs. code readability? Is that even a valid question? Let’s see a few cases. We will be seeing these distinct for loops today - for for-in forEach Note that the performance can be safely ignored for one off loops that do not hold up the user. If you are having an array of 15 elements and loop through it to display records on UI, it is not likely for you to even observe the difference in milliseconds. ...