Операторы и приведение типов
После урока вы сможете
- Всегда понимать разницу == и ===
- Предсказывать truthy/falsy в условиях
- Применять ??, ?. и ??= без сюрпризов
Операторы связывают значения в выражения. В JavaScript многие операторы неявно приводят типы (coercion). Отсюда классические загадки вроде [] + {} — мы разберём правила, чтобы писать явный код.
Арифметика
console.log(10 + 3); // 13
console.log(10 - 3); // 7
console.log(10 * 3); // 30
console.log(10 / 3); // 3.333...
console.log(10 % 3); // 1
console.log(2 ** 10); // 1024
Унарные:
let n = 5;
console.log(+n); // 5
console.log(-n); // -5
console.log(++n); // 6 префикс: сначала +1, потом значение
n = 5;
console.log(n++); // 5 постфикс: сначала значение, потом +1
console.log(n); // 6
Сложение со строкой склеивает:
console.log(1 + "2"); // "12"
console.log("2" + 1); // "21"
console.log(1 + 2 + "3"); // "33"
console.log("3" + 1 + 2); // "312"
Минус, умножение, деление предпочитают числа:
console.log("10" - 2); // 8
console.log("10" * "2"); // 20
console.log("10a" - 1); // NaN
Сравнение: === и ==
Строгое === / !==
Сравнивает без преобразования типов (с оговорками для NaN и -0):
console.log(1 === 1); // true
console.log(1 === "1"); // false
console.log(true === 1); // false
console.log(null === undefined); // false
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false
console.log(0 === -0); // true
Правило курса: используйте === и !== по умолчанию.
Нестрогое == / !=
Сначала может привести типы по сложному алгоритму Abstract Equality Comparison:
console.log(1 == "1"); // true
console.log(true == 1); // true
console.log(null == undefined); // true
console.log(null == 0); // false
console.log("" == 0); // true
console.log([] == false); // true — сюрприз
Запомнить все таблицы наизусть не обязательно; достаточно знать: == опасен, кроме осознанного x == null (ловлет и null, и undefined).
function missing(value) {
return value == null; // true для null и undefined
}
console.log(missing(null)); // true
console.log(missing(undefined)); // true
console.log(missing(0)); // false
Truthy и falsy
В условии значение приводится к boolean. Falsy-значения:
false0,-0,0n""(пустая строка)nullundefinedNaN
Всё остальное — truthy, включая "0", "false", [], {}.
function show(value) {
if (value) {
console.log("truthy", value);
} else {
console.log("falsy", value);
}
}
show(0);
show("0");
show([]);
show({});
show(null);
Явное приведение:
console.log(Boolean(0)); // false
console.log(!!"hi"); // true
Логические операторы
console.log(true && false); // false
console.log(true || false); // true
console.log(!true); // false
Важнее: && и || возвращают операнд, а не обязательно boolean:
console.log("a" && "b"); // "b"
console.log("" && "b"); // ""
console.log("a" || "b"); // "a"
console.log("" || "b"); // "b"
Классический fallback до эпохи ??:
function title(name) {
return name || "Anonymous";
}
console.log(title("Ada")); // Ada
console.log(title("")); // Anonymous
console.log(title(0)); // Anonymous — часто баг, если 0 валиден
Nullish coalescing: ??
console.log(null ?? "fallback"); // "fallback"
console.log(undefined ?? "fallback"); // "fallback"
console.log(0 ?? "fallback"); // 0
console.log("" ?? "fallback"); // ""
console.log(false ?? "fallback"); // false
Когда ноль или пустая строка — валидные данные, берите ??, не ||.
function pageSize(options) {
return options.size ?? 20;
}
console.log(pageSize({ size: 0 })); // 0
console.log(pageSize({})); // 20
Смешение с && / || требует скобок:
// const x = a ?? b || c; // SyntaxError без скобок
const x = (a ?? b) || c;
const y = a ?? (b || c);
Optional chaining: ?.
Безопасный доступ к цепочке: если база null/undefined, выражение даёт undefined, без TypeError.
const user = {
profile: {
city: "Berlin",
},
};
console.log(user.profile?.city); // "Berlin"
console.log(user.address?.city); // undefined
console.log(user.profile?.zip?.code); // undefined
Вызов метода:
const api = {
save() {
return "ok";
},
};
console.log(api.save?.()); // "ok"
console.log(api.load?.()); // undefined
Индекс:
const rows = null;
console.log(rows?.[0]); // undefined
Не путайте с ??:
const city = user.address?.city ?? "Unknown";
Логические присваивания
let a = null;
a ??= 10; // как a = a ?? 10
console.log(a); // 10
let b = 0;
b ||= 5; // b = b || 5 → 5
console.log(b);
let c = "keep";
c &&= "changed"; // c = c && "changed"
console.log(c); // "changed"
??= особенно удобен для дефолтов в конфиге:
function normalize(config) {
const cfg = { ...config };
cfg.retries ??= 3;
cfg.timeout ??= 1000;
return cfg;
}
console.log(normalize({ retries: 0 }));
Тернарный оператор
const age = 20;
const label = age >= 18 ? "adult" : "minor";
console.log(label);
Вложенные тернарники плохо читаются — лучше if или словарь.
Операторы сравнения порядка
console.log(3 > 2); // true
console.log(3 >= 3); // true
console.log("a" < "b"); // true — по Unicode/UTF-16 коду
console.log("10" > "9"); // false — сравнение строк посимвольно
console.log(Number("10") > Number("9")); // true
Для чисел приводите явно, если данные пришли строками.
Побитовые (знать о существовании)
console.log(5 & 3); // 1
console.log(5 | 3); // 7
console.log(5 ^ 3); // 6
console.log(~5); // -6
console.log(1 << 3); // 8
Побитовые операции приводят к 32-битному целому. В прикладном коде встречаются реже; иногда ~~n как грубый trunc — лучше Math.trunc.
Оператор запятая
let x = (1, 2, 3);
console.log(x); // 3
Редко нужен явно; встречается в for заголовках.
Явные преобразования — шпаргалка
String(123); // "123"
(123).toString(); // "123"
Number(" 12 "); // 12
Number(""); // 0
Number("x"); // NaN
parseInt("12px", 10); // 12
parseFloat("3.14"); // 3.14
Boolean(1); // true
Boolean(0); // false
Number(null) → 0, Number(undefined) → NaN — ещё одна причина не полагаться на неявность.
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(null + 1); // 1
console.log(undefined + 1); // NaN
Паттерны вместо магии
Проверка «есть значение»
function hasValue(x) {
return x !== null && x !== undefined;
}
или x != null.
Дефолт для числа
function clampRetries(n) {
const value = n ?? 3;
return Math.min(Math.max(value, 0), 10);
}
Безопасный deep-get
function getCity(user) {
return user?.contacts?.address?.city ?? null;
}
Разбор классических выражений
console.log([] + []); // ""
console.log([] + {}); // "[object Object]"
console.log({} + []); // зависит от контекста ASI / как парсится
console.log(true + true); // 2
console.log(true + false); // 1
Не пишите такое в проде. Если видите в шутке — вспомните ToPrimitive / ToNumber / ToString.
console.log(String([])); // ""
console.log(String({})); // "[object Object]"
console.log(Number([])); // 0
console.log(Number([2])); // 2
console.log(Number([1, 2])); // NaN
Приоритет (фрагмент)
Выше арифметика, затем сравнения, затем &&, затем ||, присваивание ниже. При сомнении — скобки:
const ok = (score >= 50 && !banned) || isAdmin;
Практика: нормализация query
function normalizeQuery(input) {
const q = {
page: input.page ?? 1,
limit: input.limit ?? 20,
sort: input.sort ?? "createdAt",
tag: input.tag ?? null,
};
if (q.page < 1) q.page = 1;
if (q.limit < 1) q.limit = 1;
return q;
}
console.log(normalizeQuery({ page: 0, limit: undefined }));
console.log(normalizeQuery({}));
Запустите в Node и поменяйте входы.
Практика: безопасный вызов колбэка
function run(handler, payload) {
return handler?.(payload) ?? null;
}
console.log(run((x) => x * 2, 5)); // 10
console.log(run(undefined, 5)); // null
Частые ошибки
if (arr)вместо проверки длины.value || defaultзатирает0и"".user.profile.cityбез?.— падение на отсутствииprofile.- Смешение
??с||без скобок — SyntaxError. ==«чтобы короче» — потом час отладки.
const port = process.env.PORT ?? 3000; // строка из env всё же строка!
const portNum = Number(process.env.PORT ?? 3000);
В Node переменные окружения — строки; ?? не заменит Number.
Таблица выбора
| Ситуация | Что взять |
|---|---|
| Сравнение значений | === |
| «Нет значения» null/undefined | == null или ?? |
| Дефолт, ноль валиден | ?? / ??= |
| Дефолт, пустая строка = нет данных | || осознанно |
| Доступ к вложенности | ?. |
| Явный boolean для API | Boolean(x) / !!x |
Итог
Строгое сравнение, понимание falsy, ?? и ?. — база читаемого JS. Дальше соберём это в if, switch и циклы.
Чему равно выражение 0 ?? 10?
// Упрощённо: false → 0, [] → "" → 0, затем 0 == 0
console.log([] == false); // true
console.log([] === false); // false
console.log(Boolean([])); // true — в if([]) ветка true!
Именно поэтому смешивать == с массивами/объектами — плохая идея. В условиях опирайтесь на явные проверки.
Чеклист готовности
Я уверенно умею
0 / 4 выполнено
Дочитали до конца?
Отметьте урок пройденным — так проще вернуться туда, где остановились.