How to protect code from destructuring a null value in Javascript? [duplicate] - javascript

This question already has answers here:
JS/ES6: Destructuring of undefined
(8 answers)
Avoid an error when destructuring from undefined
(3 answers)
Closed 3 years ago.
I'm a big fan of destructuring and optional chaining proposal in Javascript.
I couldn't help but feel that when destructuring a null or undefined value it'd be really useful if the result would be undefined as it is in optional chaining instead of throwing an error.
For example:
const person = null
console.log(person?.age) // undefined
However:
const person = null
const { age } = person // runtime error
It doesn't work like this of course but is there some Babel proposal to add this feature? Is there some workaround?

It sounds like you might just want to use || {} to destructure an empty object in case person is is null (and happens to also apply if it's otherwise falsey too):
const person = null
const { age } = person || {};
console.log(age);

You can use a default value using ||,
const person = null
const { age } = person || {}
console.log(age)
Short circuiting in JavaScript

Related

Proper way to null check Vue object with "__proto__" and/or "__ob__" property [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 1 year ago.
I would like to know a quick and clean way to check if objects with just __ob__ or __proto__ properties are empty. Now I have to "guess" a value inside my object and null check that instead of the object itself. Example:
const myObject = objectFromDb.innerValue ? objectFromDb : mockObject;
I would love to write this instead:
const myObject = objectFromDb || mockObject;
but it will return objectFromDb even if the values have not yet been retrieved. I'm fine with using a ternary statement instead if the || one, but I'm not happy with having to null-check an inner object. I'm sure there has to be a better way of doing this.
This worked:
Object.keys(objectFromDb).length > 0
(thanks to comment from Bergi)

What does "?." (dot after questiion mark) mean in JS [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I stumbled upon the "?." syntax in another SO question. Something like this -
console.log(x?.y?.z);
What does it do?
This is called Optional Chaining.
It allows to use the property chaining without having to validate properties in each level. It short circuits property evaluation without raising exceptions - thus avoiding the "Cannot read X of undefined" error.
let o = {p: {q: 'foo'}};
try {
console.log('Trying to access the property x');
console.log(o.x.y);
}
catch(e) {
console.log('That was an error');
}
console.log('Trying to access the property x with Optional Chaining');
console.log(o?.x?.y);
Optional chaining more use cases
With function calls
let result = someInterface.customMethod?.();
With expressions
let nestedProp = obj?.['prop' + 'Name'];
With array elements
let arrayItem = arr?.[42];
ECMAScript Draft

What does ?. and ?? operator in javascript do? [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Optional Chaining in JavaScript [duplicate]
(8 answers)
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 3 years ago.
I recently noticed usage like this in a java script code base what does it do. I was unable to find any relevant documentation regarding that. Though intuitively operators seem to checking whether property is present. Is there any official documentation regarding this.
Ex:
args?.propertyName !== 'someValue'
const value = props.someProp ?? props.defaultProp;
They are for optionals:
val ?? other is called nullish coalescing operator and is equivalent to val == null ? other : val
and optionalThing?.property is refered as optional chaining and is the same as optionalThing == null ? null : optionalThing.property
This optional chaining expressions result in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing ( allows you to do things like optionalThing?.optionalProperty?.anotherOptionalProperty?.property ).
The ?. is called the optional chaining operator (TC39 Stage 4), it is used when you are not sure whether a nested property exists or not. If you try to use the . operator to access a property which is undefined you get a TypeError.
For example:
const obj = {foo: {} };
//This is safe, results in undefined
console.log(obj?.foo?.bar?.baz);
//This results in Uncaught TypeError: Cannot read property 'baz' of undefined
console.log(obj.foo.bar.baz);
Where as the ?? is called the null coalescing operator (TC39 Stage 3). When you are using falsy values like an empty string "" or a 0 with a || operator the operand on the right hand side of the || is returned as the falsy value is ignored.
The ?? comes handy when you don't want that and actually you want to consider the falsy values. If the value on the left is a null or undefined only then the value on the right of the ?? is taken:
For example:
const empString = "";
const defaultValue = empString || "A default value";
//Outputs A default value as "" empty string is falsy
console.log(defaultValue);
const actualValue = empString ?? "A default value";
//Does not print the default value as the empString is neither null or undefined
console.log(actualValue);
Same for other falsy values like 0, false, in disagreement with the || operator which will output the 'default string:
console.log(false ?? 'default') //false
console.log(0 ?? 'default') // 0
Only for undefined and null this will output the default value provided in agreement with the || operator:
console.log(undefined ?? 'default') //default
console.log(null ?? 'default') //default

What is the purpose of || in a JavaScript variable? [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
How does javascript logical assignment work?
(6 answers)
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 4 years ago.
I just saw a line of code like this one below and I was intrigued by the use of ||
const myCars = ['BMW','Audi','VW']
const foo = myCars.length || [];
Does this mean if myCars.length was to ever be undefined that foo would equal an empty array instead of undefined?
Yes, how it should be read is:
if 'myCars' doesn't have a length (e.g. no values), the constant foo should be set to [].
Note: https://www.w3schools.com/jsref/jsref_length_array.asp, specifically the return value of the .length: "A Number, representing the number of elements in the array object".
this is Short-circuit evaluation in Javascript. its Unique in JS to USE || operator because other languages use this operator in conditional statements only. please read this
https://en.wikipedia.org/wiki/Short-circuit_evaluation

Is there a reason to not assign a variable in the while block declaration? [duplicate]

This question already has answers here:
Why would you use an assignment in a condition?
(12 answers)
Closed 8 years ago.
Whenever I do something like this...
var obj;
while (obj = doSomething()) {
// something with obj
}
JSHint tells me warning 84| Expected a conditional expression and instead saw an assignment.. However, doing obj = doSomething() returns the value that doSomething() returns during assignment, so it makes sense to write a while loop in this fashion.
Is there a specific reason that JSHint warns me, and more importantly, are there reasons to not do this? Or can I tell JSHint to ignore those lines for that specific warning?
That warning is to make sure that you have not mistyped = instead of == or ===.
Instead, you can get the boolean value of the evaluated result, like this
while (!!(obj = doSomething())) {
The single = assigns value and is not a comparison operator. Use the below:
while (obj == doSomething()) {
// something with obj
}
Refer: http://www.w3schools.com/js/js_comparisons.asp

Categories