By: Syed Fazal in Javascript Tutorials on 2008年08月16日 [フレーム]
One of the most frequently used statements in JavaScript (and indeed, in many languages), is the if statement. The if statement has the following syntax:
if ( condition ) statement1 else statement2
The condition can be any expression; it doesn’t even have to evaluate to an actual Boolean value. JavaScript converts it to a Boolean for you. If the condition evaluates to true , statement1 is executed; if the condition evaluates to false , statement2 is executed. Each of the statements can be either a single line or a code block (a group of code lines enclosed within braces). For example:
if (i > 25)
alert(“Greater than 25.”); //one-line statement
else {
alert(“Less than or equal to 25.”); //block statement
}
You can also chain if statements together like so:
if ( condition1 ) statement1 else if ( condition2 ) statement2 else statement3
Example:
if (i > 25) {
alert(“Greater than 25.”)
} else if (i < 0) {
alert(“Less than 0.”);
} else {
alert(“Between 0 and 25, inclusive.”);
}
Tip: It’s considered best coding practice to always use block statements, even if only one line of code is to be executed. Doing so can avoid confusion about what should be executed for each condition.
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
Most Viewed Articles (in Javascript )
Dynamically modify the option set in Dynamics 365 forms
promise and .then() in JavaScript
reduce() and filter() in JavaScript
History and evolution of Javascript
Using parseInt() and parseFloat() in JavaScript to convert data types to Numbers
Show how many characters remaining in a html text box using javascript
Latest Articles (in Javascript)
© 2023 Java-samples.com
Tutorial Archive: Data Science React Native Android AJAX ASP.net C C++ C# Cocoa Cloud Computing EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Trends WebServices XML Office 365 Hibernate
Latest Tutorials on: Data Science React Native Android AJAX ASP.net C Cocoa C++ C# EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Cloud Computing WebServices XML Office 365 Hibernate