–––––––––––––––––––––––––––––––––––––––––––––––––– -->

🌑

Hi Folks.

17 Pro JavaScript tricks you didnt know

There are many ways to write code but generally the first way for many people is very long and can take you some time. Here is my latest post that will increase your efficiency and productivity when coding JavaScript.


JavaScript : Tricks You Should Know

The ternary operator

Noobs:

1
2
3
4
5
6
7
let hungry = true;
let eat;
if (hungry == true) {
eat = 'yes';
} else {
eat = 'no';
}

Pro:

1
2
const hungry = true;
const eat = hungry == true ? 'yes' : 'no';

Number to string / string to number

Noobs:

1
2
3
let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number

Pro:

1
2
3
let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number

Populating an array

Noobs:

1
2
3
for(let i=0; i < arraySize; i++){
filledArray[i] {'hello' : 'goodbye'};
}

Pro:

1
let filledArray = new Array(arraysize).fill(null).mao(()=> ({'hello' : 'goodbye'}));

Dynamic properties in objects

Noobs:

1
2
3
4
5
let dynamic = "value"; 
let user = {
id: 1
};
user[dynamic] = "other value";

Pro:

1
2
3
4
5
let dynamic = "value"; 
let user = {
id: 1
[dynamic] = "other value"
};

Read more => 3 Steps to learn a programming language

Removing duplicates

Noob:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = [];
let flag = false;
for (j = 0; < array.length; j++) {
for (k = 0; k < outputArray.length; k++) {
if (array[j] == outputArray[k]) {
flag = true;
}
}
if (flag == false) {
outputArray.push(array[j]);
}
flag = false;
}
//outputArray = [100, 23, 67, 45]

Pro:

1
2
3
const array = [100, 23, 23, 23, 23, 67, 45]; 
const outputArray = new Set(array);
//outputArray = [100, 23, 67, 45]

Array to object

Noob:

1
2
3
4
5
6
7
let arr = ["value1", "value2", "value3"]; 
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== undefined) {
arrObject[i] = arr[i];
}
}

Pro:

1
2
let arr = ["value1", "value2", "value3"]; 
let arrObject = {...arr};

Read more => A guide to Geolocation API

Object to Array

Noob:

1
2
3
4
5
6
7
8
9
10
11
let number = {
one: 1,
two: 2,
};
let keys = [];
for (let numbers in numbers) {
if (number.hasOwnProperty(number)) {
keys.push(number);
}
}
// key = [ 'one', 'two' ]

Pro:

1
2
3
4
5
6
7
let number = {
one: 1,
two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers); // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]

Short circuit conditionals

Noob:

1
2
3
if (docs) {
goToDocs();
}

Pro:

1
docs && goToDocs()

Read more => “use strict” in JavaScript

Use ^ to check if numbers are not equal

1
2
3
if(a!=123) // before // NOOBS

if(a^123) // after // PRO

Loop over an object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const age = {
Rahul: 20,
max: 16
};

// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age);
keys.forEach(key => age[key]++);

console.log(age); // { Rahul: 21, max: 16 }

// Solution 2 - for ..in loop
for(let key in age){
age[key]++;
}

console.log(age); // { Rahul: 22, max: 18 }

Object keys are stored in insertion order

1
2
3
4
5
6
7
8
cosnt obj = {
name: "Rahul",
age: 16,
address: "Earth",
profession: "Developer",
};

console.log(Object.keys(obj)); // name, age, address, profession

Check if value is an array

1
2
3
const arr = [1, 2, 3]; 
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true

Initialize an array of size n and fill with default values

1
2
3
4
const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]

Truthy and False values

False values => false, 0, ""(empty string), null, undefined, &NaN.
Truthy values => "Values", "0", {}(empty object), &[](empty array)


Difference between double equal and triple equal

1
2
3
4
5
// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == 'o'); // true

// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false

Better way to accept arguments

1
2
3
function downloadData(url, resourceId, searchTest, pageNo, limit) {}

downloadData(...); // need to remember the order

Simpler way to do:

1
2
3
4
5
6
7
function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}

downloadData(
{ resourceId: 2, url: "/posts", searchText: "WebDev" }
);

null vs undefined

null => It is a value whereas undefined is not.
null is like an empty box and undefined it not box at all.

const fn = (x = 'default value') => console.log(x);
fn(undefined); // default value
fn(); // default value
fn(null); // null

When null is passed, the default value is not taken. Whereas, when undefined or nothing is passed the default value is taken.


⚡Thanks For Reading | Happy Coding 🍺

, , , — Nov 30, 2020


Made with 🍺 and 🍕 by Rahul