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!")
}
Part of Adding interactivity
- Introducing Javascript
- Your first Javascript program
- Variables
- Conditional logic
- Affecting the page
- Making a menu
- Responding to user actions
- Keep your Javascript accessible
- Get confident with Javascript
- Add interactivity to your prototypesP