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

Generators in Javascript

What are generators and how can I use them? How do you write loops in Javascript - Simple for/while? Recursion? In other less exciting ways? How do you throttle and control function execution? Debounce function? Build your own? What if you could produce the right mix of reusable functions, looping and throttling in one go? Enter generators. What are Generators? Generators are functions that lets you can control iteration. You can use generators to suspend execution of a function while saving the context for continuing the execution at a later time. ...

The NPM Problem in Javascript

Is there really a problem with NPM use? Short answer: no. Long answer: it’s complicated. I am nothing but thankful for the tonnes of NPM packages. I would never have built web applications that could support thousands of users all by myself without all those hundreds of packages. There are thousands of developers (if not millions) who do much better than what I could. With NPM to support what I do - I just identify the right solution, search in NPM / GitHub, and most of the times find it. At least I find something in the general area of what I am looking for. ...

Flatten recursive arrays

Flatten recursive arrays using Array.flat(). We have seen how to flatten arrays before. Array.flat() is quite useful to flatten arrays in one statement and output a simpler array. But, what about situations where you do not know the depth of array hierarchy - const nums = [[1, 2], [3, 4], [[5], [6]], [[[7]]]]; Fear not. Array.flat() takes in an argument to flatten to a specific depth or flatten everything. console.log(nums.flat()); // [ 1, 2, 3, 4, [ 5 ], [ 6 ], [ [ 7 ] ] ] console.log(nums.flat(2)); // [1, 2, 3, 4, 5, 6, [7]]; console.log(nums.flat(Infinity)); // [ 1, 2, 3, 4, 5, 6, 7 ]

Filter Falsy Values in Array

Remember to filter your arrays before doing array-wise operation. Filtering falsy values must be the first operation even if you do not have specific filtering requirements. Consider this array - const nums = [1, 3, 5, undefined, 7, 9, null]; If you are in control of the data source, you can very well expect to filter only when necessary. But any kind of array operations, or data from external systems can cause all kinds of unexpected results. We have seen how unexpected values impact array sort before. As you can imagine filtering goes beyond a simple array sort. ...

Date without brackets in Javascript

Can you use the Date object without brackets? Yes, apparently - to a friend’s delight and my chagrin. I should know better than to rely on my somewhat shaky Javascript knowledge. This is the format for a sane Date code.. const today = new Date(); console.log(today); // 2019-08-23T09:31:12.181Z If you want to pass parameters - const firstDay = new Date(2019, 0, 1); console.log(firstDay); // 2019-01-01T00:00:00.000Z This simply means that firstDay is created by passing variables to Date, which are in turn being used by the date constructor. ...

Load external scripts asynchronously

Load external scripts asynchronously in Javascript. We have seen about loading functions asynchronously in Javascript. But, what about the scripts that you load from other files, CDNs or other external sources You can do a simple async to load scripts without impacting the loading speed as perceived by the user. <script src="loadMe.js" async></script> This will load loadMe in the background without impacting any elements displayed on the page. Alternatively, you can also do a defer. ...

Don't use arguments object in Arrow functions

Arguments object throws an error when used with arrow functions. Consider this code - function getSum() { return arguments[0] + arguments[1]; } console.log(getSum(1, 2)); // 3 The result is as expected. But, you cannot do the same using an arrow function. const getSum = () => { return arguments[0] + arguments[1]; }; console.log(getSum(1, 2)); // gobbledygook or error You will see a function definition, or an error depending on the runtime engine. Arrow functions do not provide the binding for arguments object like regular functions. ...