Chapter 4: Decisions and Loops Flashcards
What happens in an if / else statement
A condition in ( ) is checked. If its true, the code that immediately follows the condition in { } is run. If not the code preceded by else in { } is run.
What do the following comparison operators do: == != === !== > =
== is equal to
!= not equal to
=== strict equal to (also checks the data type as well as the value)
!== strict not equal to (also checks the data type as well as the value)
> greater than
= greater than or equal to
In general how does a condition work for say we have 2 variables
Usually there is 2 operands and an operator. The operas are placed on either side of the operator. They can be value, expressions (remember these result in a single value) or variables and you’ll often see them enclosed in ( )
Can we use expressions as an operand?
Yes
e.g. (score1 + score2)
What are logical operators
The and, or, not. They allow us to compare the results of more then one comparison operator.
&& and
|| or
! not
What’s short circuit evaluation?
If a minimal conditions are met then any subsequent conditions are ignored.
What’s an if statement
It checks if a condition is true. If it is, it runs the code
if (score >= 50) {
congratulate();
}
What’s an if…else statement?
It specifies some code if a condition is true, or if not, some other code to run
if (score >= 50) { congratulate(); } else { failure(); }
What’s a switch statement? Write out the basic syntax
This allows you specify what the code should do if a particular value is true.
switch(level) {
case ‘One’:
title = ‘Level 1’;
break;
case ‘Two’:
title = ‘Level 2’;
break;
case ‘Three’:
title = ‘Level 3’;
break;
default:
title = ‘Test’;
break;
}
When should I use a switch or an if?
When a series of if’s are used, they are all checked even if a match has been found (so it performs more slowly then switch)
What is type coercion?
JS can convert data types behind the scenes to complete an operation
What does Javascript is weakly typed mean?
It means the data type of a variable can change (as opposed to a strongly typed language).
That’s why its a good idea to use strict equals and not equals (check if type coercion has occurred).
Every value in javascript can be treated as true or false because of type coercion. True or false?
True
The following values are considered as if they were false:
false boolean, number zero, NaN, empty value, variable with no value assigned
the following values are considered as if they were true:
boolean true, all numbers other than zero, strings with content, calculations, true written as a string, zero written as a string, false written as a string
When would you want to use a for loop?
When you want to run a loop a specific amount of times
When would you use a while loop?
You’re not sure how many times the loop needs to run. The condition is not a counter.
A variation of the while loop is the do…while. Main difference is the code in a do…while is run at least once.