Home Web Front-end JS Tutorial Detailed explanation of the differences and connection examples between if and switch, == and === in javascript

Detailed explanation of the differences and connection examples between if and switch, == and === in javascript

Jul 18, 2017 pm 02:46 PM
javascript js switch

This article mainly introduces you to the differences and connections between if and switch, == and === in JavaScript. It is very detailed and practical.

Let’s look at a sample code first:


1

2

3

4

5

6

7

8

9

10

var a = '5';

switch (a) {

  case 5:

    console.log('==');

    break;

  case "5":

    console.log('===');

    break;

  default:

}

Copy after login

The final console display is ===, which seems to be safe to use.

1.if and switch

if are the most commonly used, there is not much to say. One thing worth noting is: if is actually very similar to ||. If conditionA in if (conditionA){} else {} is true, then it will not even look at the code in else after executing the code block before else. . Just like when || is true in the front, it will be ignored later, even if there are many errors in it. Based on this property, of course, put the code blocks that may be used most in front to reduce the number of judgments. On the other hand, if there are many if judgments and the number of possible executions is relatively evenly distributed, then subsequent judgment statements will have to execute the previous judgments one by one each time, which is not conducive to optimization. A better approach is to change the one-level judgment statement into a two-level judgment statement, such as


1

2

3

4

5

6

7

8

9

10

11

12

13

if (a > 0 && a <= 1) {

  //do something

} else if (a > 1 && a <= 2) {

 

} else if (a > 2 && a <= 3) {

 

} else if (a > 3 && a <= 4) {

 

} else if (a > 4 && a <= 5) {

 

} else if (a > 5 && a <= 6) {

 

}...

Copy after login

becomes


1

2

3

4

5

6

7

8

9

10

11

12

13

if (a > 0 && a <= 4) {

  if (a <= 1) {

    //do something

  } else if (a > 1 && a <= 2) {

 

  } else if (a > 2 && a <= 3) {

 

  } else if (a > 3 && a <= 4) {

 

  }

} else if (a > 4 && a <= 8) {

  //

}..

Copy after login

Although each of the previous judgments has been added one more time, the subsequent judgments have been reduced by (4-1)*n times, which is still a full profit. Suddenly I feel that this method is a bit similar to nested loops. Putting the loops outside with a small number of loops can help performance optimization. How to divide it into two or even multiple layers depends on the specific situation.

Switch is if’s closest comrade. Every time if is too busy, he comes to help. There is probably nothing to say about the mutual conversion between switch and if, and switch, like if, performs judgments sequentially from top to bottom. The difference is that the else in if does not work in switch. It has its own little brother: break . If no break is encountered, switch will continue to execute, such as


1

2

3

4

5

6

7

8

9

10

11

12

var a = 2;

switch (a) {

  case 1:

    console.log("1");

    //break miss

  case 2:

    console.log("2");

  case 3:

    console.log("3");

  default:

    console.log(&#39;no break&#39;);

}

Copy after login

Finally, the console displays 2,3,no break. In fact, it is quite easy to understand. break prompts the program to jump out of the internal execution body and go to the next case judgment. If there is no more, it is equivalent to if(condition){A}{B}. Without else, of course both A and B will be executed. There are two other small tips. One is that you can write any expression in switch and case, such as


1

2

3

4

5

6

7

8

9

10

switch (A + B) {

  case a * b:

    console.log("1");

    break;

  case a / b + c:

    break;

    //...

  default:

    console.log(&#39;no break&#39;);

}

Copy after login

The actual comparison is (A+B)===( a*b) and (A+B)===(a/b+c). Second, switch has a special usage, such as


1

2

3

4

5

6

7

8

9

10

11

switch (true) {

  case condition1:

    //do something

    break;

  case condition2:

    break;

    //...

  default:

    //..

    ;

}

Copy after login

At this time, each case in switch will be judged and executed in order. As for switch(false)? It’s useless.

2.== and ===

The most classic case


1

2

3

4

5

6

7

var a = "5",

  b = 5;

a == b     //true

a === b     //false

var a = "ABC",

  b = "AB" + "C";

a === b     //true

Copy after login

The following shows true The reason is actually inseparable from the immutability of the string type. On the surface, it seems that b is just concatenating a string, but in fact it has nothing to do with the original b. Each string is stored in a specific place in the memory pool. When b="AB"+"C" is executed, strings AB and C have been destroyed, and b points to the location of ABC in the memory pool. Since the string ABC was found in the memory pool before pointing (because a refers to it, it exists), so b points to the same area as a, and the congruence judgment is equal. If there is no variable before b pointing to the string ABC, then there is no variable in the memory pool, and a space will be allocated for ABC in it, and b will point to ABC.

The above is the detailed content of Detailed explanation of the differences and connection examples between if and switch, == and === in javascript. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Can Elden's Ring be played on switch? Can Elden's Ring be played on switch? Mar 11, 2024 am 11:31 AM

Can Elden's Ring be played on the switch? As a very charming action RPG game, many friends may not know whether it can be played smoothly on the switch platform. The answer is that it cannot be played at the moment. accomplish. Can Ring of Elden be played on switch? Answer: It cannot be played on switch. This highly anticipated Souls series role-playing action game has been officially released. Players can purchase it on PC, PS4/5 and Xbox Series eX|S/XboxOne and experience it immediately. Many friends who own a switch may still be eager to enjoy this game on the NS, but unfortunately, there is no switch version of the game. According to the official website configuration requirements, the game configuration is relatively high, and sw

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Is Switch2 compatible with Switch cartridges? Is Switch2 compatible with Switch cartridges? Jan 28, 2024 am 09:06 AM

Switch2 is a new model announced by Nintendo at Gamescom 2023. Some players are worried about whether there will be compatibility issues between the new model and the cartridges of previous versions. Let’s take a look. Is switch2 compatible with switch cassette? Answer: switch2 is not compatible with switch cassette. Introduction of Switch 2 cartridges According to information from Nintendo’s production chain company, Switch 2 may use 64GB cartridges. Because it has better performance and supports more 3A game masterpieces, it requires a larger cartridge capacity. Because many game works need to be castrated and compressed before they can be stuffed into a game cartridge. Moreover, Switch cartridges are prone to copying game content, so replace them with new cartridges.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The AI ​​era of JS is here! The AI ​​era of JS is here! Apr 08, 2024 am 09:10 AM

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

js method to refresh current page js method to refresh current page Jan 24, 2024 pm 03:58 PM

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.

See all articles