0

I'm trying to use the syntax of:

someVar = otherVar || ''; 
// set someVar to otherVar, or '' if otherVar is false

when I turn otherVar into some array key,

someVar = otherVar[1] || ''; // otherVar[1] is undefined.

i get the error

Cannot read property '1' of undefined

This makes sense since otherVar[1] is undefined...But -

Question: Is the only way to prevent this, to check if otherVar[1] is truthy before setting someVar? Or can I still use this easy method to do set variables quickly like an if else?

I also tried

someVar = (!!otherVar[1]) ? otherVar[1] : ''; // didn't work either.

Thanks!

2 Answers 2

3

You have to first test that otherVar exists so you cannot really do it with that syntax, but you could do this:

someVar = otherVar && otherVar[1] ? otherVar[1] : '';

This works because the and statement fails before the test for the index.

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

1 Comment

Awesome, thanks! Why would checking for the key instead of the whole array not work?
1

I'm assuming this is your case where the variable is declared but undefined. You can use this little trick, cryptic but neat:

var arr; // declared but 'undefined'
var result = (arr || [,'foo'])[1];

console.log(result); //=> "foo"

arr = [1, 2]; // declared and defined
result = (arr || [,'foo'])[1];

console.log(result); //=> 2

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.