BETAThis is a new service – your feedback will help us to improve it.

Conditional logic

The strength of Javascript compared to simpler languages like HTML and CSS is logic.

Javascript programs can run code in response to circumstances.

Check two things are the same

We can test whether two things are equal by using two equals signs together:

let age = 30

console.log(age == 35)

It's important to use two signs. Using a single sign does something different—it assigns a value to a variable.

In the above example, we will see the message false logged to the console, because age does not equal 35.

If the two things were equal, we would see the message true instead.

If statements

The simplest form of logic is the if statement.

An if statement has a condition, and some code to run if the condition is true.

let age = 30

if (age == 30) {
	console.log("The age is 30!")
}

In this example, the if statement will print a message to the console, because age does indeed equal 30.

We can put whatever code we like inside the curly brackets. We could even put more if statements inside.

If/else statements

We can also provide a second block of code to run if the condition is not true.

let age = 30

if (age == 30) {
	console.log("The age is 30!")
} else {
	console.log("The age is NOT 30!")
}
Try to create an if statement with a block of code that runs only when two conditions are true.
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Adding interactivity
  1. Introducing Javascript
  2. Your first Javascript program
  3. Variables
  4. Conditional logic
  5. Affecting the page
  6. Making a menu
  7. Responding to user actions
  8. Keep your Javascript accessible
  9. Get confident with Javascript
  10. Add interactivity to your prototypesP