Awesome JavaScript hacks

Mitchell Mutandah - Dec 21 '22 - - Dev Community

In this post I will share useful hacks for JavaScript. These hacks reduce the code and will help you to run optimized code. So let’s start hacking!!!

hacker

Use shortcuts for conditionals

Javascript allows you to use certain shortcuts to make your code easier on the eyes. In some simple cases, you can use logical operators && an || instead of if and else.
&& Operator Example:

//instead of
if(loggedIn) {
  console.log("Successfully logged in")
}

//use
loggedIn && console.log("Successfully logged in")
Enter fullscreen mode Exit fullscreen mode

The || functions as an "or" clause. Now, using this operator is a bit trickier since it can prevent the application from executing. However, we can a condition to get around it.
|| Operator Example:

//instead of 
if(users.name) {
  return users.name;
} else {
  return "Getting the users";
}

// use
return (users.name || "Getting the users");

Enter fullscreen mode Exit fullscreen mode

Check if an object has values

When you are working with multiple objects it gets difficult to keep track of which ones contain actual values and which you can delete.
Here is a quick hack on how to check if an object is empty or has value with Object.keys() function.

Object.keys(objectName).length
// if it returns 0 it means the object is empty, otherwise it
 // displays the number of values.
Enter fullscreen mode Exit fullscreen mode

Console Table

This awesome hack will help you to convert your CSV format or dictionary format data into tabular form using the console.table() method.

//console.table
const data = [
  {"city": "New York"},
  {"city": "Chicago"},
  {"city": "Los Angeles"},
]

console.table(data); // the result is a table below
Enter fullscreen mode Exit fullscreen mode

table

Operator Typeof

This simple hack will show you how you can use typeof() operator to check the type of any data in JS. You just need to pass the data or the variable as an argument of typeof().

let v1 = "JavaScript";
let v2 = true;
let v3 = 123;
let v4 = null;

console.log(typeof v1) //---> string
console.log(typeof v2) //---> boolean
console.log(typeof v3) //---> number
console.log(typeof v4) //---> object
Enter fullscreen mode Exit fullscreen mode

Shuffling array elements

To shuffle the array's elements without using any external libraries like Lodash, just run this magic trick:

const list = [1, 2, 3];
console.log(list.sort(function() {
   return Math.random() -0.5;
})); //---> [2, 1, 3]
Enter fullscreen mode Exit fullscreen mode

That's it!!! #HappyCoding

Let me know in the comments section any other awesome JS hacks to add to the list :)

cheers

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .