search
HomeWeb Front-endFront-end Q&AHow to use if statement in javascript

How to use if statement in javascript

Feb 16, 2022 pm 03:37 PM
if statementjavascript

In JavaScript, the if statement is used to perform different operations based on different conditions. The syntax is "if (conditional expression) {// code to be executed;}" or "if (conditional expression) {//The code to be executed when the expression is true}else{//The code to be executed when the expression is not true}”.

How to use if statement in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, if statements are used to perform different operations based on different conditions.

if statements have three different forms:

  • if statement;

  • if else statement;

  • if else if else statement;

#if statement

if statement is the simplest conditional judgment statement in JavaScript. The syntax format is as follows:

if(条件表达式){
    // 要执行的代码;
}

When the conditional expression is established, that is, when the result is a Boolean value true, the code in { } will be executed.

The sample code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var age = 20;
        if(age >= 18){      // 如果 age >= 18 的结果为 true,则执行下面 { } 中的代码
            alert("adult");
        }
    </script>
</body>
</html>

The running result is as shown below:

How to use if statement in javascript

if else statement

The if else statement is an upgraded version of the if statement. It can not only specify the code to be executed when the expression is true, but also the code to be executed when the expression is not true. The syntax format is as follows:

if(条件表达式){
    // 当表达式成立时要执行的代码
}else{
    // 当表达式不成立时要执行的代码
}

The sample code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var now = new Date();           // 获取当前的完整日期
        var dayOfWeek = now.getDay();   // 获取一个 0-6 之间的数字,用来表示当前是星期几,0 表示星期日、1 表示星期一、以此类推
        if (dayOfWeek > 0 && dayOfWeek < 6) {       // 判断:如果当前是星期一到星期五中的一天,则输出“Have a nice day!”,若不是则输出“Have a nice weekend!”
            alert("Have a nice day!");
        } else {
            alert("Have a nice weekend!");
        }
    </script>
</body>
</html>

The running result is as shown below:

How to use if statement in javascript

##if else if else statement

If and if else statements both have only one conditional expression, and if else if else statement is their more advanced form, in if else if else statement allows you to define multiple conditional expressions and execute them based on the result of the expression The corresponding code, the syntax format is as follows:

if (条件表达式 1) {
    // 条件表达式 1 为真时执行的代码
} else if (条件表达式 2) {
    // 条件表达式 2 为真时执行的代码
}
...
  else if (条件表达式N) {
    // 条件表达式 N 为真时执行的代码
} else {
    // 所有条件表达式都为假时要执行的代码
}

Tip: During the execution of if else if else statement, when it encounters a established conditional expression, the code in { } will be executed immediately and then exit. The entire if else if else statement will not be executed if there is a valid conditional expression in the subsequent code.

The sample code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        var now = new Date();           // 获取当前的完整日期
        var dayOfWeek = now.getDay();   // 获取一个 0-6 之间的数字,用来表示当前是星期几,0 表示星期日、1 表示星期一、以此类推
        if(dayOfWeek == 0) {            // 判断当前是星期几
            alert("星期日")
        } else if(dayOfWeek == 1) {
            alert("星期一")
        } else if(dayOfWeek == 2) {
            alert("星期二")
        } else if(dayOfWeek == 3) {
            alert("星期三")
        } else if(dayOfWeek == 4) {
            alert("星期四")
        } else if(dayOfWeek == 5) {
            alert("星期五")
        } else {
            alert("星期六")
        }
    </script>
</body>
</html>

The running results are as shown below:

How to use if statement in javascript

Notes

When using nested if else, if there is only one line of statement, it should be wrapped in curly brackets to avoid condition ambiguity.

For example, the following nested if else can easily lead to misunderstanding:

if(0)
    if(1)
        console.log(1);
else
    console.log(0);

For the above code, the JavaScript interpreter will interpret it according to the following logical level based on the proximity principle:

if(0)
    if(1)
        console.log(1);
    else
        console.log(0);

So using braces can avoid many problems:

if(0){
    if(1) console.log(1);
}else{
    console.log(0);
}

[Related recommendations:

javascript learning tutorial]

The above is the detailed content of How to use if statement in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

CSS ID and Class: common mistakesCSS ID and Class: common mistakesMay 13, 2025 am 12:11 AM

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

See all articles

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 Article

Hot Tools

SecLists

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor