20 JavaScript shorthand tips

Keywords: Javascript

1. Declare multiple variables

//Conventional writing
let x;
let y = 20;
//Abbreviation
let x,y = 20;

2. Assign values to multiple variables

Use array deconstruction assignment

//Conventional writing
let a,b,c;
a = 5;
b = 8;
c = 10;
//Abbreviation
let [a,b,c] = [5,8,10]

3. Proper use of ternary operators

//Conventional writing
let marks = 26;
let result;
if(marks >=30){
result = `Pass`;
}else{
result = `Fail`;
}
//Abbreviation
let result = marks >= 30 ? `Pass` : `Fail`

4. Specify default values

//Conventional writing
let inagePath
let path = getImagrPath()
if(path !== null && path !==undefined && path !==''){
   inagePath = path;
   }else{
     inagePath ='default.jpg';
   }
//Abbreviation
let imagrPath = imagrPath() || 'default.jpg'

5. And (& &) short circuit evaluation

If a function is called only when a variable is true, you can use the logic of "and (& &) short circuit evaluation" instead

//Conventional writing
if(isLoggedin){
 goToHomepage();
 }
 //Abbreviation
 isLoggedin &&  goToHomepage()```

6,Exchange the values of two variables
 When we want to exchange the values of two variables, we often introduce the third variable. In fact, we can easily exchange two variables through array deconstruction and assignment

```javascript
let x = 'hello',y=55;
//Conventional writing
const temp = x;
x=y;
y=temp;
//Abbreviation
[x,y] = [y,x]

7. Make good use of arrows

//Conventional writing
function add(num1,num2){
 return num1 + num2;
 }
 //Abbreviation
 const add = (num1,num2)=> num1+num2

8. Template string

We usually use the + operator to connect strings with other types of variables. With ES6 Template Strings, we can combine strings in a simpler way.

//Conventional writing
console.log('you got a missde call from' + number + 'at' + time)
//Abbreviation
console.log(`you got a missed call from ${number} at ${time}`)

9. Multiline string

For multiline strings, we usually use the + operator and a new line break (\ n) splicing implementation. In fact, we can make it easier by using backquotes (`).

//Conventional writing
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.')
//Abbreviation
console.log(`JavaScript, often abbreviated as JS,is a
 programming language that conforms to the
  ECMAScript specification. JavaScript is high-level, 
  often jus-in-time compiled,and multi-paradigm.`)

10. Multiple checks

For multi value matching, we can put all the values in the array and use the indexOf() or includes() methods provided by the array to simplify it

//Conventional writing
if(value === 1|| value === 'one'|| value === 2 || value ==='two'){
   //Execute some code
}
//Abbreviation 1
if( [1,'one',2,'two'].indexOf(value) >= 0){//Executed code}
//Abbreviation 2
if([1,'one',2,'two'].includes(value)){//Executed code}

11. Assignment of object properties

If the variable name is the same as the attribute name of the object, we can write only the variable name in the object, but not the attribute name and attribute value. JavaScript will automatically set the attribute name to be the same as the variable name and assign the attribute value to the variable value.

let first = 'Amitav'
let last = 'Mishra'
//Conventional writing
let obj = {first:first,last:last};
//Abbreviation
let obj = {first,last}

12. Convert String to Number

There are some built-in methods, such as parseIent and parseFloat, which can convert a string into a number. We can also simply provide a unary operator + in front of the string value

//Conventional writing
let total = parseInt('123')
let average = parseFloat('42.6')
//Abbreviation
let total = +'123'
let average = +'42.6'

13. Repeated string

To repeat a string a specified number of times, you can use the for loop, but using the repeat() method, we can do it on one line.

//Conventional writing
let str = '';
for(let i = 0;i<5;i++){
   str += 'hello ';
}
console.log(str);//hello hello hello hello hello 
//Abbreviation
'hello '.repeat(5)

14. Power of power

We can use the Math.pow() method to find the power of a number. A simpler method is the double star (* *)

//Conventional writing
const power = Math.pow(4,3);//64
//Abbreviation
conet power = 4**3;//64

15. Double NOT bit operator (~ ~)?

The double NOT bit operator is an alternative to the Math.floor() method.

//Conventional writing
const floor = Math.floor(6.8);//6
//Abbreviation
const floor = ~~6.8;//6

16. Find the maximum and minimum values in the array

We can use the for loop to traverse the array to find the maximum or minimum value, or we can use the Array.reduce() method to find the maximum and minimum values in the array.

//Abbreviation
const arr = [2,3,4,5]
Math.max(...arr);//Max. 5
Math.min(...arr);//Min. 1```

17. About For loop

To traverse an array, we usually use the traditional for loop. We can use the method of for... Of to traverse an array. If we want to access the index of each value of the array, we can use the for... in loop.

let arr = [10,20,30,40];
//Conventional writing, for loop
for (let i= 0;i<arr.length; i++){
  console.log(arr[i]);
}
//Abbreviation
//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 use the for...in loop to traverse the properties of the object
let obj = {x: 20, y: 50};
for(const key in obj){
  console.log(obj[key])
}

18. Merging of arrays

let arr1 = [20,30];
//Conventional writing
let arr2 = arr1.concat([60,80]);
//[20,30,60,80]

//Abbreviation
let arr2 = [...arr1,60,80];
//[20,30,60,80]

19. Deep copy

To implement a deep copy of a multi-level object, we can traverse each attribute and check whether the current attribute contains an object. If so, we will call the same function recursively and pass the current attribute (nested object) as the parameter of the function.
If our object does not contain function, undefined, NaN or Date equivalents, we can also use JSON.stringify() and JSON.parse() to implement it
If our object is a single-layer object without nested objects, we can also use the expansion operator (...) for deep copy.

let obj = {x: 20, y: {z: 30}};
//General writing, recursion
const makeDeepClone = (obj) =>{
  let new Object = {}
  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);
//Abbreviation for special cases (when the attribute value in the object has no function, undefined or NaN)
const cloneObj = JSON.parse(JSON.stringify(obj));
//Abbreviation for single-layer objects (no nested objects)
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj}

20. Gets a character in a string

let str = 'jscurious.com';
//Conventional writing
str.charAt(2);//c
//Abbreviation
str[2];//c

Posted by zc1 on Tue, 09 Nov 2021 02:33:17 -0800