Top ten Javascript tricks – part 1

Convert a string to an array of Characters using spread Syntax – ES6

// Split string uisng ES6 Spread
const angular  = 'angular';

//  old ways
const splicedAngualr = angular.split('');
// [ 'a', 'n', 'g', 'u' , 'l' , 'a' ,'r']

// new ES6 way
const splicedAngular = [...angular]
// [ 'a', 'n', 'g', 'u' , 'l' , 'a' ,'r']

Addition string (’10’) and number (5)

const str = '10';
const num = 5;

// This doesn't returnt the sum, its concatenated
str + num
// 105 (not correct)

//prepend string with "+" to calculate the sum
+str + num
// 15 (correct)

How to remove an Array Duplicates

const duplicates = [1, 2, 2, 4 , 5, 5, 6, 6];

const uniques = Array.from(new Set(duplicates));

// uniques [1, 2, 4, 5, 6]

3 ways to convert string to boolean

const isBool = 'Helperscript';

new Boolean(isBool) // true

Boolean(isBool) // true

!!isBool // true

How to check if NaN equals to NaN?

const item = NaN;

// this doesn't work
item === NaN; // false

//This works!
Object.is(item, NaN); // true

Two ways to repeat the strings

const str = 'J';

// 1. Repeat
str.repeat(3);

// 2. Fill
Array(3).fill(str).join('');

// result 'JJJJ'

Refactoring the ‘if’ condition

const isPerson = false;

//not correct
if(isPerson === false)

// correct
if(!isPerson)

Check if a string contains Substring

const word ='summer';

// old way
word.indexOf('sum') !=== -1 // true

// ES6 way
word.includes('sum');

Check the number is Negative or Positive

const num = -2;

// old ways
num === 0 ? num : (num > 0 ? 1 : -1) // -1

// ES6
Math.sign(num); // -1 if positive return 1 

The standard naming pattern for boolean variable

// Non standard
const person =  false;
const age = false;
cosnt dance = false

// Good standard
const isPerson =  true;
const hasAge = true;
cosnt canDance = true

I hope this will helpful for most beginners as well as to everyone. Thanks for reading. If you know any tricks comment below.

Javascript tricks part2 >

One thought on “Top ten Javascript tricks – part 1”

Leave a Reply

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