JavaScript If...Else statement

JavaScript If...Else Statement

Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

Usually when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.

In JavaScript, we can use the following conditional statements:

if statement - Use this statement to execute code only when the specified condition is true

if... else statement - execute code when the condition is true and other code when the condition is false

if...else if....else statement - use this statement to select one of multiple blocks of code to Execute

switch statement - Use this statement to select one of multiple blocks of code to execute

If statement

The statement will only be executed if the specified condition is true code.

Syntax

if (condition)
{
Code executed when the condition is true
}

Please use lowercase if. Using uppercase letters (IF) will generate a JavaScript error!

If...else statement

Please use the if...else statement to execute the code when the condition is true, and when the condition is Execute other code when false.

Grammar

if (condition)
  {
  当条件为 true 时执行的代码
  }
else
  {
  当条件不为 true 时执行的代码
  }
点击这个按钮,获得基于时间的问候。点击这里function myFunction(){
var x="";
var time=new Date().getHours();
if (time
Continuing Learning
||
<html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>早安</b>") } else { document.write("<b>祝您愉快</b>") } </script> <p>本例演示 If...Else 语句。</p> <p>如果浏览器时间小于 10,那么会向您问“早安”,否则会向您问候“祝您愉快”。</p> </body> </html>
submitReset Code