Web Front-end
JS Tutorial
One article teaches you how to implement branch optimization in JavaScriptOne article teaches you how to implement branch optimization in JavaScript
This article brings you relevant knowledge about JavaScript, which mainly introduces the relevant content about branch optimization. If there are many judgment conditions, using a large number of if branches will make the entire code The readability and maintainability are greatly reduced. Let's take a look at it. I hope it will be helpful to everyone.

【Related recommendations: JavaScript video tutorial, web front-end】
Watched it recently while surfing the Internet Here is a piece of code like this:
function getUserDescribe(name) {
if (name === "小刘") {
console.log("刘哥哥");
} else if (name === "小红") {
console.log("小红妹妹");
} else if (name === "陈龙") {
console.log("大师");
} else if (name === "李龙") {
console.log("师傅");
} else if (name === "大鹏") {
console.log("恶人");
} else {
console.log("此人比较神秘!");
}}
At first glance, I don’t feel anything unusual, but if there are 1,000 judgment conditions, is it difficult to write 1,000 if branches in this way?
If you write a large number of if branches, and may also have branches within branches, you can imagine that the readability and maintainability of the entire code will be greatly reduced. This is indeed a headache in actual development. Is there any way to achieve the requirements while avoiding these problems?
Simple branch optimization
This involves branch optimization, let us change our thinking and optimize the above code structure:
function getUserDescribe(name) {
const describeForNameMap = {
小刘: () => console.log("刘哥哥"),
小红: () => console.log("小红妹妹"),
陈龙: () => console.log("大师"),
李龙: () => console.log("师傅"),
大鹏: () => console.log("恶人"),
};
describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");}
The judgments in the problem code are all simple Equality judgments, then we can write these judgment conditions as an attribute into the object describeForNameMap. These attributes correspond to The value is the processing function after the condition is established.
After that, we only need to obtain the corresponding value in the describeForNameMap object through the parameters received by the getUserDescribe function. If the value exists, run the value (because the value is a function).
In this way, the original if branch judgment is converted into a simple key value corresponding value. The conditions and processing functions correspond one to one, making it clear at a glance.
Complex branch optimization
Then if the judgment condition in our if branch is not just a simple equality judgment, but also has some calculations that need to be calculated expression, what should we do? (As shown below)
function getUserDescribe(name) {
if (name.length > 3) {
console.log("名字太长");
} else if (name.length <p>For code with this structure, objects cannot be introduced for branch optimization. We can introduce <strong>two-dimensional arrays</strong> for branch optimization: </p><pre class="brush:php;toolbar:false">function getUserDescribe(name) {
const describeForNameMap = [
[
(name) => name.length > 3, // 判断条件
() => console.log("名字太长") // 执行函数
],
[
(name) => name.length console.log("名字太短")
],
[
(name) => name[0] === "陈",
() => console.log("小陈")
],
[
(name) => name === "大鹏",
() => console.log("管理员")
],
[
(name) => name[0] === "李" && name !== "李鹏",
() => console.log("小李"),
],
];
// 获取符合条件的子数组
const getDescribe = describeForNameMap.find((item) => item[0](name));
// 子数组存在则运行子数组中的第二个元素(执行函数)
getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");} Above we defined an describeForNameMap array. Each element in the array represents a set of judgment conditions and execution functions (also an array). Then we use the find method of the array. Just find the subarray in the describeForNameMap array that meets the judgment conditions.
Extraction branch
The describeForNameMap object we defined in the above example is an independent structure, and we can completely extract it. :
const describeForNameMap = {
小刘: () => console.log("刘哥哥"),
小红: () => console.log("小红妹妹"),
陈龙: () => console.log("大师"),
李龙: () => console.log("师傅"),
大鹏: () => console.log("恶人"),};function getUserDescribe(name) {
describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");}const describeForNameMap = [
[
(name) => name.length > 3, // 判断条件
() => console.log("名字太长") // 执行函数
],
[
(name) => name.length console.log("名字太短")
],
[
(name) => name[0] === "陈",
() => console.log("小陈")
],
[
(name) => name === "大鹏",
() => console.log("管理员")
],
[
(name) => name[0] === "李" && name !== "李鹏",
() => console.log("小李"),
],];
function getUserDescribe(name) {
// 获取符合条件的子数组
const getDescribe = describeForNameMap.find((item) => item[0](name));
// 子数组存在则运行子数组中的第二个元素(执行函数)
getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");}Through modular development, you can also write this
mapobject into a separatejsfile, and then import it wherever you need to use it. Can.
Controversy
In this way, the entire getUserDescribe function becomes very concise. Some students may ask what is the use of this? Woolen cloth? Isn't this more troublesome? If if else really doesn’t look good, then I will use if return instead of else:
function getUserDescribe(name) {
if (name === "小刘") {
console.log("刘哥哥");
return;
}
if (name === "小红") {
console.log("小红妹妹");
return;
}
if (name === "陈龙") {
console.log("大师");
return;
}
if (name === "李龙") {
console.log("师傅");
return;
}
if (name === "大鹏") {
console.log("恶人");
return;
}
console.log("此人比较神秘!");}Just imagine, if There are 1000 judgment branches in your getUserDescribe function, and there are also a large number of processing codes that are executed based on the judgment results, and the getUserDescribe function will return the value of this processed judgment result.
At this time, the focus of the getUserDescribe function lies in the processing of the judgment result, not in which branch the result is obtained, for example :
function getUserDescribe(name) {
let str; // 存储判断结果
if (name.length > 3) {
str = "名字太长";
} else if (name.length If you do not perform branch optimization, the <p>getUserDescribe<code> function will be occupied by a large number of </code>if<code> branches, making the </code>getUserDescribe<code> function the focus of Lost (</code>getUserDescribe<code>Function</code>The focus is on the processing of the judgment result<strong>, not on which branch the result is obtained through), then you can take a look at our optimized code:</strong></p><pre class="brush:php;toolbar:false">const describeForNameMap = [
[(name) => name.length > 3, () => "名字太长"],
[(name) => name.length "名字太短"],
[(name) => name[0] === "陈", () => "小陈"],
[(name) => name === "大鹏", () => "管理员"],
[(name) => name[0] === "李" && name !== "李鹏", () => "小李"],];function getUserDescribe(name) {
let str; // 存储判断结果
const getDescribe = describeForNameMap.find((item) => item[0](name));
if (getDescribe) {
str = getDescribe[1]();
} else {
str = "此人比较神秘!";
}
// 对判断结果str的一些处理
// ......
console.log(str);
return str;} Looking at the optimized getUserDescribe function we can know that it obtains a value from describeForNameMap and assigns it to str (describeForNameMap We don't care how returns the value), and then did some processing on str. This highlights the focus of the getUserDescribe function (processing the judgment result str).
In this example
describeForNameMapThe second element of the subarray can directly use a value:[(name) => name.length > 3, "name Too long"], but for the scalability of the overall code, it is recommended to use functions, because functions can receive parameters, making it easier to deal with more complex scenarios in the future.
Conclusion
Branch optimizationThere are different implementation methods and application scenarios in various languages. This article adoptsJavaScript introduces two ideas of code branch optimization. The implementation of the code is very simple, and the focus is on the application of this idea.
In fact, there has been controversy about the issue of branch optimization. There are currently two views:
-
View 1: There is no need to bother optimizing it, and optimizing it Because the following code creates an extra
object/array, retrieving theobject/arrayis still more wasteful than simplyif else. -
Viewpoint 2: The code after branch optimization
readability/maintainabilityis better, and the introduction ofobject/arraybrings Performance issues are simply not worth mentioning in this day and age.
[Related recommendations: JavaScript video tutorial, web front-end]
The above is the detailed content of One article teaches you how to implement branch optimization in JavaScript. For more information, please follow other related articles on the PHP Chinese website!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment





