Executing Functions Only Once in Javascript

Let us see how to execute a specified function only once in the life time of the program. The Simple Way The easiest way is to use a global variable and remember the function execution. We can then ignore all future invocations. let saidHello = false; function sayHello() { console.log("hello world"); saidHello = true; } function helloOnce() { if (!saidHello) sayHello(); } helloOnce(); // hello world helloOnce(); // nothing helloOnce(); The Reusable Way We can apply concepts similar to our debounce utility to execute a function once and only one time. ...

Reusable Debounce Function

Debouncing a function gives us a way to wait for input to stop and only then trigger a set of actions. This is particularly useful when we have to call a function only when user input is complete (or there is a gap in typing that we can utilise for processing). Debounce avoids sending multiple requests that load the client as well as server with needless processing. We have previously seen how debounce can be done using a simple timeout. ...

Return values from async functions

How do you return anything from async functions? How do you receive what is returned from async functions? Previously we have seen how return works in Javascript. I typically write functions that return at least a true or false value. function printThis(statement) { console.log(statement); return true; } const ret = printThis("hello world"); console.log(ret); /* output hello world true */ If the function described above is async - async function printThis(statement) { console.log(statement); return true; } const ret = printThis("hello world"); console.log(ret); /* output hello world Promise { true } */ If you are interested in the return value from an async function, just wait till the promise resolves. Use then or wrap function in await. ...

Coercions can be counter-intuitive, use same-type comparisons

Coercions are useful and almost intuitive, but beware of pitfalls. Consider below block of code - const x = 42; Numbers greater than 0 and not undefined are generally considered truthy. So, following is understandable - if (x) console.log("found the answer"); // found the answer But, you will be surprised if you do this - if (x == true) console.log("found the answer"); // nothing This seems counterintuitive to the previous test that did not use an explicit true check. The reason is simple. While the first comparison simply checked whether 42 is truthy (it is), the next code block compared the int 42 with Boolean true. ...

Array `forEach` not iterating all elements

I like Array.forEach() and use it whenever I need to iterate through elements. However one needs to be aware of its quirk. const arr = new Array(5); arr[0] = 0; arr[4] = 4; A typical for outputs all elements including those not initialized yet (hold your breath for a moment on the initialized thing). for (let i = 0; i < arr.length; i++) console.log("for rocks", arr[i]); /* output for rocks 0 for rocks undefined for rocks undefined for rocks undefined for rocks 4 */ Now, repeat the same for forEach. ...

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