DevNotes

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

JavaScript
const price = 499;          // numberconst title = "Notebook";   // stringconst inStock = true;       // booleanlet coupon = null;          // null: empty on purposelet address;                // undefined: no value yet

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.

JavaScript
10 + 3   // 1310 - 3   // 710 * 3   // 3010 / 3   // 3.333333333333333510 % 3   // 1, the remainder2 ** 3   // 8, two to the power of three

% 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.

JavaScript
const first = 'Ravi';const last = "Kumar";const full = `${first} ${last}`;  // "Ravi Kumar"

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:

JavaScript
full.length          // 10full.toUpperCase()   // "RAVI KUMAR"full.includes("Ku")  // true"  hi  ".trim()      // "hi"

When types mix

This is where JavaScript trips people up:

JavaScript
"5" + 3    // "53""5" - 3    // 2"5" * "2"  // 10

+ 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:

JavaScript
const qty = Number("5");   // 5Number("abc")              // NaN, which means "not a number"

Comparing values

JavaScript
5 === 5      // true5 === "5"    // false: different types5 == "5"     // true: == converts types first5 !== 3      // true10 > 9       // true

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

javascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.