null
and undefined
values in JavaScript. Here he gives an analysis of the current situation, shows some techniques of safe work with null
and undefined
, and also, speaking about the future, considers the operator ?.
.Undefined
is a primitive value that is automatically assigned to declared, but uninitialized variables. This value can be obtained by referring to a non-existent property of the object or to a non-existent argument of the function.Null
is another primitive value, which is the absence of a value. For example, if the variable is assigned the value null
, it can be interpreted as the fact that at this stage of the program’s work this variable exists, but it still has neither type nor value. let obj; console.log(obj.someProp);
TypeError: Cannot read property 'someProp' of undefined
null
value.TypeError
error described above, you can write the following code: let obj; console.log(obj && obj.someProp); // undefined
obj.prop1.prop2.prop3
? In this situation, you can try to solve the problem by performing a lot of checks: console.log( obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2.prop3 );
undefined
or null
is found in such a chain? This is possible, but then you will have to write more code: const evaluation = obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2.prop3; console.log( evaluation != null ? evaluation : "SomeDefaultValue" );
null
and undefined
in javascript, let's talk about how similar values are processed in other languages.Optional
: SomeClass object; Optional.ofNullable(object) .map(obj -> obj.prop1) .map(obj -> obj.prop2) .map(obj -> obj.prop3) .orElse("SomeDefaultValue");
?:
And safe-call ( ?.
). val object: SomeClass? object?.prop1?.prop2?.prop3 ?: "SomeDefaultValue";
?.
), And null-coalescing ( ??
). SomeClass object; object?.prop1?.prop2?.prop3 ?? "SomeDefaultValue";
undefined
in JavaScript and not write code kilometers. So I started experimenting with regular expressions. I wanted to create a function that would allow secure access to the properties of objects. function optionalAccess(obj, path, def) { const propNames = path.replace(/\]|\)/, "").split(/\.|\[|\(/); return propNames.reduce((acc, prop) => acc[prop] || def, obj); } const obj = { items: [{ hello: "Hello" }] }; console.log(optionalAccess(obj, "items[0].hello", "def")); // Hello console.log(optionalAccess(obj, "items[0].he", "def")); // def
lodash._get
method, which has the same signature: _.get(object, path, [defaultValue])
// function optional(obj, evalFunc, def) { // const handler = { // get: function(target, prop, receiver) { const res = Reflect.get(...arguments); // , , - return typeof res === "object" ? proxify(res) : res != null ? res : def; } }; const proxify = target => { return new Proxy(target, handler); }; // return evalFunc(proxify(obj, handler)); } const obj = { items: [{ hello: "Hello" }] }; console.log(optional(obj, target => target.items[0].hello, "def")); // => Hello console.log(optional(obj, target => target.items[0].hell, { a: 1 })); // => { a: 1 }
obj?.arrayProp?[0]?.someProp?.someFunc?.();
null
and undefined
present in programming for a very long time, and nothing indicates that they will disappear soon. Probably, the concept of a null
value is the most unloved in programming, but we have the means to ensure safe operation with similar values. With regard to working with null
and undefined
in JavaScript, you can use several approaches discussed above. In particular, here is the code of the functions proposed by the author of this material. If you are interested in the operator ?.
, which is expected to appear in JS, take a look at one of our previous publications , which addresses this issue.Source: https://habr.com/ru/post/373499/
All Articles