Table of Contents
正片
Reduce if...else noodle code
Pipeline operations replace redundant loops
find replaces the redundant loop
includes replace redundant loops
result return value
Return early
Keep the object intact
Smart use of operators
Written at the end
Home Web Front-end JS Tutorial Several practical JavaScript optimization tips worth knowing

Several practical JavaScript optimization tips worth knowing

Mar 28, 2022 am 10:33 AM
javascript optimization

In our work, we can often increase the readability of the code through some small details and make the code look more elegant. This article will share with you some practical JavaScript optimization tips that you can understand at a glance. I hope it will be helpful to you!

Several practical JavaScript optimization tips worth knowing

「Difficulty:?」 「Recommended reading time: 5min

正片

Reduce if...else noodle code

  • Once we write more than two if ...else function, you should think about whether there is a better optimization method. [Related recommendations: javascript learning tutorial]
  • For example, if we now need to calculate the price of Mai Lao’s food based on its name, you might do this.

Several practical JavaScript optimization tips worth knowing

  • This way of writing will make the function body have a lot of conditional judgment statements, and when we want to add a product next time, we need to modify the function Adding an if...else statement to the internal logic also violates the opening and closing principle to a certain extent. When we need to add a logic, we should try our best to extend the software entity. Address changes in requirements rather than modifying existing code to accomplish changes.
  • This is a very classic optimization method. We can use an organization's data similar to Map to save all products. Here we directly create an object for storage.

Several practical JavaScript optimization tips worth knowing

  • In this way, we don’t need to change the logic of getPrice next time we need to add another product. Of course, here is actually More people like to use foodMap directly where they are used. I just gave a simple example to express this idea.
  • Then some classmates will ask, if I don’t want to key just use strings, then you can use new Map, idea It's almost the same, with an additional entity extended to store changes.

Pipeline operations replace redundant loops

  • There is such a list of Mai Lao food

Several practical JavaScript optimization tips worth knowing

  • If you want to find the food that belongs to Set 1, how will you find it?
  • The above is the method we often used before. Obviously, if we replace it with filter and map instead of for loop, it can not only make The code is more streamlined and the semantics can be made clearer, so that we can see at a glance that the array is first filtered and then reorganized.

Several practical JavaScript optimization tips worth knowing

find replaces the redundant loop

  • Still the above example, if we want to use this food object The use of find comes into play when searching for specific food in an array based on attribute values.

Several practical JavaScript optimization tips worth knowing

includes replace redundant loops

  • These are similar to the above two details. The function is a built-in function that we do not need to rewrite. Using it skillfully will save a lot of time.
  • As we all know, a bowl of Kangfu Laotan pickled cabbage beef noodles contains pickled cabbage, noodles, beef cubes, Cigarette Butt and Foot Skin, then we want to use a function to verify whether there is foot skin in this surface. How can we write it more concisely?

Several practical JavaScript optimization tips worth knowing

  • Similarly, not only Kang Fu’s Pickled Cabbage Beef Noodles can be played like this, all similar ones can be found in the array Operations on specific elements can be called using the includes function.

result return value

  • We usually struggle with naming the return value variable when writing functions that have return values, or even For some long functions, we do not use variables but directly return. This habit is actually bad, because we need to clarify the logic again when we refer to this code next time.
  • Generally, in a small function, we can use result as the return value.

Several practical JavaScript optimization tips worth knowing

Return early

  • However, using result as the return value above does not apply to all situations. Sometimes we need to end early. Function body to prevent colleagues later from reading redundant programs.

  • In the following example, when our selectedKey does not exist, we should return immediately, so that we don’t need to continue reading the following code, otherwise we will face For more complex functions, a lot of reading cost will be increased.

Several practical JavaScript optimization tips worth knowing

Keep the object intact

  • Often when we get the data returned by the backend through the request The data will be processed according to some of the attributes. If there are few attributes to be processed, many students will be accustomed to using the first method.
  • But in fact, this habit is bad, because when you are not sure whether this function needs to add dependency attributes in the future, you should keep the integrity of the object, as I mentioned in my last article, Learn to embrace change, if getDocDetail not only uses icon and content, but also title in the future, date and other attributes, so we might as well pass in the complete object directly, which not only shortens the parameter list but also makes the code more readable.

Several practical JavaScript optimization tips worth knowing

Smart use of operators

  • When we need to create a new variable, sometimes we need to check it When the variable referenced by the value is null or undefined, you can use the simple writing method.

Several practical JavaScript optimization tips worth knowing

Written at the end

  • First of all, thank you all for reading this. This time, I will share the article here and summarize it. A few very basic optimization methods, I hope they can help everyone.

[Related video tutorial recommendations: web front-end]

The above is the detailed content of Several practical JavaScript optimization tips worth knowing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

Vivox100s parameter configuration revealed: How to optimize processor performance? Vivox100s parameter configuration revealed: How to optimize processor performance? Mar 24, 2024 am 10:27 AM

Vivox100s parameter configuration revealed: How to optimize processor performance? In today's era of rapid technological development, smartphones have become an indispensable part of our daily lives. As an important part of a smartphone, the performance optimization of the processor is directly related to the user experience of the mobile phone. As a high-profile smartphone, Vivox100s's parameter configuration has attracted much attention, especially the optimization of processor performance has attracted much attention from users. As the "brain" of the mobile phone, the processor directly affects the running speed of the mobile phone.

What are some ways to resolve inefficiencies in PHP functions? What are some ways to resolve inefficiencies in PHP functions? May 02, 2024 pm 01:48 PM

Five ways to optimize PHP function efficiency: avoid unnecessary copying of variables. Use references to avoid variable copying. Avoid repeated function calls. Inline simple functions. Optimizing loops using arrays.

See all articles