10 Clean JavaScript Code Tips for Beginners

1. Array Merge


// general logic
const apples = ["🍎", "🍏"];
const fruits = ["🍉", "🍊", "🍇"].concat(apples);

console.log(fruits); // ["🍉", "🍊", "🍇", "🍎", "🍏"];

// elegant writing 1
const apples = ["🍎", "🍏"];
const fruits = ["🍉", "🍊", "🍇", ...apples];

console.log(fruits); // ["🍉", "🍊", "🍇", "🍎", "🍏"];

// elegant writing 2
const apples = ["🍎", "🍏"];
const fruits = [...apples, "🥭", "🍌", "🍒"];
console.log(fruits); // ["🍎", "🍏", "🥭", "🍌", "🍒"];

// graceful deduplication
const apples = ["🍎", "🍏", "🍏"];
const fruits = [...new Set(["🍉", "🍊", "🍇", "🍇", ...apples])];
console.log(fruits); // [ '🍉', '🍊', '🍇', '🍎', '🍏' ]

2. Get the value in the array


// general logic
const apples = ["🍎", "🍏"];
const redApple = apples[0];
const greenApple = apples[1];

console.log(redApple); // 🍎
console.log(greenApple); // 🍏;

// elegant writing
const apples = ["🍎", "🍏"];
const [redApple, greenApple] = apples; // use destructuring assignment

console.log(redApple); // 🍎
console.log(greenApple); // 🍏;

3. Object value


// general logic
const user = {
name: "DevPoint",
age: 30,
};

const name = user.name; // DevPoint
const age = user.age; // 30
console.log(name);
console.log(age);

// elegant writing
const user = {
name: "DevPoint",
age: 30,
};

const { name, age } = user;

console.log(name); // DevPoint
console.log(age); // 30

4. Array loop


Array looping methods include .forEach() and for...of, which have their own characteristics in use, but for...of is faster than .forEach() in terms of efficiency. Therefore it is recommended to use for...of.
// general logic
const fruits = ["🍉", "🍊", "🍇", "🍎"];

for (let i = 0; i < fruits. length; i++) {
console.log(fruits[i]);
}

// elegant writing
const fruits = ["🍉", "🍊", "🍇", "🍎"];

for (fruit of fruits) {
console.log(fruit);
}

5. Arrow functions as callbacks


Arrow function is a new syntax introduced in ES6. In addition to making the code elegant, it can avoid the problems caused by this.
// general logic
const fruits = ["🍉", "🍊", "🍇", "🍎"];

fruits.forEach(function (fruit) {
console.log(fruit);
});

// elegant writing
const fruits = ["🍉", "🍊", "🍇", "🍎"];
fruits.forEach((fruit) => console.log(fruit));

6. Array Search


Array operation is a relatively common function in front-end development. In order to improve development efficiency and reduce duplication of code, you can consider writing a general script library for array operations.
Suppose you need to look up an object from an array of objects by its properties, usually using a for loop:
// general logic
const inventory = [
{ name: "Bananas", quantity: 5 },
{ name: "Apples", quantity: 10 },
{ name: "Grapes", quantity: 2 },
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
for (let index = 0; index < arr.length; index++) {
if (arr[index].name === "Apples") {
return arr[index];
}
}
}

const result = getApples(inventory);
console.log(result); // { name: 'Apples', quantity: 10 }

// elegant writing
const inventory = [
{ name: "Bananas", quantity: 5 },
{ name: "Apples", quantity: 10 },
{ name: "Grapes", quantity: 2 },
];

function getApples(arr, value) {
return arr.find((obj) => obj.name === "Apples");
}

const result = getApples(inventory);
console.log(result);

7. Convert String to Number


// general logic
const num = parseInt("10");

console.log(num); // 10
console.log(typeof num); // "number";

// elegant writing
const num = +"10";
console.log(num); //=> 10
console.log(typeof num); // "number"
console.log(+"10" === 10); // true;

The same method can be used to determine whether it is an integer:
const isInteger = (val) => Number.isInteger(+val);
console.log(isInteger("DevPoint")); // false
console.log(isInteger("30")); // true
console.log(isInteger(30)); // true

8. null value initialization


// general logic
function getUserRole(role) {
let userRole;
if (role) {
userRole = role;
} else {
userRole = "USER";
}
return userRole;
}

console.log(getUserRole()); // "USER"
console.log(getUserRole("ADMIN")); // "ADMIN";

// elegant writing
function getUserRole(role) {
return role || "USER"; // Common methods defined by default values
}

console.log(getUserRole()); // "USER"
console.log(getUserRole("ADMIN")); // "ADMIN";

9. String concatenation


The endless + signs in the past, plus some typography is even more of a pain.
// general logic
const name = "DevPoint";
const message = "Hi " + name + "!";
console.log(message); // Hi DevPoint!
// elegant writing
const name = "DevPoint";
const message = `Hi ${name}!`;
console.log(message); // Hi DevPoint!

10 Object Merge


Object merging, in ES6, you can learn some spread operators and destructuring assignments, which is conducive to writing more concise code.
// general logic
const employee = { name: "DevPoint", age: 30 };
const salary = { grade: "A" };
const summary = salary;
for (const key in employee) {
summary[key] = employee[key];
}
console.log(summary); // { grade: 'A', name: 'DevPoint', age: 30 }
// elegant writing
const employee = { name: "DevPoint", age: 30 };
const salary = { grade: "A" };
const summary = { ...employee, ...salary };
console.log(summary); // { name: 'DevPoint', age: 30, grade: 'A' }

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00