DEV Community

Cover image for Awesome JavaScript hacks
Mitchell Mutandah
Mitchell Mutandah

Posted on • Edited on

Awesome JavaScript hacks

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

Top comments (15)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

A few things:

  • None of these are 'hacks' - they're just features of the language
  • Your typeof example is missing typeof - oops! 😝
  • Your shuffling example will give biased results (some shuffle permutations will turn up way more often than others - explanation here)
  • Your method for testing if an object has values is overly simplistic, and may result in you deleting objects that are, in fact, not empty. It will not include keys that are Symbols, string keys that are non-enumerable, and values coming from lower down in the prototype chain. For more information on this, you can look here
  • You can add syntax highlighting to your examples by adding js after the opening three backticks of the code block
Collapse
 
wadecodez profile image
Wade Zimmerman

Came here to say the same thing. "Hacks" are more of a thing for working around libraries/frameworks. Like using reflection to access a private property or something. Better title would have been something like "My favorite pieces of code"

Collapse
 
mitchiemt11 profile image
Mitchell Mutandah

Thank you Jon Randy for highlighting some crucial points. I have updated the typeof function. There is more to learn. Thanks again for the useful links.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Might want to update it again, since typeof is an operator, not a function (as you initially correctly state) - and the data you are checking is the operand, not an argument to a function. For this reason, the parentheses in your example are unnecessary.

Collapse
 
pilcrowonpaper profile image
pilcrowOnPaper

Please don't use && as a shortcut for conditional statements. It is harder to read and understand. You may want to use ?? instead of || if you just want to check if the value is undefined or null.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Readability and understand-ability are purely subjective.

Collapse
 
mhasan profile image
Mahmudul Hasan • Edited

Good post, learn this things. Please share more!

Collapse
 
mitchiemt11 profile image
Mitchell Mutandah

Thank you.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
not-ethan profile image
Ethan

Why did you only mention console.table when there are many other methods for the console like console.group, console.error, console.warn` and many other super useful methods on the console object?

Collapse
 
amirhe profile image
Amir.H Ebrahimi

Noteing something for readers, as article said typeof is an operator not a function

so it can also be used like an operator without prantesis.

const isSSR = () => typeof window === 'undefiend';
Enter fullscreen mode Exit fullscreen mode

value wrapped with prantesis is going to be evaluated to variable iteself.

Collapse
 
mitchiemt11 profile image
Mitchell Mutandah

Thanks, updated.

Collapse
 
pavelee profile image
Paweł Ciosek

Thanks!

Collapse
 
dil2010 profile image
Dilan Udawattha

Wow!, Good to know

Collapse
 
_ianeta profile image
Ianeta Hutchinson • Edited

We could break this down into bite sized bits for other sharing formats