if(1 < 5) {
console.log(‘Condition is true’);
}
Looking at the above code it is fairly self-explanatory. The statement outlines that if 1 is less than 5, then the code inside the block should run, and log ‘Condition is true’ to the console.
This is as complex as standard if statements get. They simply run if the statement inside the parenthesis returns true. If statements will only run the block of code once, unlike a loop, which will run it a number of times.
To write an if statement, you simply write the keyword ‘if’ (this keyword is case sensitive, so always lowercase ‘if’ as using uppercase will throw an error) followed by parenthesis. Inside the parentheses you can write just about anything you like and pass in any variables from outside of the statement if you wish. The only clause is that if you don’t write a condition that can’t be validated to true, the block of code will never run. After the parenthesis, and our condition, we write our code to be executed inside the curly braces. This code can be anything again, and can use the variables that were pulled in, global, or created inside the parenthesis. Then, during execution of the code, when the code reaches the if statement, JavaScript will determine whether the condition is met (if it returns TRUE), and if it is, it will execute the code inside the block one time.
There is no end to the statements and code combinations you could write. The if statement is one of the most powerful aspects of JavaScript – it allows us to be the masters of our own code and create an application that is intelligent, dynamic and knows how to respond to various conditions.
The else statement is an adjunctive to the if statement. You can’t have an else without an if. The else statement simply says, ‘if the main condition isn’t met, then do this.’ The statement will question ‘if this is true, do this, else do this’. Quite expressive. The formatting of an else statement is very simple – it follows immediately from the closing curly brace of an if statement and contains the simple keyword ‘else’ followed by its own set of curly braces which will contain the code to be run if the main condition isn’t satisfied. Let’s look at an example below following on from our if statement.