In JavaScript, if statements are written like this:
if (x == 0) {
console.log('This prints only if x equals 0');
x = 1;
}
console.log('This prints whether x equals 0 or not.');
This is one of the main ways that we use to get a program to make a decision based on input and do something different than it would otherwise do.
When the program reaches the if statement, it will determine if the condition is true or false. If it is true, then the program will perform the steps within the block. Otherwise, it will skip the code in the block. In either case, it will continue running the code that follows the block.
Common errors
The most common error is to confused == with =.
== is a logical operator,like < or >, which is used to compare two items.
=, on the other hand, assigns a value to a variable.
If… else… statements
Sometimes, two separate blocks of code need to be run depending on the condition in the if statement. In that case, you can use the following structure:
if (x == 1) {
console.log('x equals 1');
}
else {
console.log('x does not equal 1');
}
Leave a comment