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 all values in an object to Null using JavaScript
In this article, you’ll learn how to set all values in an object to null using JavaScript by setting the values directly when iterating over the object or using the Array class’ .reduce() function alongside the Object class’ static Object.keys() function.
Set all values in an object to Null using JavaScript
Iterating over the Object (using .forEach() or for…of loops)
The general idea of the method is by iterating over an Object and setting each value to null . You can do so with either a for. of loop or the Object class’ static function Object.keys() and the Array class’ .forEach() function.
If you want to iterate an object with a for. of loop, you require a combination of the for. of loop and the Object class’ static Object.entries() function.
The for. of loop is specifically used to iterate over any iterable collections (e.g., an Array).
Syntax: for (const value of collection)
The static Object.entries() function takes an object and returns an array containing key-value pairs (i.e., an array containing a key as its 1 st value and a value as its 2 nd value).
Syntax: Object.entries(obj);
With both functions, we have the syntax:
Syntax: for (const Set value null javascript of Object.entries(obj))
const obj = < a: 123, b: "LearnShareIT", c: 325, >; function objToNull(obj) < for (const Set value null javascript of Object.entries(obj)) < objSet value null javascript = null; >> objToNull(obj); console.log(obj);
Another way of doing this is using a combination of the Object class’ static Object.keys() and the Array class’ .forEach() function.
The static Object.keys() function takes an object and returns an array containing all of the Object’s keys.
Syntax: Object.keys(obj);
The .forEach() function, similarly to the for. of loop, iterates over something while still being readable but with the downside of only being able to iterate over arrays. The function takes in a callback function, which is a function that is used as a parameter of another function. The callback function has three parameters, those being: element (the current value), index (the current index), and array (the array getting iterated). However, you will only really need to care about the element parameter for this.
Syntax: Array.prototype.forEach(function (element,index,array) <. >);
Note that since a callback function is generally an anonymous function (i.e., a function without a name), it is generally replaced by ()=><> . So the syntax can be written as:
Syntax: Array.prototype.forEach((element,index,array) => <. >);
The idea of this is to iterate over the Array created by the Object.keys() function then setting the value accessed by the current key to null . For example:
const obj = < a: 123, b: "LearnShareIT", c: 325, >; function objToNull(obj) < const keys = Object.keys(obj); // ["a","b","c"] keys.forEach((key) =>< objSet value null javascript = null; >); > objToNull(obj); console.log(obj);
Using the .reduce() function
The .reduce() function method is a faster, shorter way of doing this but with the downside of being less readable and more difficult to understand.
The Array class’ .reduce() function takes an array and “reduces” it; or more specifically, it takes 2 parameters: A callback function and initialValue . The callback function has 4 parameters: accumulator , element (the current value), index (the current index), and array (the array getting iterated). The accumulator the parameter is the value that was returned after the previous iteration, will default to the initialValue parameter at the beginning.
Syntax: Array.prototype.reduce((acumulator,element,index,array) => <. >, initialValue);
While this is the case, the function can be understood like this:
function reduce(array, callbackFunc, initialValue) < var accumulator = initialValue; // Iterate over the entire Array for (index = 0; index < array.length; index++) < const element = array[index]; // The accumulator becomes the value of the callback function in the current iteration accumulator = callbackFunc(accumulator, element, index); >return accumulator; >
With this in mind, we have:
const obj = < a: 123, b: "LearnShareIT", c: 325, >; function objToNull(obj) < const keys = Object.keys(obj); return keys.reduce((pv, v) =>< return < . pv, [v]: null >; >, <>); > console.log(objToNull(obj));
A thing to note about the code in line 9, the value that is returned is an object containing every key-value pair of the pv or accumulator parameter plus the current iterated value. The code does this by using a Spread Syntax (. ) which, put simply, deconstructs something; and, in this case: Deconstructs an object into key-value pairs.
Summary
To set all values in an Object to null using JavaScript, you can set the values directly when iterating over the Object by using a for. of loop or a combination of Object.keys() and .forEach() or using the .reduce() function alongside the Object.keys() function.
Maybe you are interested:
Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.
Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP