Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
Use the if statement to execute some code only if a specified condition is true.
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!
Make a "Good day" greeting if the time is less than 20:00:
The result of x will be:
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true.
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting
The result of x will be:
Use the if....else if...else statement to select one of several blocks of code to be executed.
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:
The result of x will be:
Random link
This example will write a link to either W3Schools or to the World Wildlife
Foundation (WWF). By using a random number, there is a 50% chance for each of the
links.
The perfect solution for professionals who need to balance work, family, and career building.
More than 10 000 certificates already issued!
The HTML Certificate documents your knowledge of HTML.
The HTML5 Certificate documents your knowledge of advanced HTML5.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The jQuery Certificate documents your knowledge of jQuery.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
Your message has been sent to W3Schools.