close

[Solved] Uncaught TypeError: Cannot destructure property `usrname` of ‘undefined’ or ‘null’

Hello Guys, How are you all? Hope You all Are Fine. Today Object destructuring throws an error in case of null object is passed Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ in Javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ Error Occurs ?

Here is My code.

function testFn({usrname= 'empty'}={}) {
  console.log(usrname);
}


testFn(null);

I am facing the following error.

Uncaught TypeError: Cannot destructure property name of 'undefined' or 'null'. at test (:1:15) at :1:1

How To Solve Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ Error ?

  1. How To Solve Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ Error ?

    To Solve Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ Error Instead of const { usrname = ’empty’ } = arg || {};, you can default arg to {} in the function params function test (arg = {}), and then remove the || {} from the destructuring statement const { usrname = ’empty’ } = arg; I personally find this easier to read and a bit cleaner

  2. Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’

    To Solve Uncaught TypeError: Cannot destructure property usrname of ‘undefined’ or ‘null’ Error Instead of const { usrname = ’empty’ } = arg || {};, you can default arg to {} in the function params function test (arg = {}), and then remove the || {} from the destructuring statement const { usrname = ’empty’ } = arg; I personally find this easier to read and a bit cleaner

Solution 1

Here the default parameter will not be assigned if null gets passed.

function testFn(arg = 'foo') {
  console.log(arg);
}


testFn(null);

Destructure in the first line of the function instead:

function testFn(arg) {
  const { name = 'empty' } = arg || {};
  console.log(name)
}
testFn(null);

Solution 2

Instead of const { usrname = 'empty' } = arg || {};, you can default arg to {} in the function params function test (arg = {}), and then remove the || {} from the destructuring statement const { usrname = 'empty' } = arg; I personally find this easier to read and a bit cleaner

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also Read

Leave a Comment