DevNotes
@devnotes ·
JavaScript Part 2: Values, types and operators
Every value in JavaScript has a type, and the type decides what you can do with it. A lot of beginner bugs come from mixing types up.
The everyday types
typeof tells you a value's type: typeof price gives "number". One odd exception: typeof null gives "object", an old mistake JavaScript keeps so that old websites don't break.
Numbers
JavaScript has one number type for whole numbers and decimals alike.
% looks odd, but it comes up a lot. n % 2 === 0 is the standard way to check whether a number is even.
One quirk to know early: 0.1 + 0.2 gives 0.30000000000000004. Computers store decimals in binary, and some of them can't be stored exactly. For money, count in paise as whole numbers, and divide by 100 only when you show the amount.
Strings
Text goes in quotes: single, double, or backticks.
Backticks make a template literal. Anything inside ${ } is worked out and dropped into the text. It's the cleanest way to build a string out of text and values, so use it whenever you mix the two.
Strings come with tools built in:
When types mix
This is where JavaScript trips people up:
+ with a string joins text, so 3 becomes "3". The other maths operators turn strings into numbers instead. Anything you read from a form input is a string, even if it's digits, so convert it before doing maths:
Comparing values
Always use === and !==. The loose == converts types behind your back, and its rules are hard to remember: 0 == "" is true, for example. With ===, there are no conversions to remember.
Try it
In the console, make a price and a quantity, then print a line like Total: Rs 998 with a template literal. Then work out what "10" + 5 - 5 gives, and why, before you check.
Next: JavaScript Part 3: Making decisions with if
Join WIK to like and reply to DevNotes and see more like this.