JavaScript Basics: Your First Programs
Operators and Conditions
In this lesson you will
- Use arithmetic and comparison operators
- Make decisions with if, else if and else
- Combine conditions with and, or and not
Introduction
A program that always does the same thing is not very useful. Real programs decide: if the password is wrong, show an error; if the basket is empty, hide the checkout button. To decide, you need to compare values.
Arithmetic
%is the remainder: what is left after dividing.7 % 2is1. It is handy for checking odd and even numbers.**is "to the power of".
Computers store decimals in binary, which causes small surprises:
Comparison
Comparisons produce a boolean, true or false.
Use === not ==
===(strict equality) compares value and type.==(loose equality) converts types first, which gives odd results.
Always use === and !==. It avoids a whole class of bugs.
Quick quiz
What does the strict comparison of the number 5 with the text 5 give?
if, else if, else
An if statement runs code only when a condition is true.
JavaScript checks each condition in order and runs the first block whose condition is true. Change temperature and run it again.
Logical operators
&&means and: both must be true.||means or: at least one must be true.!means not: flips true and false.
Truthy and falsy
In a condition, some values act like false: false, 0, "" (empty string), null, undefined and NaN. Everything else acts like true.
The ternary operator
A short way to choose between two values:
Quick quiz
Which value is falsy?
Try it yourself
Write a program that checks a number. If it is even, print "even", otherwise print "odd". Hint: use % and ===.
Summary
- Arithmetic:
+ - * / % **. Comparison givestrueorfalse. - Prefer
===and!==. if,else if,elsechoose what to run.&&,||and!combine conditions.- Values like
0,"",nullandundefinedare falsy.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading