0

What is the least amount of code needed to do the following:

If an object exists and it has a required property and the property is not an empty string then set a variable to the value of the property else set the variable to a default string.

Assuming that the object variable can only be undefined or a valid object, it can never be a function, null, string or anything else. Also if the object has the required property it is a string and never anything else.

A solution to this maybe:

// obj is the object we are testing, prop is the name of the property, def is the default string

var result = def;
if (obj && obj[prop] && obj[prop].length) {
    result = obj[prop];
}

Whether this is completely correct I am unsure.

But is there a shorter way?

Thanks,

AJ

2
  • 2
    This is how I would do it. It's readable and does what you intend. Commented Oct 2, 2014 at 15:27
  • Since this question about looking to optimize working code, i've flagged it for migration to Code Review. Commented Oct 2, 2014 at 15:28

1 Answer 1

2

If you want to shorten it, you can write:

result = (obj && obj[prop]) || def;

An empty string is falsy, so you don't need to check the length explicitly.

result = <val> || <default>;

is a common idiom for setting a variable to a value, with a default if the value is null.

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

1 Comment

I didn't know that an empty string was falsy, that is actually very helpful. Thanks

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.