JavaScript Tricks

JavaScript Tricks

Here is a list of useful tricks for JavaScript developers that will definitely help you one day. They help you to achieve the same goal, but these are shorter and much cleaner.

1. Format JSON Code

JSON is JavaScript Object Notation. Convert a JavaScript object into a string with JSON.stringify(); This will convert the object into a string.

console.log(JSON.stringify({name: "John", Age: 23}, null, '\t'))

/* Output
{
    "name": "John",
    "Age": 23
}
*/

2. Get unique values from an array with the help of set

The set objects let you store unique values of any type, whether primitives values or object references. Set is an ES6 feature supported in all modern browsers.

let fruits = ["🍎","🍓","🍇","🍎","🍋","🍒","🍅","🍇"];
let uniqueFruits = [... new Set(fruits)];
console.log(uniqueFruits);

// Output
["🍎","🍓","🍇","🍋","🍒","🍅"];

3. Removing Falsy values from arrays

Use Boolean. Passing Boolean constructor as the argument of filter method. The filter() method creates an array filled with all array elements that pass a test. filter() does not execute the function for array elements without values. It does not change the original array.

myArray.filter(Boolean)

4. Sort number array

sorting items in an array can be done with the sort() method. It helps sorts the items of an array. The sort order can be either alphabetic or numeric and either ascending or descending. Sort works for string, but it works differently with numbers. The problem can be fixed by providing a compare function.

[0,10,4,9,123,54,1].sort((a,b) => a-b);

//Output
//[0,1,4,9,10,54,123]

5. Disable right click

The context menu can be disabled by returning false with the attribute of the body element. It can be applied to other elements as well.

<body oncontextmenu="return false">
  <div></div>
</body>
<canvas oncontextmenu="return false;"></canvas>

6. Get last items in an array with slice

You can use the slice method with negative numbers. The slice() method returns the selected elements in an array, as a new array object. The original array is not affected by this method.

let array = [0,1,2,3,4,5,6,7];
console.log(array.slice(-1));
// [7]

console.log(array.slice(-2));
// [6,7]

console.log(array.slice(-3));
// [5,6,7]

Thanks for scrolling & Share this blog (JavaScript Tricks), if you have liked it. You can read our other blogs here.

Follow us on Instagram & GitHub. 💝

Show 2 Comments

2 Comments

  1. Lynne Nelson

    Howdy! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

    • I am not sure about any plugins to protect against hacker.
      Would like to know, If someone is familiar.
      Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

fifteen + twenty =