0

Here's my JS snippet, which is all part of a VAR call.

                    $showNextMonth,
                    $showNextMonthFunction = new function() {
                        if ($monthsLeft <= 9) {
                            $showNextMonth = '+1'
                        } else {
                            $showNextMonth = '0'
                        }
                    },

As you can see, i'm population $showNextMonth based of the IF condition. While this works, it seems sloppy. How could i use a Return, an then just use $showNextMonthFunction where i need to.

I'm sure this is a dupe, but i couldn't find a fit, so if there is one, please let me know.

3
  • 1
    Remove the new as you're assigning a function to a variable, not creating an instance of a object. Commented Mar 15, 2017 at 12:38
  • Are you sure using strings of numbers is the best way of doing it? Commented Mar 15, 2017 at 12:39
  • I need the string, as the jqueryUI datepicker needs a string when modifing the date range. to change the year range it's like -10:+3. So 10 back, and 3 forward type of thing. Commented Mar 15, 2017 at 12:51

4 Answers 4

1

try this

$showNextMonthFunction = function() {
    return ($monthsLeft <= 9 ? "+1" : "0");
 }();
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I was hitting a wall using return as i kept getting an object.
glad to help :)
What do the trailing parentheses do?
unless you include trailing parentheses, function is consider as an value for the var and will return your whole function as a string. When you hit trailing parentheses, JS will consider it as a function and will return your value from logic inside the function block. Hope this helps :)
Thanks. That's why i switch from using Return. Helps alot!
1

Much simplier :

showNextMonth = monthsLeft <= 9 ? '+1' : '0';

Comments

0

if i understand your question you want something like this:

$showNextMonthFunction = function() {
    return ($monthsLeft <= 9 ? "+1" : "0");
 }

Comments

-1
$showNextMonthFunction = function() {
    if ($monthsLeft <= 9) 
        return '+1';
    return '0';
}

1 Comment

While this answer provides source code, it should also include some narrative to describe the answer.

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.