9 JavaScript Hacks Nobody Talks About

9 JavaScript Hacks Nobody Talks About

Features and tricks to reduce workload and write neat code.

Photo by [engin akyurt](https://cdn.hashnode.com/res/hashnode/image/upload/v1630753842230/vh18M8tzR.html) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)Photo by engin akyurt on Unsplash

JavaScript has quite an extensive list of applications, from web development to Machine Learning to app development.

Fortunately, JavaScript provides a comprehensive list of features that can come in handy but many of these features and hacks aren’t popular and rarely talked about.

With such a huge array of applications and use-cases, the complexity of the code increases as well, and knowing tips and tricks can surely save you tons of time.

Therefore, I have curated a list of 9 JavaScript hacks that nobody talks about:

1. Quick Resizing and Emptying Arrays

We often need to change or empty an array while programming.

The most efficient way to do this is by using the Array.length method.

const array = [1, 2, 3, 4, 5];
console.log(array); // 5

array.length--;
console.log(array); // 4

array.length += 15;
console.log(array); // 19

The output of the code snippet would be:

[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 4, ..15 empty]
undefined

You can also remove all the elements of the array by setting the length to 0.

let arr= ['a', 'b', 'c'];

arr.length = 0;

console.log(arr.length); // Ouput=> 0
console.log(arr); // Output=> []

2. Shortcut for Conditionals

During programming, you may want a certain piece of code when a certain condition is fulfilled.

For example, you may want to show the login page to a user who isn’t logged in and when the user is logged in, you want to show the home page.

Such logic can be implemented using conditional statements.

var x=1;

if(x==1){
    console.log(x)
  }
else{
    console.log("Error")
  }

However, such logic can easily be implemented using ternary operators(? and :).

It takes three operands: a condition followed by a ? , followed by the expression to execute if the condition is true, followed by a : , and then the expression which has to be executed if the condition was false.

Let’s see the code to understand it better.

var x=1;
console.log( x==1? x: "Error"); //Output: 1

3. Dynamic Imports

The standard way of importing modules is simple, but what about the times when you need to import functions dynamically?

import defaultExport from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";

You may need to import some specific modules only when certain conditions are met and this is where dynamic imports come into play.

You can use the import function to dynamically import modules.

To dynamically import, use the keyword importas a function and pass in the module name.

import('some-module')
     .then(obj => ...)
     .catch(err => console.log(err))

As you can see, it returns a promise, resolving into a module object.

While static imports can be used for importing critical and necessary modules, dynamic imports offer a few benefits:

  1. Static imports can increase the loading time of your code and can also lead to unused modules.

  2. Static imports specifier strings can’t be generated dynamically.

  3. Static imports can lead to unnecessary memory usage.

4. Nullish Coalescing Operator

Nullish coalescing operator(??) can be a real-time-saver if you need to check if a value is null and if they are, then assign a default value.

This can prevent unforeseen errors and unexpected behaviors in your app.

const name = null ?? 'Anonymous';

console.log(name); // Output=> 'Anonymous'

const age= undefined?? 18;
console.log(bar); // Output=> 18

In other words, this operator returns the right-hand side operand when the left-hand side operand is undefined( or null).

The enormous advantage that this operator offers is instantly apparent.

It will not only result in more error-free code, but it will also aid in the avoidance of unintended activities that may result in crashes.

It is worth noting that the OR operator(||) can be used to achieve the same.

let firstName = null; 
let lastName = null; 
let nickName = "Guest";  // shows the first truthy value: alert(firstName || lastName || nickName || "Anonymous"); //Guest

The OR(||) and the nullish coalescing operator(??) have a slight difference — the || operator returns the first truthy value whereas the ?? operator returns the first specified value.

5. Merging Arrays

The larger the dataset, the more computational power it takes when merging two arrays.

The simplest and common way is to use the Array.prototype.concat() method.

const array1 = ['a', 'b', 'c'];
const array2 = ['a', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3); 
// Output=> Array ["a", "b", "c", "a", "e", "f"]

However, when dealing with humongous datasets, the Array.prototype.concat() is not the most efficient choice because it is a memory-intensive task as it creates a new array.

In such cases, using the Array.push.apply(arr1, arr2) method is a better choice because it merges the two arrays without creating a new one.

let list1 = ['a', 'b', 'c'];
let list2 = ['a', 'e', 'f'];

list1.push.apply(list1, list2);
console.log(list1);
//Output=> Array ["a", "b", "c", "a", "e", "f"]

6. Minimal Evaluation

If you are assigning a variable to another one, you may want to check that the value of the variable you are assigning is not null.

This operation can be simply performed by using a if statement, however, writing if statement with multiple condition evaluations can be cumbersome and might even lead to errors.

if (var1 !== null || var1 !== undefined || var1 !=='') {
     var2 = var1;
}

But the shorthand way of achieving this is present in JavaScript.

var2 = var1 || 'Some value';

7. Default Parameter Values

Your app may be giving a choice to the user to enter a custom value or use the default one.

This is commonly seen in interest calculator apps where a default rate of interest, say 6.5%, is used unless a different one is provided by the user.

This logic, again, can be simply implemented using the if statement.

function calculator(principle,rate,time) {
  if (principle === undefined)
    principle = 5000;
  if (rate === undefined)
    rate = 6;
  if (time===undefined)
    time = 3;
  ....
}

The shorthand way of implementing this is actually quite straightforward.

function calculator(principle=5000, rate=6, time=3){
   ...
}

You basically assign the default value in the function declaration itself.

8. inOperator

If you want to check if a specified property exists in an object or in its prototype chain, the in operator will facilitate this.

In other words, the in operator makes it easier to check whether a defined property exists in an object or in its prototype chain.

const car = { make: 'Honda', model: 'Accord', year: 1998 };

console.log('make' in car);
// expected output: true

delete car.make;

if ('make' in car === false) {
  car.make = 'Suzuki';
}
console.log(car.make);
// expected output: "Suzuki"

This operator returns trueor false .

When working with the DOM(Document Object Model), this property can be extremely helpful.

var q= "onrender" in  document.createElement("div");
if(q){
  ...
}
else{
  ...
}

You can read more on this operator here.

9. Mandatory Parameter Check

At times, you need to have certain values to successfully complete a task.

For instance, when signing into your email account, you have to provide the email address.

Similarly, you may need to provide your name, age, email, and phone number when signing up for some social media platform. Here, the platform can’t provide some sort of a default value.

From a developer point of view, checking if the mandatory value is provided and not null can become tiresome, more so if the checks have to be performed various times and there are multiple such mandatory values involved.

function submitName(name) {
  if(name=== undefined) {
    throw new Error('Missing parameter');
  }
  return name;
}

Fortunately, the shorthand way of quickly checking if a parameter value is null or not is done by implementing our #7 hack on this list i.e default parameter values.

You need to create a function that simply throws the error which addresses the missing parameter issue.

Once you have created this function, you need to assign it as the default value for the mandatory parameter.

mandatory = () => {
  throw new Error('Missing parameter');
}

submitName= (name= mandatory()) => {
  return name;
}

Thus, if the default parameter, in our case “name”, is not provided then the function mandatory() which throws the error is returned and executed.

This hack also promotes the DRY( Don’t Repeat Yourself) principle.

Conclusion

JavaScript is being increasingly used in a wide variety of scenarios, and there seems to be no end in sight when it comes to new JavaScript frameworks.

However, one thing common with all these frameworks and libraries is the fact that they all are based on JavaScript, and gaining proficiency in JavaScript will always do good when trying any of these frameworks.

You can check my recent blog covering some of the modern tips and tricks to save time. 5 Modern JavaScript Tips and Tricks To Save Time Reduce workload and write clean code using these JavaScript tipsjavascript.plainenglish.io

Gaining a complete mastery of JavaScript is tough, if not impossible.

However, by continuously learning new tricks and features you can surely become extremely proficient at JavaScript.

Hope you enjoyed reading this article!

More content at **plainenglish.io**

Did you find this article valuable?

Support Smart Dev Blogs by becoming a sponsor. Any amount is appreciated!