20 concise JS code snippets

preface

Today we'll focus on 20 simple JavaScript code snippets

1. Single line if else statement

This is a common feature of many programming languages. Instead of writing if else on multiple lines, you can use ternary operators to write the entire statement in one line of code.
For example, here are some examples:

const age = 12;
let ageGroup;


// LONG FORM
if (age > 18) {
  ageGroup = "An adult";
} else {
  ageGroup = "A child";
}

But don't overuse it. It will make your code more verbose. It is wise to replace simple expressions with this only to improve readability and reduce the number of lines of code.

2. Remove duplicates from the array

In JavaScript, Set is a collection that allows you to store only unique values. This means removing any duplicate values.

Therefore, to remove duplicates from the array, you can convert them to a collection and then back to the array.
For example, here are some examples:

const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)]; // -> [1, 20, 3, 9]

Confused? Let me explain how it works:

1) , new Set(numbers) creates a set from a list of numbers. Creating a collection automatically removes all duplicate values.

2) , expand operator... Converts any iteratable object to an array. This means converting the collection back into an array. […new Set(numbers)]

3. Empty merge of short if else

This is also short for if else.

You can use bullish consolidation instead of using the if else construct to check whether the value is empty. This nullish merge operation??, If left is not defined, return to right. If yes, return to the left:
For example, here are some examples:

let maybeSomething;

// LONG FORM
if(maybeSomething){
  console.log(maybeSomething)
} else {
  console.log("Nothing found")
}
//SHORTHAND
console.log(maybeSomething ?? "Nothing found")

4. Optional chain to prevent collapse

If you access an undefined property, an error occurs. This is where optional chains come in.

Using the optional chain operator when no attribute is defined, undefined returns instead of an error. This prevents your code from crashing.
For example, here are some examples:

const student = {
  name: "Matt",
  age: 27,
  address: {
    state: "New York"
  },
};


// LONG FORM
console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined


// SHORTHAND
console.log(student?.address?.ZIPCode); // Doesn't exist - Returns undefined

5. Exchange two variables without a third variable

In JavaScript, you can use deconstruction to split values from an array. This can be applied to swapping two variables without a third:
For example, here are some examples:

let x = 1;
let y = 2;


// LONGER FORM
let temp = x;
x = y;
y = temp;


// SHORTHAND
[x, y] = [y, x];

6. Convert any value to a Boolean value

In JavaScript, you can use!! Convert anything to a Boolean value in JS.
For example, here are some examples:

!!true    // true
!!2       // true
!![]      // true
!!"Test"  // true


!!false   // false
!!0       // false
!!""      // false

7. Extension operator

Combine two arrays using the extension operator...:
For example:

const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
// LONG FORM
let newArray = nums1.concat(nums2);
// SHORTHAND
newArray = [...nums1, ...nums2];

You can also use this syntax instead of pushing values to an array:

let numbers = [1, 2, 3];

// LONGER FORM
numbers.push(4);
numbers.push(5);
// SHORTHAND
numbers = [...numbers, 4, 5];

8. Deconstruction of communication

Use the extension operator to assign the remaining elements to the variable:

const student = {
  name: "Matt",
  age: 23,
  city: "Helsinki",
  state: "Finland",
};
// LONGER FORM
const name = student.name;
const age = student.age;
const address = { city: student.city, state: student.state };
// SHORTHAND
const { name, age, ...address } = student;

9. Use & & for short circuit assessment

Instead of checking whether something is true with an if statement, you can use the & & operator:
For example:

var isReady = true;
function doSomething(){
  console.log("Yay!");
}
// LONGER FORM
if(isReady){
  doSomething();
}
// SHORTHAND
isReady && doSomething();

10. String of steroids

Insert variables between strings by wrapping strings in back quotes and using ${} to embed values.
For example:

const age = 41;
const sentence = `I'm ${age} years old`;

// result: I'm 41 years old

11. Find a specific element from an array

Use the find() method to find elements that match specific criteria:

const fruits = [
  { type: "Banana", color: "Yellow" },
  { type: "Apple", color: "Green" }
];


// LONGER FORM
let yellowFruit;
for (let i = 0; i < fruits.length; ++i) {
  if (fruits[i].color === "Yellow") {
    yellowFruit = fruits[i];
  }
}

// SHORTHAND
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow");

12. Object attribute assignment

Do you want the object key to have the same name as the value? You can do this by omitting the object text:

const name = "Luis", city = "Paris", age = 43, favoriteFood = "Spaghetti";


// LONGER FORM
const person = {
  name: name,
  city: city,
  age: age,
  favoriteFood: favoriteFood
};


// SHORTHAND
const person = { name, city, age, favoriteFood };

13. Compression For cycle

Use the built-in forEach() method to loop through the array through one line of code:

const numbers = [1, 2, 3, 4, 5];


// LONGER FORM
for(let i = 0; i < numbers.length; i++){
  console.log(numbers[i]);
}


// SHORTHAND
numbers.forEach(number => console.log(number));

14. Default function parameters

You can provide default values for function parameters:

// LONG FORM
function pickUp(fruit) {
  if(fruit === undefined){
    console.log("I picked up a Banana");
  } else {
    console.log(`I picked up a ${fruit}`);
  }
}


// SHORTHAND
function pickUp(fruit = "Banana") {
  console.log(`I picked up a ${fruit}`)
}


pickUp("Mango"); // -> I picked up a Mango
pickUp();        // -> I picked up a Banana

15. Collect the value of the object into the array

For object Values() collects all the values of the object into a new array:

const info = { name: "Matt", country: "Finland", age: 35 };


// LONGER FORM
let data = [];
for (let key in info) {
  data.push(info[key]);
}


// SHORTHAND
const data = Object.values(info);

16. Check whether an item exists in the array

This is not necessarily shorthand, because you can hardly save a few characters. But this is a cleaner method.

You can use the include () method instead of the indexOf() method to check whether the elements are in the array. This makes your intention very clear:

let numbers = [1, 2, 3];


// LONGER FORM
const hasNumber1 = numbers.indexOf(1) > -1 // -> True


// SHORTHAND/CLEANER APPROACH
const hasNumber1 = numbers.includes(1)     // -> True

17. Compress multiple conditions

Instead of using long 𞓜 to check multiple condition chains, you can use what you just learned in the last technique -- that is, use the include () method:

const num = 1;


// LONGER FORM
if(num == 1 || num == 2 || num == 3){
  console.log("Yay");
}


// SHORTHAND
if([1,2,3].includes(num)){
  console.log("Yay");
}

18. Exponential operator

You, math Is pow () used to raising a number to a power? Did you know that you can also use the * * operator?

// LONGER FORM
Math.pow(4,2); // 16
Math.pow(2,3); // 8


// SHORTHAND
4**2 // 16
2**3 // 8

19. Math.floor() abbreviation

Round math Floor () is nothing new. But did you know that you can also use the ~ ~ operator?

For example:

// LONG FORM
Math.floor(5.25) // -> 5.0


// SHORTHAND
~~5.25 // -> 5.0

20. Assign multiple values in one line of code

Use deconstruction syntax to assign multiple values in a row:

let num1, num2;


// LONGER FORM
num1 = 10;
num2 = 100;


// SHORTHAND
[num1, num2] = [10, 100];

This also applies to using JavaScript objects:

student = {
  name: "Matt",
  age: 29,
};


// LONGER FORM
let name = student.name;
let age = student.age;


// SHORTHAND
let { name, age } = student;

summary

Well, that's all I want to share with you today
If you like, don't save your one button three connections ~,

Keywords: Javascript Front-end Vue

Added by Courbois on Mon, 03 Jan 2022 11:35:56 +0200