1. Use ‘const’ for the constants instead of ‘var’
Constants are variables that never change, declaring the variable this way we make sure they never change
/* Old way */
var i = 1;/* Correct */
const i = 1;
2. Use ‘let’ for the changing variables instead of ‘var’
The let statement declares a locally scoped variable with block scope, this variable will change:
/* Inadequate */
var myVal = 1;
for (var i; i < 10; i++){
myVal = 1 + i;
}/* Correct */
let myVal = 1;
for (let i; i < 10; i++){
myVal += i
}
3. Declaring Objects
Example for shortcut declaring objects:
/*
Old way
The Object() class makes an unnecessary function call
*/
const myObject = new Object();/* Correct */
const myObject = {};
4. Declaring Arrays
Example for shortcut declaring arrays:
/*
Old way
The Array() class makes an unnecessary function call
*/
const myArray = new Array();/* Correct */
const myArray = [];
5. Concatenate strings
Example for concatenating strings this is very helpful:
/* Old way */
const myStringToAdd = "world";
const myString = "hello " + myStringToAdd;/* Correct */
const myStringToAdd = "world";
const myString = `hello ${myStringToAdd}`;
6. Use object method shorthand
Example of useful functions in objects:
/* Inadequate */
const customObject = {
val: 1,
addVal: function () {
return customObject.val + 1;
}
}/* Correct */
const customObject = {
val: 1,
addVal(){
return customObject.val++
}
}
7. Creating the value of an Object
Example of creating a new object with value:
/* Inadequate */
const value = 1;
const myObject = {
value: value
}/* Correct */
const value = 1;
const myObject = {
value
}
8. Assign values to an Object
Example of assign object values to another object:
/* Old way */
const object1 = { val: 1, b: 2 };
let object2 = { d: 3, z: 4 };
object2.val = object1.val;
object2.b = object1.b;/* Correct */
const object1 = { val: 1, b: 2 };
const object2 = { ...object1, d: 3, z: 4 }
9. Assign a value to an Array
Example of shortcut assign a value in an array:
/* Inadequate */
const myArray = [];
myArray[myArray.length] = "hello world";/* Correct */
const myArray = [];
myArray.push('Hello world');
10. Concatenate Arrays
Example of concatenating arrays:
/* Inadequate */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = array1.concat(array2);/* Correct */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = [...array1, ...array2]
11. Get multiple properties of an object
Example of creating a function with an object parameter:
/* Inadequate */
function getFullName(client){
return `${client.name} ${client.last_name}`;
}/* Correct */
function getFullName({name, last_name}){
return `${name} ${last_name}`;
}
12. Getting values from an object
Example to get values and create variables:
/* Inadequate */
const object1 = { a: 1 , b: 2 };
const a = object1.a;
const b = object1.b;/* Correct */
const object1 = { a: 1 , b: 2 };
const { a, b } = object1;
13. Creating functions
Example of shortcut functions with arrows:
/* Old way but good */
function myFunc() {}/* Good */
const myFunc = function() {}/* Best */
const myFunct = () => {}// IMPORTANT: In some cases it is not recommended to use these functions with arrows to avoid reading errors
14. Default values
Example of set default values in function parameters:
/* Inadequate */
const myFunct = (a, b) => {
if (!a) a = 1;
if (!b) b = 1;
return { a, b };
}/* Correct */
const myFunct = (a = 1, b = 1) => {
return { a, b };
}
15. Use ‘reduce’ Instead ‘forEach’ and ‘for’ to sum values
Example of shortcut sum of array:
/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
values.forEach( (n) => { total += n})/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
for (let i; i < values.length; i++){
total += values[i];
}/* Correct */
const values = [1, 2, 3, 4, 5];
const total = values.reduce((total, num) => total + num);
16. Exist in array
/* Inadequate */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
let exist = false;
myArray.forEach( item => {
if (item.a === 2) exist = true
})/* Correct */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
const exist = myArray.some( item => item.a == 2)
17. Shortcut if boolean
/* Inadequate */
const a = 1;
const b = 1;
let isTrue = false
if (a === b) {
isTrue = true
}/* Correct */
const a = 1;
const b = 1;
const isTrue = a === b
18. Shortcut if values
/* Inadequate */
const a = 5;
let b;
if (a === 5){
b = 3;
} else {
b = 2;
}/* Correct */
const a = 5;
const b = a === 5 ? 3 : 2;
19. Resize or Empty an Array Using array.length
array.length = nvar array = [a, b, c, d, e, f, g, h, i , j];
console.log(array.length); // returns the length as 10
array.length = 4;
console.log(array.length); // returns the length as 4
console.log(array); // returns “a,b,c,d”
var array = [a, b, c, d, e, f, g, h, i , j];
array.length = 0;
console.log(array.length); // returns the length as 0console.log(array);
20. How to Merge Arrays Without Causing Server Overload
var list1 = [a, b, c, d, e];
var list2 = [f, g, h, i, j];
console.log(list1.push.apply(list1, list2));
// returns the merged values of both arrays (a, b, c, d, e,f, g, h, i, j)
21. How to Extract Unique Values
const cars = ['Opel','Bugatti','Opel','Ferrari','Ferrari','Opel'];
var unrepeated_cars = [...new Set(cars)]; // spread Operator
console.log(unrepeated_cars); // returns the values Opel, Bugatti, Ferrari
22. How to Check if an Object Has Values
Object.keys(objectName).length// if it returns 0 then the Object is empty,// otherwise it displays the number of values
23. Assigning values to multiple variables
We can assign values to multiple variables in one line with array destructuring.
//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];
24. Assigning default value
We can use OR(||)
short circuit evaluation to assign a default value to a variable in case the expected value found falsy.
//Longhand
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
25. AND(&&) Short circuit evaluation
If you are calling a function only if a variable is true, then you can use AND(&&)
short circuit as an alternative for this.
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
The AND(&&)
short circuit shorthand is more useful in React when you want to conditionally render a component. For example:
<div> { this.state.isLoading && <Loading /> } </div>
26. Swap two variables
To swap two variables, we often use a third variable. We can swap two variables easily with array destructuring assignment.
let x = 'Hello', y = 55; //Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];
27. Multi-line String
For multiline string we normally use + operator with a new line escape sequence (\n). We can do it in an easier way by using backticks (`).
//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' +
'ECMAScript specification. JavaScript is high-level,\n' +
'often just-in-time compiled, and multi-paradigm.' ); //Shorthand
console.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);
28. Multiple condition checking
For multiple value matching, we can put all values in array and use indexOf()
or includes()
method.
//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}
29. Object Property Assignment
If the variable name and object key name is same then we can just mention variable name in object literals instead of both key and value. JavaScript will automatically set the key same as variable name and assign the value as variable value.
let firstname = 'Amitav';
let lastname = 'Mishra'; //Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
30. String into a Number
There are built in methods like parseInt
and parseFloat
available to convert a string to number. We can also do this by simply providing a unary operator (+) in front of string value.
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
31. Repeat a string for multiple times
To repeat a string for a specified number of time you can use a for
loop. But using the repeat()
method we can do it in a single line.
//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
'Hello '.repeat(5);
Tip: Want to apologize to someone by sending 100 times “sorry”? Try it with repeat()
method. If you want to repeat each string in a new line, then add \n
to the string.
'sorry\n'.repeat(100);
32. Find max and min number in array
We can use for loop to loop through each value of array and find the max or min value. We can also use the Array.reduce() method to find the max and min number in array.
But using spread operator we can do it in a single line.
// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
33. For loop
To loop through an array we normally use the traditional for
loop. We can make use of the for...of
loop to iterate through arrays. To access the index of each value we can use for...in
loop.
let arr = [10, 20, 30, 40]; //Longhand
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
} //Shorthand
//for of loop
for (const val of arr) {
console.log(val);
} //for in loop
for (const index in arr) {
console.log(`index: ${index} and value: ${arr[index]}`);
}
We can also loop through object properties using for...in
loop.
let obj = {x: 20, y: 50};
for (const key in obj) {
console.log(obj[key]);
}
Reference: Different ways to iterate through objects and arrays in JavaScript
34. Merging of arrays
let arr1 = [20, 30]; //Longhand
let arr2 = arr1.concat([60, 80]);
// [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80];
// [20, 30, 60, 80]
35. Deep cloning of multi-level object
To deep clone a multi-level object, we can iterate through each property and check if the current property contains an object. If yes, then do a recursive call to the same function by passing the current property value (i.e. the nested object).
We can also do it by using JSON.stringify()
and JSON.parse()
if our object doesn't contains functions, undefined, NaN or Date as values.
If we have single level object i.e no nested object present, then we can deep clone using spread operator also.
let obj = {x: 20, y: {z: 30}};
//Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
} const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};
Improvement from comment: The shorthand technique (JSON.parse(JSON.stringify(obj))
) doesn’t work if your object property contains function
, undefined
or NaN
as value. Because when you JSON.stringify the object, the property containing function
, undefined
or NaN
as value gets removed from the object.
So use JSON.parse(JSON.stringify(obj))
when your object contains only strings and numbers.
Reference: JSON.parse() and JSON.stringify()
36. Get character from string
let str = 'jscurious.com'; //Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
37. Smart Data Filteration
Filter your data with JavaScript built-in Filter method. This comes in handy when you had a large amount of data in array form and want to filter some elements from it.
// Data Filterationvar data = ["Football", "Soccer", "Cricket", "Basketball", "Hockey"]var filtered_data = data.filter(data => data.length < 8)console.log(filtered_data) // ["Soccer", "Cricket", "Hockey"]
38. Looping Keys and Values
Another useful Snippet code to iterate keys and values of dictionary data. we are going to use the forEach method for this task.
// looping throught objectslet data = {JavaScript: 1, Dart: 2, Java: 3};Object.keys(data).forEach((key, value) => { console.log(key, value); });// Output
// JavaScript 0
// Dart 1
// Java 2
39. Destructing assignment
You can use Destructing method to unpack the array values and assign them to other variables. Check out the below example code.
// Destructive Assignmentlet data = ["Haider", "22", "50000", "Web Developer"]let [name, age, salary, profession] = dataconsole.log(name, age, salary, profession) // Haider 22 50000 Web Developer
40. Slicing Array
This is another useful snippet code that will slice your array without using any loop. The syntax for slice is slice(startIndex, endIndex).
// Slicing An Arraylet array = [10, 12, 13, 14, 15, 16]console.log(array.slice(0, 3)) // [10, 12, 13]
console.log(array.slice(0, 2)) // [10, 12]
41. Search Object in Array
You can Search an object in Array using Js find() method. Below is a snippet code example.
// Search Object in Arraylet data = [
{name:"haider", Salary:60000},
{name:"John", Salary:50000},
{name:"Peter", Salary:20000},
]let emp = data.find(data => data.name === "Peter")console.log(emp)
// Output
{
name:"Peter",
Salary:20000
}
42. String Reversing
This snippet code will show you how to reverse a string without using a loop.
// String Reversevar reverse = (data) => {return data.split("").reverse().join(""); }console.log(reverse("CoderBoy")) // yoBredoCconsole.log(reverse("Medium")) // muideM
43. Concatenate Lists
Now you don’t need to use functions and loops to merge many lists into one. You can use Js built-in Concat() method. Check out the below code example.
let arr1 = [10, 20, 30]
let arr2 = [40, 50]var arr = arr1.concat(arr2)
console.log(arr) // [10, 20, 30, 40, 50]
44. Capture Right Click
This simple snippet code will capture the Right-Click of the mouse in a web browser.
// Capture Right Clickwindow.oncontextmenu = () => {console.log("Right Click is Pressed!")}
45. Built-in Sorting
Sorting is a common problem of every programming language. In JavaScript, you can use the sort() method to sort any list of elements.
// Built in Sortingvar num = [9, 8, 4, 2, 8, 0, 3, 8]num.sort()console.log(num) //[0, 2, 3, 4, 8, 8, 9]
46. Handle Errors in JS
Error is always a headache in Programming. To handle Errors in JavaScript you can use the try/catch statement. Check out the below syntax
// Error Handlingtry {
// Code Block to try
}
catch(err) {
// Code Block to handle errors
}
finally {
// Code Block to be executed regardless of the try and catch results
}
47. Find Index of Array Element
Now you don’t need to iterate the whole Array to find an index of any element. Make your life easier by taking a look at the below snippet code.
// Index of Elementvar num = [9, 8, 4, 2, 8, 0, 3, 8]console.log(num.indexOf(9)) // 0console.log(num.indexOf(3)) // 6console.log(num.indexOf(8)) // 1
48. Check String is Uppercase
This is a simple snippet that will help you to check whether a string is uppercase or lowercase.
// Check for UpperCase
const CheckUpper = string => string === string.toUpperCase();console.log(CheckUpper("Hello")) // false
console.log(CheckUpper("LEARN")) // true
49. Reverse a string
const reverseString = (...strArr) => strArr.reverse().join('');
50. Get query parameters from the URL
const getQueryParams = (URL) => JSON.parse( '{"' +
decodeURI(URL.split('?')[1])
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
getQueryParams('https://codingcafe.co.in?name=gyan&age=24');
// output
{name: 'gyan', age: '24'}
const getSearchParams = (url) => new URL(url).searchParams;
51. Clipboard API
const copy = (text) => navigator.clipboard.writeText('Hello world!');
52. Remove duplicate from an Array
const removeDuplicates = (ary) => [...new Set(ary)];
removeDuplicates([5,6,1,2,3,6,3,5,1])
// [5, 6, 1, 2, 3]
53. Check to see if the current tab is visible or focused
const inView = () => document.hidden;
inView();
// Result: returns true or false depending on if tab is focused
54. Check to see if the Element is focused
const inView = (el) => (el === document.activeElement);
inView(element);
// Result: returns true or false depending on if element is focused
55. URL query parameters
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=test&sex=man"
params.has("test"); // true
params.get("sex"); // "man"
56. Scroll to top or to the bottom
const scrollToTop = () => window.scrollTo(0,0);
scrollToTop();
const scrollToBottom = () => window.scrollTo(0,document.body.scrollHeight);
scrollToBottom()
57. Check that Caps Lock is on
const passwordInput = document.getElementById('password');
passwordInput.addEventListener('keyup', function (event) {
if (event.getModifierState('CapsLock')) {
// CapsLock is open
}
});
58. Get the mouse position
document.addEventListener('mousemove', (e) => {
console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
});
59. element’s dataset
<div id="user" data-name="Maxwell" data-age="32" data-something="Some Data">
Hello Maxwell
</div>
<script>
const user = document.getElementById('user');
console.log(user.dataset);
// { name: "Maxwell", age: "32", something: "Some Data" }
console.log(user.dataset.name); // "Maxwell"
console.log(user.dataset.age); // "32"
console.log(user.dataset.something); // "Some Data"
</script>