Welcome to my website!

How an If Statement Works

One of the most useful tools in JavaScript is the basic If statement. In this blog, I will be going over how it functions. Fundamentally, If statements are very easy to understand, but they do have some nuance to them. Hopefully I can shed some light on them to help you become a better programmer.

An If statement executes a block of code if a specified condition is true. As you might be able to see, this can be used in many ways to help a programmer create code.

Here is the basic syntax of an If statement:

	If(){

	}
				

Inside of the parenthesis is where the condition would go. An example would be to compare two numbers. See below:

	If(10 > 5){

	}					
				

In the above example, it's asking if 10 is greater than 5. That is true, so it will execute code inside of the curly brackets if there was code in it. If it wasn’t true, for example 10 > 15, then it would just skip to the end of the statement and continue the program.

You insert what you want to happen if it is true like this:

	If(10 > 5){
		prompt("that is true!")
	}	
				

Alright, so those are the basics, but there is some other cool stuff you can do with If statements. One being that you can nest If statements inside of other If statements. See below:

	If(10 > 5){
		prompt("that is true!")
		if(10 < 20){
			promt("10 is less than 20!")
		}
	}		
				

With this code snippet, it will prompt “True!” and "10 is less than 20!"


Another thing you can do is use variables for the condition statement. The statement below would be true.

	var x = 10;
	var y = 5;
	If(x > y){
			prompt("that is true!")
		}	
				

And lastly, the IfElse and ElseIf statements. Both can be tacked on the end of an If statement. The IfElse will execute code if the If statement is false. And the ElseIf will do the same but also with an additional condition check.

If Else:

	If(10 > 5){
		prompt("that is true!")
	}else{
		prompt("False!")
	}	
				

Else If:

	If(10 > 5){
		prompt("that is true!")
	}elseif(10 = 10){
		prompt("They are equal")
	}
				

For the ElseIf, it will only prompt "that is true!"

And there you have it! The basics of how an If statement works.