Share 9 practical JavaScript tips

d163f36405ee01b3bd593c2eea2a1588.jpeg

https://javascript.plainenglish.io/9-javascript-tricks-that-make-your-code-fantastic-4cf3d7880229

The original purpose of JavaScript was a simple language to add some functionality to websites. It's amazing how ubiquitous it is these days, and it's even more sophisticated.

As web applications have become more complex, JavaScript has evolved so rapidly. Writing concise, readable, and maintainable JavaScript programs isn't as easy as it used to be.

This article will summarize 9 practical JavaScript tips to help you write better front-end code and feel the beauty of this elegant programming language.

Now, let's take a look.

1. Break out of nested loops the JavaScript way

Many programming languages ​​have a break keyword for breaking out of loops.

However, this keyword is only used to break out of the current loop. If you have to break out of nested loops, it can be difficult to keep your code clean.

For example, how to implement the following code?

for (let i in arr1) {
    for (let j in arr2) {
        for (let k in arr3) {
            if (k === j - 4) {
                // need to break out of the second loop
            }
            if (k === i - 3) {
                // need to break out of the outermost loop
            }
        }
    }
}

In other languages, you may need to declare boolean variables as "flags" for the outer loop, and check the "flags" for breaks when entering the corresponding loop. This works, but can clutter your code a bit if there are a lot of boolean flags.

JavaScript provides a syntax-level solution for this scenario - label.

You can use a label to identify a loop and then refer to that label to break the corresponding loop.

So a JavaScript implementation of the above code would look like this:

loop1:
    for (let i in arr1) {
        loop2:
            for (let j in arr2) {
                for (let k in arr3) {
                    if (k === j - 4) {
                        break loop2
                    }
                    if (k === i - 3) {
                        break loop1
                    }
                }
            }
    }

Loop1 and Loop2 are the labels of the two outer loops, so matching loops can be easily broken using their labels. No need to declare other variables as "flags".

2. Using the spread operator for destructuring assignment

The spread operator is the key to clean JavaScript programs.

let leaders = {
    me: "Yang",
    T: "Elon",
    A: "Tim",
    MS: "Bill"
}
let {me, ...others} = leaders


console.log(me)
// "Yang"
console.log(others)
// {T: "Elon", A: "Tim", MS: "Bill"}

As shown in the example above, we use a simple three-dot spread operator to assign the value of leader["me"] to the variable named me and the other key-value pairs to the array others.

In React, this trick is often used to receive multiple values ​​from props when building UI components.

3. Several methods of shallow copying objects or arrays

We all know that non-primitive data types like objects and arrays in JavaScript are passed by reference.

So, changing the "new" array also changes the original array, as in the following example:

let a = [1, 2, 3]
let b = a
b.push(8)
console.log(a, b)
// [ 1, 2, 3, 8 ] [ 1, 2, 3, 8 ]

To actually copy array a to new array b, there are at least 4 methods in JavaScript.

Use the slice() method

The slice() method is to extract a part of the array. Given that it returns the extracted part in a new array, we can extract the entire array and return the array as a copy:

let a = [1, 2, 3]
let b = a.slice()
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

use the spread operator

The spread operator is not only good at destructuring assignments, it is also able to unpack items from arrays or objects:

let a = [1, 2, 3]
let b = [...a]
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

Use the built-in Array.from() method

In fact, there is a method specifically designed to do the copying - Array.from():

let a = [1, 2, 3]
let b = Array.from(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

Use the concat() method

The concat() method is used to combine two or more arrays. Since this method returns a new array without changing the existing one, we can also use it to make a copy:

let a = [1, 2, 3]
let b = [].concat(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

For objects, these three points also work perfectly:

let leader = {
    name:'Yang',
    age:'30'
}
let fake_leader = {...leader}
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }

Another way is to use the built-in Object.assign() method:

let leader = {
    name:'Yang',
    age:'30'
}
let fake_leader = Object.assign({},leader)
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }

This type of copying is actually called shallow copying, which means it's only one level deep. It only copies the element's reference, not the element itself. Therefore, if the elements are objects or arrays, the copied array will still refer to the same object or array.

For example, if array a contains an inner array (two levels deep), a shallow copy cannot actually copy them, and editing array b's inner array also changes a's:

let a = [1, [2, 2, 2], 3]
let b = [].concat(a)
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2, 8 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]

4. Deep Copy Using JSON Tricks

To achieve deep copying, a popular technique is to combine JSON.stringify() and JSON.parse().

The idea is to serialize an object (or array) into a JSON-formatted string, then parse it back into a new object. This procedure efficiently and elegantly creates a deep copy of the original array or object:

let a = [1, [2, 2, 2], 3]
let b = JSON.parse(JSON.stringify(a))
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]

JSON-based tricks are useful in most simple cases. However, we need to know that for this method to work, the object must be JSON serializable.

Let's look at a counterexample:

const obj = {
    func: function() {
        console.log("hello world!");
    }
}


const cp_obj=JSON.parse(JSON.stringify(obj))


console.log(cp_obj['func'])
// undefined

The value of obj['func'] is a function. It can no longer be replicated via JSON tricks.

In this case, we can leverage lodash, a well-known third-party JS library:

const _ = require('lodash');
const obj = {
    func: function() {
        console.log("hello world!");
    }
}


const cp_obj=_.cloneDeep(obj)


cp_obj['func']()
// hello world!

As shown above, the cloneDeep method in lodash perfectly clones the functions inside obj and can be successfully executed on the new cp_obj.

5. Skillfully implement the For loop

If you're still using C/C++-style for loops in JavaScript, you definitely need to improve your skills.

Of course, the code below is correct, but it's not "JavaScript" enough.

const arr = ['Y', 'a', 'n', 'g']
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i])
}
// Y
// a
// n
// g

The idiomatic way to write the above code in JavaScript is as follows:

Use the forEach() method

The forEach method is great for iterating over the elements of an array:

const author = [ 'Y', 'a', 'n', 'g' ];
author.forEach((c)=>{console.log(c)})
// Y
// a
// n
// g

Use the map() function

If you read open source JavaScript programs, you've probably come across the map() function. It is one of the most popular methods in JavaScript:

const author = [ 'Y', 'a', 'n', 'g' ];
author.map((c)=>{console.log(c)})
// Y
// a
// n
// g

The map() function behaves basically like forEach(), with one notable difference:

The map() method returns a new array of the same length as the original array, where each element is the result of calling a function on the corresponding element. The original array remains unchanged. The forEach() method doesn't return anything.

The following code illustrates how to use the map() function to obtain a new array:

const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.map((c) => c + ':)')
console.log(cute_author)
// [ 'Y:)', 'a:)', 'n:)', 'g:)' ]
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]

However, we cannot get a new array using the forEach() function:

const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.forEach((c) => c + ':)')
console.log(cute_author)
// undefined
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]

Use the for...of... structure

ES6 is a milestone for JavaScript. This release introduces many nice features. The "for...of..." method is one of them.

const author = [ 'Y', 'a', 'n', 'g' ];
for (let char of author){
    console.log(char);
}
// Y
// a
// n
// g

Use the for...in... structure

The "for...in..." syntax can also achieve the same functionality as ours. But we should pay attention to the difference between "for...in..." and "for...of...". The code snippet below explains this:

const author = [ 'Y', 'a', 'n', 'g' ];
for (let idx in author){
    console.log(author[idx]);
}
// Y
// a
// n
// g

6. The fastest way to remove duplicate values ​​from an array

ES6 introduces a new data structure to JavaScript - collections. Collections are collections of unique items.

Due to the nature of collections, it makes it easier to remove duplicate values ​​from arrays.

const a = [1, 2, 1, 6, 6, 6, 9]
const unique_a = [...new Set(a)]
console.log(unique_a)
// [ 1, 2, 6, 9 ]

As shown in the above program, we can use the spread operator and the Set() method to easily get the unique element of the array.

7. Reverse a string with one line of code

To reverse a string in JavaScript, we don't need to write a for loop.

Doing this requires 3 steps:

  • Split a string into an array

  • reverse array

  • convert array to string

These 3 steps take advantage of 3 different built-in methods, as follows:

const author = "Yang Zhou";
const reversedAuthor = author.split("").reverse().join("");
console.log(reversedAuthor);
// uohZ gnaY

That's a nice quip, but let's be honest, the way JS reverses strings isn't as elegant as Python's. Thanks to its elegant slice syntax, Python can do the same thing more succinctly:

author = 'Yang Zhou'
reversed_author = author[::-1]
print(reversed_author)
# uohZ gnaY

By the way, a simple way to check if a JavaScript string is a palindrome is to compare the string with its reversed version:

const author = 'YangnaY'
const isPalindrome = author.split("").reverse().join("") === author
console.log(isPalindrome)
// true

8. Quickly calculate the elements in the array

How to count each element in JavaScript array?

Use a for loop to iterate over the items one by one and count them in the process?

This is a solution, but not an elegant one at all. I would say lodash is a super useful JS library:

const _ = require('lodash');
const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
console.log(_.countBy(author))
// { Y: 1, a: 3, n: 2, g: 4 }

If you don't want to use a third-party library, it's not hard to implement similar functionality yourself:

const countBy = (arr) => {
    let count = {};
    arr.forEach((e) => {
        count[e] = (count[e] || 0) + 1;
    });
    return count;
}


const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
const charCount = countBy(author);
console.log(charCount);
// { Y: 1, a: 3, n: 2, g: 4 }

If you only need to count one specific item, the filter() method is a good choice:

const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']


// Filter all elements equal to 'a' and return the length (count)
const countOfa = author.filter(x => x === 'a').length
console.log(countOfa)
// 3

9. Use the comma operator to simplify code

Commas are more powerful in JavaScript due to the syntax of the comma operator.

The comma (,) operator evaluates each expression (from left to right) and returns the value of the last expression. If you can use its power skillfully, it can be very helpful to simplify your code.

For example, the following program demonstrates how to use the comma operator to accomplish two different purposes with one line of code:

let sum = 0;
const squares = [1, 2, 3, 4, 5].map((x) => (sum += x, x * x));
console.log(squares);
// [1, 4, 9, 16, 25]
console.log(sum);
// 15

Given that the comma operator always returns the result of the last expression, we can take advantage of this feature to avoid writing many return keywords.

For example, the get_author() function of the following code returns the changed arr:

const get_author = arr => {
    arr.push('g')
    return arr
}
console.log(get_author(['Y','a','n']))
// [ 'Y', 'a', 'n', 'g' ]

Here's the best scenario to let the comma operator show off:

const get_author = arr => (arr.push('g'), arr)
console.log(get_author(['Y', 'a', 'n']))
// [ 'Y', 'a', 'n', 'g' ]

The above is all the content I share with you today, I hope you will like it.

Finally, thanks for reading, and happy programming!

learn more skills

Please click the public number below

4ce674179db498c84635c4551f9efa77.gif

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132331542
Recommended