@46.30m on first video
Comparion operators
symbol | meaning | Example |
---|---|---|
= |
assign as in let name = 'John'; |
|
== |
equals regardless of data type. So a string '10' would be be equal, == to the number 10 . |
5 == ‘5’ is true |
!= |
does not equal regardless of data type. | 5 != 5 is false |
=== |
equals including the data type. '10' (a string) does not equal 10 (a number). |
5 === ‘5’ is false |
!== |
strict does not equal. Will be true if operands are equal bout of different types. |
5 !== ‘5’ is true |
<= |
less than or equals to | 5 <= 5 is true |
< |
less than | 5 < 5 is false |
>= |
greater than or equals to | 5 >= 5 is true |
> |
greater than | 5 > 5 is false |
Examples
let age = 60;
console.log(age === 60);
// returns true
Examples
let age = 60;
console.log(age === 60);
// returns true
Logical Operators
symbol | meaning |
---|---|
&& |
means AND. Returns true if both operands are true |
|| | (double pipe) means OR. Returns true if either operand is true |
! |
means NOT. Returns true if operand is false |
If statements
The basic syntax is
if ( some condition ) {
execute code
}
else {
execute other code
}
Here is a real life example
const x = 10;
if (x === '10') {
console.log('x is 10');
}
else {
console.log('x is not 10');
}
Using or
:
if (x < 5 || y < 7) {
console.log('We can buy something');
};
The Ternary Operator
JavaScript operators work with one or two values. An operator that acts on a single value is called a unary operator and on two values is a operator.
The ternary operator is the only operator that works with 3 values. It uses just two symbols: a question mark and a colon and works like an if ... else
statement.
The form is: some condiition ?
if true :
not true
The ?
represents then
and the colon :
means else
.
const tern = 'rhino' < 1100 ? 'extinction' : 'red list';
// if the score is less than ten have a cat otherwise have a dog.
const pet = score < 10 ? 'cat' : 'dog';
Switches
With many else if
statements it can be more readable to use a switch statement instead.
const phyla = ['viverids', 'theropoda', ]
let x = 9;
const color = x > 10 ? 'red' : 'blue';
switch(color) {
case 'red':
console.log('colour is red');
break;
case 'blue':
console.log('colour is blue');
break;
default:
console.log('colour is neither red nor blue');
break;
}
The default is used in case both of the first two conditions are not met. You can have multiple options here, for every colour for instance.