0

I wasn't sure how to properly word the title for this question but jumping right into it,

Using the the ? : operator I setup a JavaScript variable and an if statement like so:

var test = callsAFunction ? test : false;

if I do this, will test equal whatever the function returns here? Or will it be undefined since it's "Technically" not set yet?

What I'm trying to do is set a variable to either what data it gets back and is run through a function, or set it to Boolean false so it will process through my Boolean check as an error. I figured this approach was best but I'm running into issues determining how to go about this. Below are my code snippets:

var hash = self.getHashFromMasterRecords(d[0]);

if(hash === false){
                done("Can't find master record hash", self.requestData, self);
            }

Obviously it needs to turn false as a Boolean in order to pass as an error. I want to do this without having to call the function more than 1 time for this sequence.

So if I do var hash = self.getHashFromMasterRecords(d[0]) ? hash : flase; would hash return the value? Or undefined?

Thank you ahead of time, if I need to post more info let me know.

2
  • 5
    Have you tried it? Anyway var hash = self.getHashFromMasterRecords(d[0]) || false; is probably what you are looking for Commented Dec 15, 2014 at 14:27
  • That's what I was thinking of but couldn't get it past the tip of my tongue. Thank you sir. Commented Dec 15, 2014 at 14:30

2 Answers 2

2

The syntax:

var a = (b) ? c : d;

Will set a equal to c if b is evaluates to something truthy, and d if b evaluates to something falsy. If I understand you correctly, you want to set a variable to the return value of a function, and if that function fails, set it to some default value. To do that, use ||:

var a = b() || 'error occurred!';

In the line above, if b() evaluates to something falsy, a will get the value of error occurred!. If b() evaluates to something truthy, it will get the return value of b().

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

1 Comment

Thank you for the clarification I was thinking along those lines but could not get it fully on of the tip of my tongue.
1

It would be undefined. As long as your function returns a falsey value when it returns you can use the or (||) operator:

var hash = self.getHashFromMasterRecords(d[0]) ?? false;

Although, if that is a concrete example there is little value in the above code as you'd already have a falsey value by just storing the result from the function.

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.