Uncaught TypeError: Cannot destructure property `name` of 'undefined' or 'null'
Asked Answered
V

4

34

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

Venitavenite answered 18/2, 2019 at 10:18 Comment(2)
What is your question?Facilitation
default arguments are only assigned when the input parameter is undefined. null is not the same as undefined.Cuneal
S
47

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);
Schmit answered 18/2, 2019 at 10:21 Comment(2)
Instead of 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
The problem is that default arguments do not trigger when null is passed (see first snippet).Schmit
I
1

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)

...}
Israelisraeli answered 7/4, 2021 at 21:29 Comment(0)
B
0
function test (user = {}) {
  const defaultName= 'Invalid User Object'
  if(!user?.name) return defaultName
  const {name} = user
  return user
}
test(null);
Blithesome answered 30/9, 2021 at 18:20 Comment(0)
O
-5

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`
    });
}
Oliviero answered 11/2, 2021 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.