Values, Variables and Operators
Declaring variables
const taxRate = 0.2; // cannot be reassigned
let total = 0; // can be reassigned
total = total + 10;
Use const by default and let when the value must change. Avoid the old var: its scoping rules cause bugs.
Primitive types
const count = 42; // number (integers and decimals share one type)
const price = 19.99;
const name = "Ada"; // string
const isAdmin = false; // boolean
let phone = null; // intentionally empty
let nickname; // undefined: never assigned
const big = 9007199254740993n; // bigint
typeof tells you the type: typeof "x" is "string". (Quirk: typeof null is "object".)
Numbers and money
0.1 + 0.2 is 0.30000000000000004, as in most languages. Store money as integer cents and format at the end:
const cents = 1999 * 3;
(cents / 100).toFixed(2); // "59.97"
Number("42"); // 42
Number("abc"); // NaN (not a number)
Number.isNaN(Number("abc"));// true
Strings
const product = "Hoodie";
`${product} costs $${(3900 / 100).toFixed(2)}`; // template literal
product.toUpperCase();
product.includes("ood"); // true
product.slice(0, 3); // "Hoo"
"a,b,c".split(","); // ["a", "b", "c"]
" hi ".trim(); // "hi"
Equality: always use ===
0 == "0" // true (coerces types: confusing)
0 === "0" // false (strict: compares type and value)
null == undefined // true
null === undefined // false
Use === and !== everywhere.
Truthy and falsy
Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy, including "0" and [].
Useful operators
const displayName = user.nickname || user.name; // first truthy value
const limit = settings.limit ?? 20; // only null/undefined fall back (0 is kept)
const city = user.address?.city; // optional chaining: no error if address is missing
count += 1; count++;
?? is safer than || for numbers and empty strings that are valid values.
Exercise
Write a function-free script that takes const priceCents = 2599 and const qty = 3, computes a 20% tax, and logs a receipt line using a template literal and toFixed(2).
Check yourself
- When should you use
letinstead ofconst? - Why is
===preferred over==? - What is the difference between
||and???
Ваш прогресс сохраняется только в этом браузере.
Отправить на проверку (10 баллов)