- How to Set Default Value Only in Case of null or undefined in JavaScript?
- Using the Nullish Coalescing Operator
- Using the Nullish Assignment Operator
- Explicitly Checking for Nullish Value
- null
- Try it
- Syntax
- Description
- Examples
- Difference between null and undefined
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- null
- Кратко
- Пример
- Как понять
- На практике
- Николай Лопин советует
- На собеседовании
- How to Set Default Value Only in Case of null or undefined in JavaScript?
- Using the Nullish Coalescing Operator
- Using the Nullish Assignment Operator
- Explicitly Checking for Nullish Value
How to Set Default Value Only in Case of null or undefined in JavaScript?
To set a default value only in case of a nullish value (i.e. undefined or null ), you can do the following:
Using the Nullish Coalescing Operator
If the left-hand side of an expression is nullish value, then you can simply use the nullish coalescing operator ( ?? ) to specify a default value, for example, like so:
// ES11+ console.log(null ?? 'default'); // 'default' console.log(undefined ?? 'default'); // 'default'
You can also combine the nullish coalescing operator ( ?? ) with the optional chaining operator ( ?. ), to return a default value when the optional chaining operator evaluates to undefined . For example:
// ES11+ const obj = < foo: 'bar' >; const value = obj?.nonExistent ?? 'default'; console.log(value); // 'default'
Using the Nullish Assignment Operator
The logical nullish assignment operator ( ??= ) allows you to only assign a value to a variable if it is nullish. For example:
// ES12+ let value; value ??= 'default'; console.log(value); // 'default'
In the example above, since the variable » value » is undefined , the nullish assignment operator sets its value to ‘default’ .
Explicitly Checking for Nullish Value
If you are unable to support a minimum ES11, then you can explicitly check for null and undefined values, for example in an if/else or a ternary, like so:
function isNullish(value) < return null === value || typeof value === 'undefined'; >const foo = null; const bar = undefined; console.log(isNullish(foo) ? 'default' : foo); // 'default' console.log(isNullish(bar) ? 'default' : bar); // 'default'
Hope you found this post useful. It was published 07 Dec, 2021 . Please show your love and support by sharing this post.
null
The null value represents the intentional absence of any object value. It is one of JavaScript’s primitive values and is treated as falsy for boolean operations.
Try it
Syntax
Description
The value null is written with a literal: null . null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.
// foo does not exist. It is not defined and has never been initialized: foo; //ReferenceError: foo is not defined
// foo is known to exist now but it has no type or value: const foo = null; foo; //null
Examples
Difference between null and undefined
When checking for null or undefined , beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion.
typeof null; // "object" (not "null" for legacy reasons) typeof undefined; // "undefined" null === undefined; // false null == undefined; // true null === null; // true null == null; // true !null; // true Number.isNaN(1 + null); // false Number.isNaN(1 + undefined); // true
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Feb 21, 2023 by MDN contributors.
Your blueprint for a better internet.
null
Примитивный тип данных. Состоит из единственного значения null и обозначает отсутствие значения.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Null — это примитивный тип данных, который состоит из единственного значения null .
Значение null используют, когда нужно обозначить намеренное отсутствие значения.
Пример
Скопировать ссылку «Пример» Скопировано
const password = null
const password = null
В списке важных дел по дням недели пользователь решил, что в субботу и воскресенье главного дела нет:
const mainFocusByDays = mon: 'Исправить баг в вёрстке', tue: 'Разобрать почту', wed: 'Написать бота', thu: 'Изучить примитивные типы', fri: 'Отправить резюме в Яндекс', sat: null, sun: null>
const mainFocusByDays = mon: 'Исправить баг в вёрстке', tue: 'Разобрать почту', wed: 'Написать бота', thu: 'Изучить примитивные типы', fri: 'Отправить резюме в Яндекс', sat: null, sun: null >
Как понять
Скопировать ссылку «Как понять» Скопировано
null обозначает понятия «отсутствует», «ничего», «пусто» или «значение неизвестно». Оно всегда явно задаётся программистом, JavaScript автоматически не устанавливает его.
В JavaScript null используется только для обозначения конца цепочки прототипов, чтобы показать, что следующий прототип отсутствует.
В языке существует похожий примитив undefined , он обозначает, что значение ещё не установлено. Их можно легко спутать, потому что оба обозначают отсутствие значения. Разница состоит в том, что null обозначает намеренное отсутствие, а undefined — неявное.
Например, сам JavaScript использует undefined для обозначения не проинициализированных переменных:
let newValue console.log(newValue)// undefined // в явном виде говорим, что значение отсутствуетnewValue = null
let newValue console.log(newValue) // undefined // в явном виде говорим, что значение отсутствует newValue = null
На практике
Скопировать ссылку «На практике» Скопировано
Николай Лопин советует
Скопировать ссылку «Николай Лопин советует» Скопировано
🛠 Оператор typeof некорректно определяет тип у null и возвращает значение ‘object’ по историческим причинам.
console.log(typeof null)// 'object'
console.log(typeof null) // 'object'
🛠 Разделение между undefined и null очень слабое. Это рекомендация, которую не все выполняют. Команды могут договориться о своей трактовке этих значений.
Например, в приложении нужно отобразить список пользователей, полученный с сервера. Пока данных нет, мы рисуем заглушку. В этом случае мы можем трактовать значение undefined как «отправили запрос на сервер, рисуем заглушку и ждём ответа», а null как «сервер ответил, что у него нет данных».
🛠 Уточняйте договорённости по undefined и null на проекте. Часто они не зафиксированы на бумаге, но имеют большое значение.
На собеседовании
Скопировать ссылку «На собеседовании» Скопировано
В чём разница между null , undefined и объявленной переменной без начального значения? ( let foo; )
Скопировать ссылку «В чём разница между null, undefined и объявленной переменной без начального значения? (let foo;)» Скопировано
Скопировать ссылку «Александр Рассудихин отвечает» Скопировано
null обычно задаётся переменной явно и означает, что она ничего не содержит. undefined показывает, что значение переменной «не определено». undefined обычно присваивается переменной, когда она была объявлена, но не было определено её начальное значение. Также, undefined может возвращаться и из функции — это происходит, если функции явно не возвращает ничего другого. null же обычно возвращают из функции явно, чтобы показать, что результат функции равен «ничему».
Без начального значения можно оставлять только переменную объявленную через let или var . Если объявить переменную через const и не задать ей начального значения, будет ошибка: Uncaught SyntaxError : Missing initializer in const declaration .
Оператор typeof для null работает странно. typeof ( null ) выдаст нам строку ‘object’. Это официально признанная ошибка в языке, сохраняемая для совместимости. Ошибка тут в том, что null это отдельный тип данных, а не объект. С undefined всё куда лучше и typeof ( undefined ) выдаст нам ‘undefined’. Почитать ещё о typeof можно здесь.
Поговорим немного о приведении типов. Для начала, пример:
console.log(null + null); // 0console.log(undefined + undefined); // NaN
console.log(null + null); // 0 console.log(undefined + undefined); // NaN
null во время сложения приводится к нулю. Это логично, так как числовым значением «ничего» является как раз 0.
С undefined другое поведении, так как JavaScript пытается привести его к числу, но у него не получается и в результате мы получаем NaN .
Немного упомяну и про оператор нулевого слияния ( ? ? ). В выражении между двумя операндами, он будет возвращать первый операнд, если он не равен null или undefined . Можно сказать, что ? ? приравнивает смысл undefined и null к «ничего не содержит» и в этом случае, кладёт в переменную значение второго операнда.
How to Set Default Value Only in Case of null or undefined in JavaScript?
To set a default value only in case of a nullish value (i.e. undefined or null ), you can do the following:
Using the Nullish Coalescing Operator
If the left-hand side of an expression is nullish value, then you can simply use the nullish coalescing operator ( ?? ) to specify a default value, for example, like so:
// ES11+ console.log(null ?? 'default'); // 'default' console.log(undefined ?? 'default'); // 'default'
You can also combine the nullish coalescing operator ( ?? ) with the optional chaining operator ( ?. ), to return a default value when the optional chaining operator evaluates to undefined . For example:
// ES11+ const obj = < foo: 'bar' >; const value = obj?.nonExistent ?? 'default'; console.log(value); // 'default'
Using the Nullish Assignment Operator
The logical nullish assignment operator ( ??= ) allows you to only assign a value to a variable if it is nullish. For example:
// ES12+ let value; value ??= 'default'; console.log(value); // 'default'
In the example above, since the variable » value » is undefined , the nullish assignment operator sets its value to ‘default’ .
Explicitly Checking for Nullish Value
If you are unable to support a minimum ES11, then you can explicitly check for null and undefined values, for example in an if/else or a ternary, like so:
function isNullish(value) < return null === value || typeof value === 'undefined'; >const foo = null; const bar = undefined; console.log(isNullish(foo) ? 'default' : foo); // 'default' console.log(isNullish(bar) ? 'default' : bar); // 'default'
Hope you found this post useful. It was published 07 Dec, 2021 . Please show your love and support by sharing this post.