jnbdz
jnbdz

Reputation: 4383

How do you test a method in JavaScript without getting a error?

Here is the code:

if(!typeOf(node.parentNode)) return null;

Here is the error:

Uncaught TypeError: Cannot read property 'parentNode' of null

I am trying to test if it is null/undefined/false. But it keeps sending me errors.

How can I test it without getting an error with the if statement?

Upvotes: 0

Views: 65

Answers (4)

Tibos
Tibos

Reputation: 27823

As the other answers mentioned, your particular errors come from the fact that your node object is actually null. The most bullet-proof way of testing if node.parentNode exists and is not null is:

if ((typeof node==='undefined') || !node || !node.parentNode) return null;

This covers the following cases:

  • the node variable doesn't exist
  • the node variable is null or undefined
  • parentNode is falsy (undefined, null, false, 0, NaN, or '')

As per Blue Skies' comments, you should take care about the first check (typeof node === 'undefined') because it masks undeclared variables which may lead to problems later on:

function f() {
  if (typeof node==='undefined') {
     node = {}; // global variable node, usually not what you want
  }
}

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95518

You have to check to see if node is null first.

if(!node || !node.parentNode) {
    return null;
}

This is also known as a "short-circuit" evaluation. When it sees that !node is true, it will immediately execute what is inside the block because the operator is an OR (||) and in an OR if one of the inputs is true, then the result can only be true.

Also, typeof is a keyword; not a function (although your code will still work).

Upvotes: 1

Max
Max

Reputation: 145

try {
        if (!typeOf(node.parentNode)) return null;
    } catch (err) {
        console.log(err);
    }

Upvotes: -1

Pointy
Pointy

Reputation: 413709

Test the object reference too:

if (!node || !node.parentNode) return null;

If "node" can really be anything (like, a string or a number in addition to an object reference), you'd also want to test the type.

Upvotes: 2

Related Questions