CINXE.COM
JavaScript If Statements
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="keywords" content="javascript if statement, else, elseif, else if, javascript tutorial, code, function, source, learn, method, javascript dropdown menu, rollovers, form validation, pop up windows, scripting, jscript, reference, switch, case"> <meta name="Description" content="Learn about JavaScript If statements (includes Else and Else If)."> <link rel="canonical" href="https://www.quackit.com/javascript/tutorial/javascript_if_statements.cfm"> <title>JavaScript If Statements</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link rel="shortcut icon" href="/pix/favicon96.png"> <link rel="apple-touch-icon" href="/pix/apple-touch-icon.png"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet"> <link href="/common/css/master.45.min.css" rel="stylesheet"> <script async src="https://cdn.fuseplatform.net/publift/tags/2/3499/fuse.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-Q3H025ZKLN"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-Q3H025ZKLN'); </script> </head> <body> <header class="site-header"> <div class="site-header-base"> <div class="site-logo"> <a title="Quackit Homepage" target="_top" href="/"><img src="/pix/quackit_logo_watermark.png" width="87" height="33" alt="Quackit Logo"></a> </div> <button id="site-nav-toggler" class="site-nav-toggler" aria-expanded="false" aria-controls="site-nav"> <span class="sr-only">Toggle navigation</span> ☰ </button> </div> <nav id="site-nav" class="site-nav"> <div class="site-links"> <ul> <li><a href="/"><i class="fa fa-home"></i> <span class="sr-only">Home</span></a></li> <li><a href="/html/">HTML</a></li> <li><a href="/css/">CSS</a></li> <li><a href="/scripting/">Scripting</a></li> <li><a href="/database/">Database</a></li> </ul> </div> <div class="site-search-top"> <form action="/search/" id="cse-search-box-bottom" class="site-search"> <div> <input type="hidden" name="cx" value="partner-pub-6331358926293806:98x0fk-bbgi"> <input type="hidden" name="cof" value="FORID:10"> <input type="hidden" name="ie" value="ISO-8859-1"> <input type="text" name="q" size="20" class="site-search-input"> <button type="submit" name="sa" class="site-search-button"><i class="fa fa-search"></i></button> </div> </form> </div> </nav> </header> <div class="main"> <article class="content"> <h1 class="page-title">JavaScript If Statements</h1> <div class="ad ad-top"> <!-- GAM 71161633/QCKIT_quackit/article_header --> <div data-fuse="23059883623"></div> </div> <ul class="pager"> <li><a href="/javascript/tutorial/javascript_events.cfm"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> JavaScript Events</a></li> <li><a href="/javascript/tutorial/javascript_switch_statement.cfm">JavaScript Switch Statement <i class="fa fa-long-arrow-right" aria-hidden="true"></i></a></li> </ul> <p class="lead">When you write code, you will often need to use conditional statements, such as "if" statements. Here's an explanation of the JavaScript If statement.</p> <p>A <dfn>conditional statement</dfn> refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like. <p>JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only <em>if</em> a given condition is true.</p> <div class="ad"> <!-- GAM 71161633/QCKIT_quackit/article_incontent_1 --> <div data-fuse="23059883629"></div> </div> <h2>Example If statement:</h2> <script src="/common/js/codemirror/lib/codemirror.js"></script> <script src="/common/js/codemirror/mode/htmlmixed/htmlmixed.js"></script> <script src="/common/js/codemirror/mode/css/css.js"></script> <script src="/common/js/codemirror/mode/javascript/javascript.js"></script> <script src="/common/js/codemirror/mode/xml/xml.js"></script> <div class="code-only"> <textarea id="example1" autocomplete="off" spellcheck="false"><script>
function analyzeColor1(myColor) {
	if (myColor == "Blue") {
	 alert("Just like the sky!");
	}
}
</script>
<h3>Favorite Color</h3>
<label>
	<input type="radio" name="fav_color1" value="Blue" onclick="analyzeColor1(this.value);"> Blue
</label>
<label>
	<input type="radio" name="fav_color1" value="Red" onclick="analyzeColor1(this.value);"> Red
</label>
<label>
	<input type="radio" name="fav_color1" value="Green" onclick="analyzeColor1(this.value);"> Green
</label></textarea> </div> <script> var exampleCode1 = CodeMirror.fromTextArea(document.getElementById("example1"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <h3>Explanation of code</h3> <ul> <li>We create three radio buttons using the HTML <a href="/html/tags/html_input_tag.cfm"><code><input></code></a> element. Each of the radio buttons have a different value. The value is set using the <code>value</code> attribute (eg, <code>value="Blue"</code>)</li> <li>When the user clicks any of the radio buttons, we use the <code>onclick</code> event handler to call the <code>analyzeColor1()</code> function. When we call that function, we pass in the value of the radio button (using <code>this.value</code>). The function then takes that value and performs an <code>if</code> statement on it. </li> <li>The <code>if</code> statement's first line is <code>if (myColor == "Blue") {</code>. This means that it will test the value of the <code>myColor</code> variable. It will test to see if it's value is equal to <code>Blue</code>. Notice the opening curly brace on this line (the closing one is two lines down). </li> <li>In between the curly braces, we write whatever we want to occur in the event the test is true (i.e. the color is equal to <code>Blue</code>). In this case, we display an <a href="/javascript/javascript_alert_box.cfm">alert box</a> with a customized message.</li> </ul> <h3>To create a JavaScript If statement</h3> <p.To construct a JavaScript if statements, do the following:</p> <ol> <li>Start with the word <code>if</code></li> <li>Between open and closed brackets, write the actual condition that is being tested (i.e. if something is equal to something else).</li> <li>Between open and closed curly brackets (<code>{}</code>), specify what will happen if the condition is satisfied.</li> </ol> <h1>JavaScript If Else statement</h1> <p>The above code is OK if you only want to display something when the condition is true. But what if you want to display something when the condition is <em>not</em> true. For example, what if the variable <code>myColor</code> was equal to, say, <code>Red</code>?</p> <p>This is where an If Else statement comes in handy. The <code>else</code> part is what we're interested in here. The <code>else</code> is what tells the browser what to do if the condition is not true.</p> <h2>Example If Else statement:</h2> <script src="/common/js/codemirror/mode/htmlmixed/htmlmixed.js"></script> <div class="code-only"> <textarea id="example2" autocomplete="off" spellcheck="false"><script>
function analyzeColor2(myColor) {
	if (myColor == "Blue") {
		alert("Just like the sky!");
		}
	else {
		alert("Didn't pick blue huh?");
	}
}
</script>
<h3>Favorite Color</h3>
<label>
	<input type="radio" name="fav_color2" value="Blue" onclick="analyzeColor2(this.value);"> Blue
</label>
<label>
	<input type="radio" name="fav_color2" value="Red" onclick="analyzeColor2(this.value);"> Red
</label>
<label>
	<input type="radio" name="fav_color2" value="Green" onclick="analyzeColor2(this.value);"> Green
</label>
<label>
	<input type="radio" name="fav_color2" value="None" onclick="analyzeColor2(this.value);"> None
</label></textarea> </div> <script> var exampleCode2 = CodeMirror.fromTextArea(document.getElementById("example2"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <h3>Explanation of code</h3> <p>The first part of this code is the same as the previous example. The second part is where we specify what to do if the condition is not true. Therefore, you write <code>else</code> followed by what you want to occur, surrounded by curly braces. </p> <ol> <li>Write an if statement (as per first example)</li> <li>Follow this with the word <code>else</code></li> <li>Between open and closed curly brackets (<code>{}</code>), specify what to do next.</li> </ol> <h1>JavaScript If Else If statement</h1> <p>The If Else If statement is more powerful than the previous two. This is because you can specify many different outputs based on many different conditions — all within the one statement. You can also end with an <code>else</code> to specify what to do if none of the conditions are true.</p> <h2>Example If Else If statement:</h2> <div class="code-only"> <textarea id="example3" autocomplete="off" spellcheck="false"><script>
function analyzeColor3(myColor) {
	if (myColor == "Blue") {
		alert("Just like the sky!");
		}
	else if (myColor == "Red") {
		alert("Just like shiraz!");
	}
	else {
		alert("Suit yourself then...");
	}
}
</script>
<h3>Favorite Color</h3>
<label>
	<input type="radio" name="fav_color3" value="Blue" onclick="analyzeColor3(this.value);"> Blue 
</label>
<label>
	<input type="radio" name="fav_color3" value="Red" onclick="analyzeColor3(this.value);"> Red 
</label>
<label>
	<input type="radio" name="fav_color3" value="Green" onclick="analyzeColor3(this.value);"> Green 
</label>
<label>
	<input type="radio" name="fav_color3" value="None" onclick="analyzeColor3(this.value);"> None
</label></textarea> </div> <script> var exampleCode3 = CodeMirror.fromTextArea(document.getElementById("example3"), { mode: "htmlmixed", tabMode: "indent", styleActiveLine: false, lineNumbers: false, lineWrapping: true, theme: "q-dark" }); </script> <h3>Explanation of code</h3> <p>We started with an <code>if</code> and ended with an <code>else</code>, however, in the middle, we used an <code>else if</code> statement to specify what to do if the <code>myColor</code> variable was equal to Red. This statement looks exactly like the <code>if</code> statement — just with an <code>else</code> prepended to it.</p> <p>By the way, we could have specified as many <code>else if</code> conditions as we liked.</p> <p>If you do have many "else if" conditions, you might consider using a JavaScript Switch statement. The Switch statement is explained in the next lesson.</p> <ul class="pager"> <li><a href="/javascript/tutorial/javascript_events.cfm"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> JavaScript Events</a></li> <li><a href="/javascript/tutorial/javascript_switch_statement.cfm">JavaScript Switch Statement <i class="fa fa-long-arrow-right" aria-hidden="true"></i></a></li> </ul> </article> <div class="sidebar"> <nav> <ul> <li> <h3><a href="/javascript/tutorial/">JavaScript Tutorial</a></h3> <ul> <li><a href="/javascript/tutorial/introduction.cfm">Introduction</a></li> <li><a href="/javascript/tutorial/how_to_enable_javascript.cfm">How to Enable JavaScript</a></li> <li><a href="/javascript/tutorial/javascript_syntax.cfm">JavaScript Syntax</a></li> <li><a href="/javascript/tutorial/javascript_popup_boxes.cfm">JavaScript Popup Boxes</a></li> <li><a href="/javascript/tutorial/javascript_html.cfm">JavaScript and HTML</a></li> <li><a href="/javascript/tutorial/external_javascript_file.cfm">External JavaScript File</a></li> <li><a href="/javascript/tutorial/javascript_operators.cfm">JavaScript Operators</a></li> <li><a href="/javascript/tutorial/javascript_variables.cfm">JavaScript Variables</a></li> <li><a href="/javascript/tutorial/javascript_functions.cfm">JavaScript Functions</a></li> <li><a href="/javascript/tutorial/javascript_events.cfm">JavaScript Events</a></li> <li><a href="/javascript/tutorial/javascript_if_statements.cfm">JavaScript If Statements</a></li> <li><a href="/javascript/tutorial/javascript_switch_statement.cfm">JavaScript Switch Statements</a></li> <li><a href="/javascript/tutorial/javascript_while_loop.cfm">JavaScript While Loop</a></li> <li><a href="/javascript/tutorial/javascript_for_loop.cfm">JavaScript For Loop</a></li> <li><a href="/javascript/tutorial/javascript_try_catch.cfm">JavaScript Try Catch</a></li> <li><a href="/javascript/tutorial/javascript_escape_characters.cfm">JavaScript Escape Characters</a></li> <li><a href="/javascript/tutorial/javascript_void_0.cfm">JavaScript Void(0)</a></li> <li><a href="/javascript/tutorial/javascript_cookies.cfm">JavaScript Cookies</a></li> <li><a href="/javascript/tutorial/javascript_date_and_time.cfm">JavaScript Date and Time</a></li> <li><a href="/javascript/tutorial/javascript_arrays.cfm">JavaScript Arrays</a></li> <li><a href="/javascript/tutorial/two_dimensional_arrays.cfm">Two Dimensional Arrays</a></li> <li><a href="/javascript/tutorial/innerhtml_in_javascript.cfm">JavaScript innerHTML</a></li> <li><a href="/javascript/tutorial/unobtrusive_javascript.cfm">Unobtrusive JavaScript</a></li> <li><a href="/javascript/tutorial/javascript_summary.cfm">JavaScript Summary</a></li> </ul> </li> <li><h3>JavaScript Reference</h3> <ul> <li><a href="/javascript/examples/" title="">JavaScript Examples</a></li> <li><a href="/javascript/javascript_reserved_words.cfm" title="">JavaScript Reserved Words</a></li> <li><a href="/javascript/javascript_event_handlers.cfm" title="Introduction to the 12 JavaScript event handlers">JavaScript Event Handlers</a></li> <li><a href="/javascript/javascript_date_and_time_functions.cfm" title="Full listing of all JavaScript methods for dealing with date and time.">JavaScript Date and Time Functions</a></li> </ul> <li><h3>jQuery</h3> <ul> <li><a href="/jquery/tutorial/" title="">jQuery Tutorial</a></li> <li><a href="/jquery/examples/" title="">jQuery Examples</a></li> </ul> </li> <li><h3>JSON</h3> <ul> <li><a href="/json/tutorial/" title="Data format for exchanging data between applications and different environments.">JSON Tutorial</a></li> </ul> <li> </ul> </nav> <div class="ad ad-left"> <!-- GAM 71161633/QCKIT_quackit/article_vrec_2 --> <div data-fuse="23059511712"></div> </div> </div> <div class="ads"> <div class="ad ad-right"> <!-- GAM 71161633/QCKIT_quackit/article_vrec_1 --> <div data-fuse="23059883626"></div> </div> </div> </div> <div class="searchbox-bottom"> <form action="/search/" id="cse-search-box-bottom" class="site-search"> <div> <input type="hidden" name="cx" value="partner-pub-6331358926293806:npmuvy-i8kk"> <input type="hidden" name="cof" value="FORID:10"> <input type="hidden" name="ie" value="ISO-8859-1"> <input type="text" name="q" size="30" class="site-search-input"> <button type="submit" name="sa" class="site-search-button"><i class="fa fa-search"></i></button> </div> </form> <script src="//cse.google.com/cse/brand?form=cse-search-box-bottom&lang=en"></script> </div> <footer> <p class="about"><a href="/"><i class="fa fa-home"></i> Home</a> | <a href="/about.cfm" rel="nofollow">About</a> | <a href="/contact.cfm" rel="nofollow">Contact</a> | <a href="/terms_of_use.cfm" rel="nofollow">Terms of Use</a> | <a href="/privacy_policy.cfm" rel="nofollow">Privacy Policy</a></p> <p>© Copyright 2000 - 2024 Quackit.com </p> </footer> <script src="/common/js/spectrum/spectrum.js"></script> <script src="/common/js/lightbox2-master/dist/js/lightbox.min.js" charset="utf-8"></script> <script> $(document).ready(function(){ $( "#site-nav-toggler" ).click(function() { $( "#site-nav" ).toggle( "slow" ); }); }); </script> <script> $(function(){var a=window.location.href;$(".sidebar nav a").each(function(){a==this.href&&$(this).closest("li").addClass("selected")})}); </script> </body> </html>