The if statement in Javascript
By: Syed Fazal
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.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Use WinSCP to transfer log files remotely using Javascript
Verifying user input in JavaScript
Javascript to display client date and time on webpage
Getting Browser's height and width using Javascript
Highlighting text on a page using CSS
Scrolling message on the status bar using Javascript
Diabling Right Click option in a browser using Javascript
Password protect a web page using Javascript
Using revealTrans to do page transitions in Javascript
Form validation using Javascript
window.frames[i] in Javascript
Math object and Math functions in Javascript