0

I have an array that looks kind of like this memory[indexGroup][indexItem]. How can I check if that is valid, in other words if it would work when using console.log and getting a value back, not null, undefined or other non values. Empty, 0 and false are valid. These don't give errors.

This is what I ended up with (seems to work) but it's a mess:

function hasMemory() {
    if( typeof memory === 'undefined') return;
    if( typeof memory[indexGroup] === 'undefined') return;
    if( memory[indexGroup] === null ) return;
    if( typeof memory[indexGroup][indexItem] === 'undefined') return;
    if( memory[indexGroup][indexItem] === null) return;
    if( memory[indexGroup][indexItem] !== true ) return;
    return true;
}

Scenarios

  • memory is not set
  • memory[indexGroup] is not set
  • memory[indexGroup][indexItem] is not set

Then it should just return but if the full multidimensional array is valid, it should return true.

Is there a shorter/better/safer ways to check this?

2
  • 1
    function hasMemory(){ return Boolean(memory && memory[indexGroup] && memory[indexGroup][indexItem]) } Commented Jan 27, 2017 at 20:32
  • @Thomas If this works, maybe add it as an answer? :) Commented Jan 27, 2017 at 20:34

2 Answers 2

2
function hasMemory() {
return memory && memory[indexGroup] && memory[indexGroup][indexItem]
}

To handle the case where memory[indexGroup][indexItem] is 0 or false, based on

undefined == null
null == undefined

you can add to condition memory[indexGroup][indexItem]!=null

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

3 Comments

So it checks if these values are... what? Valid values?
This would check if undefined, null, 0 or empty string. So the logic will break down if you need to accept something other than undefined/null
This doesn't handle the case where memory[indexGroup][indexItem] is 0 or false. Also, there's no reason to return true or false. It's functionally equivalent to doing return (true) ? true : false.
1

You can check for both null and undefined simultaneously by performing a loose check against null but will not work for 0 or false.

var u = undefined;
var n = null;
var z = 0;
var f = false;
console.log(u == null);
console.log(n == null);
console.log(z == null);
console.log(f == null);

Using that, here's a shorter way of approaching this:

function hasMemory() {
  return memory &&
         memory[indexGroup] != null &&
         memory[indexGroup][indexItem] != null;
}

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.