JavaScript notes for learners and developers

Ashok Vishwakarma
5 min readJan 14, 2019

--

Image from freecodecamp

Filtering duplicates from an Array

const array= ['a', 'b', 'c', 'πŸ”₯', 'a', 'c', 'πŸ”₯'];let uniqueArray = [];// new Set
uniqueArray = [...new Set(array)];
// Using Filter
uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
// Using reduce
uniqueArray = array.reduce((unique, item) => {
return unique.includes(item) ? unique: [...unique, item];
});
// console.log(uniqueArray);
// ['a', 'b', 'c', 'πŸ”₯'];

Using template string for better readability

// without template string
const sample = 'using backslash \\ "" \'\'';
// with template string
const sample = `using templte string "" ''`;
// using variables
const word = "world!";
// without template string
const message = 'Hello ' + word; // Hello world!
// with template string
const message = `Hello ${word}`; // Hello world!

ES6 Class vs ES5 Function

// ES5 function
var hey = function(there){
this.there = there;
}
hey.prototype.greet = function(){
return `Hey, ${this.there}`
}
// ES6 Classclass Hey {
constructor(there){
this.there = there;
}
greet(){
return `Hey, ${this.there}`;
}
}

Dynamic Object properties

let some = 'πŸŽƒ';// ES5 way
let thing = {};
thing[some] = 'πŸ’ͺ';
// ES6 way (reduced in one step)
let thing = {
[some]: 'πŸ’ͺ'
}

Avoid bad variable names

// Avoid single letter names
let a = 'Sorry what is A?';
// Avoid acronyms
let edu = 'Sorry, I am too lazy to type education';
// Avoid abbreviations
let cat = 'You mean Cat or Category?';
// Avoid meaningless names
let foo = 'what is foo??';

Shallow Cloning Object or Array

const names = ['John', 'Merry', 'Cris'];// using slice
const copiedNames = names.slice();
// using Object.assign
const copiedNames = Object.assign([], names);
// using ... operator
const copiedNames = [...names];

Better booleans variable and property names

// bad names
const person = true;
const age = true;
const dance = true;
// prefix with verb like is, has and can
const isPerson = true;
const hasAge = true;
const canDance = true;

Formatting different currencies

const fee = 150;// ES5 way
fee.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
}); // $150.00
// ES6 way
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(fee); // $150.00
// multiple formatter can be created and reuse multiple times
// USD formatter
const USD = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
// JPY formatter
const JPY = new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency: 'JPY'
});
USD.format(fee); // $150.00
JPY.format(fee); // οΏ₯150.00

Checking if a string contains a substring

const message = 'This is a sunny day!';// Using indexOf
message.indexOf('sun') !== -1; // true
// using includes
message.includes('sun'); // true

Better if conditions

const hasAge = false;// Bad way
if(hasAge === false) // true
// good way
if(!hasAge) // true

Essential false values in JavaScript

// falsy values
false
undefined
null
NaN
0, +0, -0 // all variation of 0
"", '', `` // empty string
// Everything else is truthy

Prevent error with default values

const hey = function(name){
const {name} = name;
}
hey(); // Type Errorconst hey = function(name = ''){ // '' default value for name
const {name} = name;
}
hey(); // no error

Avoid using else inside a function

// checked all the required conditions at the begining
// return if not satisfied
// Do your stuff after the if block
function hey(name) {
if(!name){
return;
}
// no need to have else
return `Hey, ${name}`;
}

Repeat string or array

const ghost = 'πŸ‘»';// using repeat
const moreGhosts = ghost.repeat(5); // πŸ‘»πŸ‘»πŸ‘»πŸ‘»πŸ‘»
// Using fill
const moreGhosts = Array(5).fill(ghost).join(''); // πŸ‘»πŸ‘»πŸ‘»πŸ‘»πŸ‘»

Checking if NaN equals to NaN

const data = NaN;// direct check
if(data === NaN) // false
// Using .is
Object.is(data, NaN); // true

Using Destructured Object / Array to get values

function send(){
// without destructors
const name = arguments[0];
const message = arguments[1]
// with destructors
const [name, message] = arguments;

// use blanks to skip indexes
const [, message] = arguments; // skiped name
}
// the same can be used with Objects as wellconst data = {name: 'John', message: 'Hey John!'};const {name, message} = data;// using in function params
function send({name, message}) { ... };
send({name: 'John', message: 'Hey John'});
// swap values
let name = "hey john";
let message = "John";
const [name, message] = [message, name];message // hey john
name // John

Convert to boolean

const hasAge = 'This person has age';// using new Boolean
new Boolean(hasAge); // true
// using Boolean
Boolean(hasAge); // true
// using !!
!!hasAge // true

Adding Range support in JavaScript natively

Number.prototype[Symbol.iterator] = function*(){
for(let i = 0; i <= this; i++){
yield i;
}
}
// uses
const range5 = [...5]; // [0, 1, 2, 3, 4, 5]

Combining two strings

const name = 'John';// using template string
const message = `Hello ${name}`;
// using join
const message = ['hello ', name].join();
// using concat
const message = "".concat('Hello ', name);
// using + operator
const message = 'Hello ' + name;

Using the spread operator (…)

// no need to use split in strings
const name = "john";
// using split
const letters = name.split(""); // ['j', 'o', 'h', 'n']
// using spread operator
const letters = [...name]; // ['j', 'o', 'h', 'n']
// copying and adding element in array
const names = ['John', 'Doe'];
const moreNames = [...names, 'Cris'];// adding/updating object properties
const data = {name: 'John', message: 'Hey, John'};
// modify exising properties
const newData = {...data, message: 'Hello, John'};
// add new properties
const newData = {...data, email: 'john@domain.com'};
// deleting property from object
const data = {name: 'John', email: 'john@domain.com', age: 30};
const {name, ...remainingData} = data;remainingData;
// {email: 'john@domain.com', age: 30}

Using arrow functions in JavaScript

// use in callbacks
[].forEach(item => { ... });
// avoid using in objects
const data = {
name: 'John',
message: 'Hey, John',
greet: () => { // use function() instead
return this.message; // this is not data
}
}

Let me know if you have anything similar I’ll add them here too.

Share with your friends and don’t forget to clap :)

--

--

Ashok Vishwakarma
Ashok Vishwakarma

Written by Ashok Vishwakarma

@GoogleDevExpert β€” #WebTechnologies & @angular | #Principal #Architect at @Naukri | #Entrepreneur | #TechEnthusiast | #Speaker

No responses yet