What the IF
Question:
Describe the purpose and function of JavaScript if
statements and demonstrate how they work.
An if
statement gives the program the ability to make a decision which is necessary for most programs. For example, you might say “If the word is spelled correctly then I will get a message that it was correct” In Javascript, this can be written as:
if (x === str) {
document.write("you spelled it correctly");
}
Here x
is compared to a string and if they match you get a message that its correct.
Syntax
There are several parts to the construction of an if statement. First, you write if
then its followed by a (
then the text condition closed off by the )
. Next, you have a curly brace {
to mark the beginning of the block of code. Any time in Javascript the {}
are used they mark out a block of code so that any code within runs line by line till it get to the last curly brace. Each line in the curly braces ends with a semicolon, ;
.
Although you could get away without using the curly braces if you only have one line of code to run I would advise you not to as this could cause problems if you forget to add when needed.
\\ This will work but better to just use braces
if (x === str)
document.write("Hello");
\\ This won't work only the first line of code will run
if(x === str)
document.write("Hello");
alert("Goodbye") ;
\\ Best way do this all the time
if(x === str) {
document.write("Hello");
alert("Goodbye");
}
Example Simple:
See the Pen Simple if by oscar (@nopity) on CodePen.
Example Complex:
Here’s a Fahrenheit to Celsius program, don’t worry about the other stuff but as you can see it uses two if
statements. When the variable is over zero or equal to 100 it will print that statement to the console. Try entering 212 to see this in action.
See the Pen Fahrenheit to Centigrade by oscar (@nopity) on CodePen.