Object destructuring throws error in case of null object is passed
function test ({name= 'empty'}={}) {
console.log(name)
}
test(null);
Uncaught TypeError: Cannot destructure property
name
of 'undefined' or 'null'. at test (:1:15) at :1:1
Object destructuring throws error in case of null object is passed
function test ({name= 'empty'}={}) {
console.log(name)
}
test(null);
Uncaught TypeError: Cannot destructure property
name
of 'undefined' or 'null'. at test (:1:15) at :1:1
See the docs:
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
In other words, the default parameter will not be assigned if null
gets passed:
function fn(arg = 'foo') {
console.log(arg);
}
fn(null);
Destructure in the first line of the function instead:
function test (arg) {
const { name = 'empty' } = arg || {};
console.log(name)
}
test(null);
const { name = 'empty' } = arg || {};
, you can default arg
to {}
in the function params function test (arg = {})
, and then remove the || {}
from the destructuring statement const { name = 'empty' } = arg
; I personally find this easier to read and a bit cleaner. –
Scenario null
is passed (see first snippet). –
Schmit If you don't have any arguments or a value assigned to the object,but want to pass it empty because you plan on assigning it a value at a later stage,Its best to pass it empty by not placing it inside parenthesis.
So lets suppose you have :
This function :
const {signup} = useAuth()
This will definitely throw an error because you are essentially passing the object with no arguments.
To fix this,you would have to remove the empty object from parenthesis as follows:
const signup = useAuth()
then use it in your class or function thereafter as follows:
async {....
await signup(emailRef.current.value, passwordRef.current.value)
...}
function test (user = {}) {
const defaultName= 'Invalid User Object'
if(!user?.name) return defaultName
const {name} = user
return user
}
test(null);
This is what you need:
function doDotsCalculations(el) {
const height = el.height();
const {top = 'empty', left = 'empty'} = el.position() || {};
const res = height + top + 20;
$(".owl-carousel .owl-dots").css({
top: `${res}px`,
left: `${left}px`
});
}
© 2022 - 2024 — McMap. All rights reserved.
undefined
.null
is not the same asundefined
. – Cuneal