0

If you create a multidimensional-array:

var ThisArray = [];
ThisArray["a"] = [];
ThisArray["a"]["b"] = [];
ThisArray["a"]["b"]["c"] = "This is a string.";

How can you check if ThisArray["a"]["w"]["c"] for example is defined. Right now I'm doing this:

if (typeof ThisArray !== 'undefined') {
    if (typeof ThisArray["a"] !== 'undefined') {
        if (typeof ThisArray["a"]["w"] !== 'undefined') {
            if (typeof ThisArray["a"]["w"]["c"] !== 'undefined') {

                // ThisArray["a"]["w"]["c"] is defined!

            }
        }
    }
}

How can I do this better and cleaner?

1
  • 3
    An array should have number indices, not strings. Did you mean to use an object {}? Commented Apr 7, 2021 at 20:04

4 Answers 4

4

Use optional chaining:

if (typeof ThisArray?.["a"]?.["w"]?.["c"] !== 'undefined') {
   // ThisArray["a"]["w"]["c"] is defined!
}

As noted in the comments, this is a relatively new language feature, and is not supported by older browsers. See Browser Compatibility.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this requires Firefox 74+ or Chrome 80+
This is a great solution, just make sure this meets the browser compatibility requirement for your project: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

You can use optional chaining. the optional chaining operator enables simple way to access values through connected objects when it's possible that a reference or function may be undefined or null, hence, protecting you from getting null exception on null/undefined objects.

var ThisArray = [];
ThisArray["a"] = [];
ThisArray["a"]["b"] = [];
ThisArray["a"]["b"]["c"] = "This is a string.";

console.log(ThisArray.a.b.c?.d?.e);

Comments

0

This is a perfect place to use optional chaining!

You can do so like this:

if (typeof ThisArray.a?.b?.c !== 'undefined') {
  console.log(`ThisArray["a"]["b"]["c"] is defined!`);
}

Here's a full demo:

var ThisArray = [];
ThisArray["a"] = [];
ThisArray["a"]["b"] = [];
ThisArray["a"]["b"]["c"] = "This is a string.";

if (typeof ThisArray.a?.b?.c !== 'undefined') {
  console.log(`ThisArray["a"]["b"]["c"] is defined!`);
  console.log(`ThisArray.a.w.c === "${ThisArray.a.b.c}"`)
} else {
  console.log(`ThisArray["a"]["b"]["c"] is NOT defined!`);
}

Comments

0

go with try catch

var thirdDimensionValue = null;
try{
thirdDimensionValue = ThisArray["a"]["b"]["c"]
}
catch{
thirdDimensionValue = null
}
if(thirdDimensionValue){
console.log("value exist")
}
else{
console.log("No value exist in the property")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.