JavaScript Conditionals

Source Material

See the first two chapters of the second edition of Eloquent JavaScript for more detailed information:

Boolean Values

Besides numbers and strings, there is another type that we talked about briefly. They are booleans. What are the possible values that a boolean can be?

true
false

Boolean Operators

There are a couple of operators that return boolean values!

Boolean Expressions

You can create boolean expressions with these operators:

1 === "1"
12 !== "cat"

By the way… what is the type of value given back by these, and how do we find out what the type actually is?

# boolean
var result =  1 === "1"
typeof result

Boolean Expressions Give Back Boolean Values!

Conditionals

See Conditional Execution in Eloquent JavaScript

A conditional is a way of allowing us to conditionally execute code based on a boolean expression.

If Statement

Conditionally execute a branch of code.

if (some_boolean_expression) {
	// do stuff here if expression is true
}

If / Else Statement

Execute one branch if condition is true, another branch if condition is false. An else must have a preceding if!

if (some_boolean_expression) {
	// do stuff here if expression is true
} else {
	// do stuff here if expression is false
}

If / Else If

Chain multiple conditions. You can add else at the end as well. Conditions are evaluated until the first true condition, at which point the if statement finishes immediately.

if (boolean_expression_1) {
	// do stuff here if expression 1 is true
} else if (boolean_expression_2) {
	// do stuff here if expression 2 is true
} else if (boolean_expression_3) {
	// do stuff here if expression 3 is true
}

Boolean Expression

Note that within the parentheses is some expression that produces a boolean values (true or false).

if (boolean_expression_1) {
	// do stuff here if expression 1 is true
} 

Blocks of Code

Curly braces denote statements of code that are grouped together. Everything within the curly braces below is considered part of the if statement.

if (boolean_expression_1) {
	// do stuff here if expression 1 is true
}