Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 21, 2022 11:30 pm GMT

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 lets 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 ofif(loggedIn) {  console.log("Successfully logged in")}//useloggedIn && console.log("Successfully logged in")

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";}// usereturn (users.name || "Getting the users");

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.

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.tableconst data = [  {"city": "New York"},  {"city": "Chicago"},  {"city": "Los Angeles"},]console.table(data); // the result is a table below

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(v1) //---> stringconsole.log(v2) //---> booleanconsole.log(v3) //---> numberconsole.log(v4) //---> object

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]

That's it!!! #HappyCoding

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

cheers


Original Link: https://dev.to/mitchiemt11/awesome-javascript-hacks-35e3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To