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

Parallelize Work with Workers in Javascript

Use workers when doing lot of work that can be spawned off in another “thread”. How do you open parallel work threads today? Possibly using async functions? Async functions do not block the main thread but allow processing to take place in parallel. Well, almost in parallel - see how event loops work. Although async functions are non-blocking, the call back functions included therein do block the thread. One of the ways of managing truly async functions is through “workers”. ...

Cloning objects in Javascript

Cloning objects is easier than ever before, but you have to remember a few nuances. We will discuss about two ways to clone/copy an object - Deep copy: copy object so that any subsequent changes to new object does not reflect in older object Shallow copy: copy props and child objects of an object, but the new object keeps pointing to the original Both have their uses. Spread operator The quickest way to deep copy is using the spread ... operator. ...

Function returns undefined unless specified otherwise

Why is my function returning undefined when I have not mentioned that anywhere. The crux of the issue is in the topic header. All functions have to return something. If nothing is specified, they return undefined. function doSomething() { // do something } const something = doSomething(); console.log("something: ", something); // undefined You may however chose to ignore receiving something from the function. function doSomething() { // do something } doSomething(); Typically, I like to return at least a true or false - just for the heck of it. That’s overengineering to some, but that’s ok. ...