7 JavaScript Shorthand Techniques that will Save your Time
In this article, we will discuss 7 cool shorthand tricks in JavaScript that will save the developer time.
1. Arrow Function: JavaScript Arrow functions were introduced in ES6. The main advantage of this function is, it has shorter syntax.
Javascript
// Longhand function add(a, b) { return a + b; } // Shorthand const add = (a, b) => a + b; |
2. Multi-line string: For multi line string we normally use + operator with a new line escape sequence (\n). We can do it in an easier way by using backticks (`).
Javascript
// Longhand console.log( 'JavaScript is a lightweight, interpreted, ' + 'object-oriented language\nwith first-class ' + 'functions, and is best known as the scripting ' + 'language for Web \npages, but it is used in many' + 'non-browser environments as well.\n' ); // Shorthand console.log(`JavaScript is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it is used in many non-browser environments as well.`); |
3. 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.
Javascript
let myArr = [50, 60, 70, 80]; // Longhand for (let i = 0; i < myArr.length; i++) { console.log(myArr[i]); } // Shorthand // 1. for of loop for (const val of myArr) { console.log(val); } // 2. for in loop for (const index in myArr) { console.log(`index: ${index} and value: ${myArr[index]}`); } |
4. String into a Number: There are built in methods like parseInt and parseFloat available to convert a string into number. It can also be done by simply providing an unary operator (+) in front of string value.
Javascript
// Longhand let a = parseInt( '764' ); let b = parseFloat( '29.3' ); // Shorthand let a = + '764' ; let b = + '29.3' ; |
5. Swap two variables
For swapping two variables, we often use a third variable. But it can be done easily with array de-structuring assignment.
Javascript
//Longhand let x = 'Hello' , y = 'World' ; const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x]; |
6. Merging of arrays: To merge two arrays, following can be used:
Javascript
// Longhand let a1 = [2, 3]; let a2 = a1.concat([6, 8]); // Output: [2, 3, 6, 8] // Shorthand let a2 = [...a1, 6, 8]; // Output: [2, 3, 6, 8] |
7. Multiple condition checking: For multiple value matching, we can put all values in array and use indexOf() or includes() method.
Javascript
// Longhand if (value === 1 || value === 'hello' || value === 2 || value === 'world' ) { ... } // Shorthand 1 if ([1, 'hello' , 2, 'world' ].indexOf(value) >= 0) { ... } // Shorthand 2 if ([1, 'hello' , 2, 'world' ].includes(value)) { ... } |