The today over lesson is about the JavaScript Tricks yo May Don’t Know, I hope this lesson is uesful for you.

1. Filter Unique Values

  • const array = [1, 1, 2, 3, 5, 5, 1]
  • const uniqueArray = […new Set(array)];
  • console.log(uniqueArray);

Output: [1,2,3,5]

Before ES6, isolating unique values would involve a lot more code than that!

2. Get the Last Items(s) in an Array

The array method slice() can take negative integers, and if provided it will take values form the end of the array rather than the beginnig.

  • const array = [1,2,3,4,5,6,7,8,9];
  • console.log(slice(-1)); // Result: [9]
  • console.log(slice(-2)); // Result: [8,9]
  • console.log(slice(-3)); // Result: [7,8,9]

3. Truncate an Array

If you want to remove values the end of an array destructively, there’s are faster alternatives than using splice().

For example, if you know the size of your original array, you can re-define its length property, like so:

  • const array = [0,1,2,3,4,5,6,7,8,9];
  • array.length = 4; or array = array.slice(0, 4);
  • consloe.log(array);

//Result: [0,1,2,3]

4. Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor(), Math.ceil() or Math.round().

But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

  • console.log(23.9|0);
  • // Result: 23
  • console.log(-23.9|0);
  • // Result: -23

5. Quick Powers

Since ES7, it has been possible to use the exponentiation operator ** as a shorthand for powers, which is faster than writing Math.pow(2, 3).

console.log(2 ** 3);

// Result: 8

6. Convert to Number

The opposite can be quickly achieved using the addition operator +

  • let int = “15”;
  • int = +int;
  • .
  • console.log(int); // Result: 15
  • console.log(typeof int); // Result: “number”

This may also be used to convert booleans to numbers, as below:

  • console.log(+true); // Return: 1
  • console.log(+false); // Return: 0

7. Convert to String

To quickly convert a number to a string, we can use the concatenation operator + followed by an empty set of quotation mark “”.

  • const val = 1 + “”;
  • console.log(val); // Result: “1”
  • console.log(typeof val); // Result: “string”

—————————————————————————-

I hope this lesson is be useful for. Have a more success. Good Luck

Do not forget to use social distance and mask #Stay At Home