Home >Web Front-end >Front-end Q&A >Do you add a semicolon to if in javascript?
There is no semicolon in if in JavaScript because the if statement is used to specify the JavaScript code to be executed if the condition is true. Its syntax is such as "if(...) {...}" , no semicolon is needed.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
Does the if in javascript add a semicolon?
The if statement in JavaScript does not include a semicolon.
Conditional statements are used to perform different actions based on different conditions.
Conditional statements
When you write code, you often need to perform different actions based on different judgments.
You can do this using conditional statements in your code.
In JavaScript, we can use the following conditional statements:
Use if to specify the code block to be executed, if the specified condition is true
Use else to Specify the code block to be executed, if the same condition is false
Use else if to specify a new condition to be tested, if the first condition is false
Use switch to specify multiple Alternative code blocks to execute
if statement
Use the if statement to specify the JavaScript code block to be executed if the condition is true.
Syntax
if (条件) { 如果条件为 true 时执行的代码 }
Note: if uses lowercase letters. Capital letters (IF or If) generate JavaScript errors.
Example
If the time is earlier than 18:00, send the greeting "Good day":
if (hour < 18) { greeting = "Good day"; }
If the time is earlier than 18:00, the result of greeting will be :
Good day
else statement
Please use the else statement to specify the code block if the condition is false.
if (条件) { 条件为 true 时执行的代码块 } else { 条件为 false 时执行的代码块 }
Example
If hour is less than 18, create "Good day" greeting, otherwise "Good evening":
if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
greeting result:
Good day
else if statement
Use else if to specify a new condition when the first condition is false.
Syntax
if (条件 1) { 条件 1 为 true 时执行的代码块 } else if (条件 2) { 条件 1 为 false 而条件 2 为 true 时执行的代码块 } else { 条件 1 和条件 2 同时为 false 时执行的代码块 }
Example
If the time is earlier than 10:00, create the "Good morning" greeting, if not, but the time is earlier than 18:00, create "Good day" greeting, otherwise create "Good evening":
if (time < 10) { greeting = "Good morning"; } else if (time < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
greeting result:
Good day
Video tutorial recommendation: "javascript basic tutorial"
The above is the detailed content of Do you add a semicolon to if in javascript?. For more information, please follow other related articles on the PHP Chinese website!