Three quick ways to convert objects to arrays

Easily convert objects to arrays and iterate to your heart’s content. There are multiple ways of converting an object to an array (which, also is an object but a different one at that.) Method 1: A simple Object.values() method The first idea that comes to mind is to just use Object.keys(), Object.values() or Object.entries() to generate an array. const numO = { a: 1, b: 2, c: 3, d: 4, e: 5 }; console.log(Object.values(numO)); // [ 1, 2, 3, 4, 5 ] Method 2: Apply transformation logic during object to array conversion If you are going fancy about the conversion and want to include some logic therein - ...

A Different IIFE Syntax

Here’s a different syntax for our favourite IIFE’s. Immediately invoked function expressions enable us to write functions without using “functions”. Well - just kidding. They are functions but with a different syntax. A typical IIFE looks like this - const x = 1, y = 9; var sum = 0; (function() { sum = x + y; console.log("sum: ", sum); }(); /* output sum: 10 */ There is another interesting syntax that is lesser known. At least it was not known at all to me-self until I came across the syntax in some library. ...

Conditionally copy props to new object in Javascript

Here’s a shorter, readable way to copy props from one object to another subject to defined conditions. The shortest way to copy object (when you don’t quite care about copying sub objects by reference) - const planet = { name: "earth", position: 3 }; const newPlanet = { ...planet }; console.log(newPlanet); // { name: 'earth', position: 3 } But, what do you do if you want to copy only name but not position? A common way to do that will be - const planet = { name: "earth", position: 3 }; const newPlanet = {}; Object.keys(planet).forEach(key => { key == "position" ? "" : (newPlanet[key] = key); }); console.log(newPlanet); // { name: 'name' } Not bad - the code is readable and we have accomplished the task in two lines. ...

Initialize empty object and add props

There are situations when you need to initialize object without props. How do you manage that it Typescript? Let’s consider the example below. First, we declare the object and initialize it to an empty object. const planet = {}; Then, we add the props - planet.name = "earth"; The above initialization + assignment combination is perfectly valid in Javascript. But Typescript does not agree with planet.name since the object was declared as type {} (an empty object). ...

A simpler curry for Javascript

A simpler way to do curry functions in Javascript. We have previously seen currying in Javascript. A simple form and application of that concept is demonstrated below - const addThem = add.curry(2); const addTotal = addThem(1); console.log("addTotal: ", addTotal); // 3 Or, we could avoid a external function or library and curry using bindings .. function add(x) { return function(y) { return y + x; }; } const addEm = add(1); console.log(addEm(2)); // 3 But, there is a simpler way to get the same result. We just use arrow functions to collect arguments at different times. ...

Implicit return gotcha for arrow functions

Beware of using implicit returns in arrow functions. Consider the below example of a simple arrow function. It returns a simple variable. In the absence of any other statement in the function body, a simple mention of x will return the value of x. const getStuff = x => x; console.log(getStuff(1)); // 1 Let’s modify the block. We now want to return an object with the input value within it. const getMoreStuff = x => { x: x; }; console.log(getStuff(1)); // 1 Oops.. We expected {x: 1} but got 1 because the flower brackets were treated as enclosing a function body and not an object. ...

Use onclick event instead of 'submit' in Javascript

Use onclick rather than submit in HTML forms. A typical HTML form has a few fields and a button to submit the data to some back-end server. And, the typical way to do the form submission is through the submit method. <form action="/helloMessage.php"> <input type="text" id="name" /> <button type="submit"></button> </form> On clicking the button, the page will submit data to helloMessage.php, receives any response from PHP page, and (can be configured to) displays the response. [Or, the page could redirect somewhere else based on the submission status, but we will not discuss that here] ...

Use await without async function in Javascript

How can you use await without an async function? Don’t click or proceed further if you are not into practical jokes. Say, you try using await in a “normal” function or directly within a module.. function getWeather(loc) { const weather = await fetchWeather(loc); return weather; } // SyntaxError: await is only valid in async function You receive a compilation error that await can be used only in async function. But, if I have to use await but do not want to create a separate function with its own memory space, what should I do? ...

Generate Fibonacci series using generators

Generate Fibonacci series with generators and feel good about yourself. Previously you have seen how the totally practical example of generating Fibonacci series was breathing fire with memoization, and may have also come across using loops or recursion to solve the same problem. But, there is no fun in all that - this is real-life and we have to “generate” fun (yep, there we go again). If you have forgotten your schooling, here’s the series - any number is the sum of previous two numbers (except the first two, of course). ...

Function object and Function in an object

Previously, we have talked about all things being an object in Javascript. But to what extent can we apply this to our beloved functions. You can see this almost everywhere with the below syntax - const getSum = (x, y) => { return x + y; }; console.log(getSum(1, 2)); // 3 We have also touched upon how function is an object and how that helps in using closures and currying. For now, let’s leave all those complex things behind. Function being an object implies that we can do this - ...