Javascript isnullHow do JavaScript closures work?How do I remove a property from a JavaScript object?Encode URL in JavaScript?Which equals operator (== vs ===) should be used in JavaScript comparisons?How can I get query string values in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?

Alignment of various blocks in tikz

How to fry ground beef so it is well-browned

On The Origin of Dissonant Chords

Apply MapThread to all but one variable

Philosophical question on logistic regression: why isn't the optimal threshold value trained?

Why must Chinese maps be obfuscated?

bldc motor, esc and battery draw, nominal vs peak

What makes accurate emulation of old systems a difficult task?

Should the Death Curse affect an undead PC in the Tomb of Annihilation adventure?

Minor Revision with suggestion of an alternative proof by reviewer

What's the polite way to say "I need to urinate"?

Can SQL Server create collisions in system generated constraint names?

A ​Note ​on ​N!

What are the steps to solving this definite integral?

Re-entry to Germany after vacation using blue card

Was there a Viking Exchange as well as a Columbian one?

Aliens crash on Earth and go into stasis to wait for technology to fix their ship

a sore throat vs a strep throat vs strep throat

How to limit Drive Letters Windows assigns to new removable USB drives

How to stop co-workers from teasing me because I know Russian?

How do I check if a string is entirely made of the same substring?

Can I criticise the more senior developers around me for not writing clean code?

Pre-plastic human skin alternative



Javascript isnull


How do JavaScript closures work?How do I remove a property from a JavaScript object?Encode URL in JavaScript?Which equals operator (== vs ===) should be used in JavaScript comparisons?How can I get query string values in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








10















This is a really great function written in jQuery to determine the value of a url field:



$.urlParam = function(name)

// example.com?someparam=name&otherparam=8&id=6
$.urlParam('someparam'); // name
$.urlParam('id'); // 6
$.urlParam('notavar'); // null


http://snipplr.com/view/11583/retrieve-url-params-with-jquery/



I would like to add a condition to test for null, but this looks kind of klunky:



if (results == null) 
return 0;
else


Q: What's the elegant way to accomplish the above if/then statement?










share|improve this question
























  • lol, exact piece of code I was about to ask the exact question on. 3yrs later

    – sMaN
    Jan 17 '13 at 6:00











  • The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

    – user663031
    Sep 28 '14 at 8:07

















10















This is a really great function written in jQuery to determine the value of a url field:



$.urlParam = function(name)

// example.com?someparam=name&otherparam=8&id=6
$.urlParam('someparam'); // name
$.urlParam('id'); // 6
$.urlParam('notavar'); // null


http://snipplr.com/view/11583/retrieve-url-params-with-jquery/



I would like to add a condition to test for null, but this looks kind of klunky:



if (results == null) 
return 0;
else


Q: What's the elegant way to accomplish the above if/then statement?










share|improve this question
























  • lol, exact piece of code I was about to ask the exact question on. 3yrs later

    – sMaN
    Jan 17 '13 at 6:00











  • The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

    – user663031
    Sep 28 '14 at 8:07













10












10








10


1






This is a really great function written in jQuery to determine the value of a url field:



$.urlParam = function(name)

// example.com?someparam=name&otherparam=8&id=6
$.urlParam('someparam'); // name
$.urlParam('id'); // 6
$.urlParam('notavar'); // null


http://snipplr.com/view/11583/retrieve-url-params-with-jquery/



I would like to add a condition to test for null, but this looks kind of klunky:



if (results == null) 
return 0;
else


Q: What's the elegant way to accomplish the above if/then statement?










share|improve this question
















This is a really great function written in jQuery to determine the value of a url field:



$.urlParam = function(name)

// example.com?someparam=name&otherparam=8&id=6
$.urlParam('someparam'); // name
$.urlParam('id'); // 6
$.urlParam('notavar'); // null


http://snipplr.com/view/11583/retrieve-url-params-with-jquery/



I would like to add a condition to test for null, but this looks kind of klunky:



if (results == null) 
return 0;
else


Q: What's the elegant way to accomplish the above if/then statement?







javascript jquery url






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 3 '14 at 16:30









Hannele

5,89043762




5,89043762










asked Dec 14 '09 at 20:58









Phillip SennPhillip Senn

20k73216332




20k73216332












  • lol, exact piece of code I was about to ask the exact question on. 3yrs later

    – sMaN
    Jan 17 '13 at 6:00











  • The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

    – user663031
    Sep 28 '14 at 8:07

















  • lol, exact piece of code I was about to ask the exact question on. 3yrs later

    – sMaN
    Jan 17 '13 at 6:00











  • The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

    – user663031
    Sep 28 '14 at 8:07
















lol, exact piece of code I was about to ask the exact question on. 3yrs later

– sMaN
Jan 17 '13 at 6:00





lol, exact piece of code I was about to ask the exact question on. 3yrs later

– sMaN
Jan 17 '13 at 6:00













The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

– user663031
Sep 28 '14 at 8:07





The test for results[1] would be unnecessary, since if results is non-null, it means the regexp succeeded, which means the first captured group was also found. So all you need is results ? results[1] : 0.

– user663031
Sep 28 '14 at 8:07












12 Answers
12






active

oldest

votes


















22














return results == null ? 0 : (results[1] || 0);





share|improve this answer

























  • @Brad What is (results[1] || 0)? I haven't seen that before.

    – imperium2335
    Nov 1 '13 at 8:03











  • Its the object at index position 1 in 'results' or the value 0.

    – Brad
    Nov 1 '13 at 16:44











  • Brad, try use .test() is best

    – KingRider
    Nov 30 '16 at 18:29


















10














return results == null ? 0 : ( results[1] || 0 );





share|improve this answer

























  • not true: the || deals with the value at results[1]

    – Frunsi
    Dec 14 '09 at 21:02











  • @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

    – just somebody
    Dec 14 '09 at 21:04











  • Well, it looks like you answered first, so you're getting my upvote.

    – Robert Harvey
    Dec 14 '09 at 21:05











  • removing my downvote: I misunderstood.

    – Dan Davies Brackett
    Dec 14 '09 at 21:06











  • On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

    – Rich
    Dec 14 '09 at 21:57


















3














the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.






share|improve this answer























  • I'm getting an error "results is null" in firebug if I return results[1] || 0

    – Phillip Senn
    Dec 14 '09 at 21:07











  • What does && do? Can you explain this line of code please?

    – Phillip Senn
    Dec 14 '09 at 21:10











  • No need for the parens, that's the default precedence, so results && results[1] || 0.

    – user663031
    Sep 28 '14 at 8:00






  • 1





    Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Stephen Kennedy
    Oct 17 '14 at 13:14


















2














You could try this:



if(typeof(results) == "undefined") 
return 0;
else





share|improve this answer
































    1














    return results==null ? 0 : ( results[1] || 0 );





    share|improve this answer























    • You've just rewritten the code provided by the OP to use the ternary operator instead of if.

      – user663031
      Jun 18 '16 at 16:44


















    1














    return (results||0) && results[1] || 0;


    The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.






    share|improve this answer






























      1














      if (typeof(results)!='undefined') 
      return results[1];
      else
      return 0;
      ;


      But you might want to check if results is an array. Arrays are of type Object so you will need this function



      function typeOf(value) 
      var s = typeof value;
      if (s === 'object')
      if (value)
      if (value instanceof Array)
      s = 'array';

      else
      s = 'null';


      return s;



      So your code becomes



      if (typeOf(results)==='array')
      return results[1];

      else

      return 0;






      share|improve this answer
































        1














        All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:



        //function that checks if an object is null
        var isNull = function(obj)
        return obj == null;


        if(isNull(results))
        return 0;
        else 0;



        Using the isNull function helps the code be more readable.






        share|improve this answer
































          1














          I prefer the style



          (results || [, 0]) [1]





          share|improve this answer

























          • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

            – sanders
            Sep 28 '14 at 8:34






          • 1





            It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

            – user663031
            Sep 28 '14 at 8:38











          • I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

            – Dave Scotese
            Jun 18 '16 at 16:39


















          1














          Why not try .test() ? ... Try its and best boolean (true or false):



          $.urlParam = function(name)
          var results = new RegExp('[\?&]' + name + '=([^&#]*)');
          return results.test(window.location.href);



          Tutorial:
          http://www.w3schools.com/jsref/jsref_regexp_test.asp






          share|improve this answer






























            1














            I'm using this function



            function isNull() 
            for (var i = 0; i < arguments.length; i++)
            if (
            typeof arguments[i] !== 'undefined'
            && arguments[i] !== undefined
            && arguments[i] != null
            && arguments[i] != NaN
            && arguments[i]
            ) return arguments[i];




            test



            console.log(isNull(null, null, undefined, 'Target'));





            share|improve this answer






























              0














              You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.



              For example:



              var pass = "";
              if(!pass)
              return false;
              else
              return true;


              This would return false because the string is empty. It would also return false if the variable pass was null.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1903448%2fjavascript-isnull%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                12 Answers
                12






                active

                oldest

                votes








                12 Answers
                12






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                22














                return results == null ? 0 : (results[1] || 0);





                share|improve this answer

























                • @Brad What is (results[1] || 0)? I haven't seen that before.

                  – imperium2335
                  Nov 1 '13 at 8:03











                • Its the object at index position 1 in 'results' or the value 0.

                  – Brad
                  Nov 1 '13 at 16:44











                • Brad, try use .test() is best

                  – KingRider
                  Nov 30 '16 at 18:29















                22














                return results == null ? 0 : (results[1] || 0);





                share|improve this answer

























                • @Brad What is (results[1] || 0)? I haven't seen that before.

                  – imperium2335
                  Nov 1 '13 at 8:03











                • Its the object at index position 1 in 'results' or the value 0.

                  – Brad
                  Nov 1 '13 at 16:44











                • Brad, try use .test() is best

                  – KingRider
                  Nov 30 '16 at 18:29













                22












                22








                22







                return results == null ? 0 : (results[1] || 0);





                share|improve this answer















                return results == null ? 0 : (results[1] || 0);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 27 '11 at 4:17









                Brad

                118k29240399




                118k29240399










                answered Dec 14 '09 at 21:00









                BradBrad

                4,35312553




                4,35312553












                • @Brad What is (results[1] || 0)? I haven't seen that before.

                  – imperium2335
                  Nov 1 '13 at 8:03











                • Its the object at index position 1 in 'results' or the value 0.

                  – Brad
                  Nov 1 '13 at 16:44











                • Brad, try use .test() is best

                  – KingRider
                  Nov 30 '16 at 18:29

















                • @Brad What is (results[1] || 0)? I haven't seen that before.

                  – imperium2335
                  Nov 1 '13 at 8:03











                • Its the object at index position 1 in 'results' or the value 0.

                  – Brad
                  Nov 1 '13 at 16:44











                • Brad, try use .test() is best

                  – KingRider
                  Nov 30 '16 at 18:29
















                @Brad What is (results[1] || 0)? I haven't seen that before.

                – imperium2335
                Nov 1 '13 at 8:03





                @Brad What is (results[1] || 0)? I haven't seen that before.

                – imperium2335
                Nov 1 '13 at 8:03













                Its the object at index position 1 in 'results' or the value 0.

                – Brad
                Nov 1 '13 at 16:44





                Its the object at index position 1 in 'results' or the value 0.

                – Brad
                Nov 1 '13 at 16:44













                Brad, try use .test() is best

                – KingRider
                Nov 30 '16 at 18:29





                Brad, try use .test() is best

                – KingRider
                Nov 30 '16 at 18:29













                10














                return results == null ? 0 : ( results[1] || 0 );





                share|improve this answer

























                • not true: the || deals with the value at results[1]

                  – Frunsi
                  Dec 14 '09 at 21:02











                • @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                  – just somebody
                  Dec 14 '09 at 21:04











                • Well, it looks like you answered first, so you're getting my upvote.

                  – Robert Harvey
                  Dec 14 '09 at 21:05











                • removing my downvote: I misunderstood.

                  – Dan Davies Brackett
                  Dec 14 '09 at 21:06











                • On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                  – Rich
                  Dec 14 '09 at 21:57















                10














                return results == null ? 0 : ( results[1] || 0 );





                share|improve this answer

























                • not true: the || deals with the value at results[1]

                  – Frunsi
                  Dec 14 '09 at 21:02











                • @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                  – just somebody
                  Dec 14 '09 at 21:04











                • Well, it looks like you answered first, so you're getting my upvote.

                  – Robert Harvey
                  Dec 14 '09 at 21:05











                • removing my downvote: I misunderstood.

                  – Dan Davies Brackett
                  Dec 14 '09 at 21:06











                • On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                  – Rich
                  Dec 14 '09 at 21:57













                10












                10








                10







                return results == null ? 0 : ( results[1] || 0 );





                share|improve this answer















                return results == null ? 0 : ( results[1] || 0 );






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 27 '11 at 4:17









                Brad

                118k29240399




                118k29240399










                answered Dec 14 '09 at 21:00









                RichRich

                2,5611317




                2,5611317












                • not true: the || deals with the value at results[1]

                  – Frunsi
                  Dec 14 '09 at 21:02











                • @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                  – just somebody
                  Dec 14 '09 at 21:04











                • Well, it looks like you answered first, so you're getting my upvote.

                  – Robert Harvey
                  Dec 14 '09 at 21:05











                • removing my downvote: I misunderstood.

                  – Dan Davies Brackett
                  Dec 14 '09 at 21:06











                • On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                  – Rich
                  Dec 14 '09 at 21:57

















                • not true: the || deals with the value at results[1]

                  – Frunsi
                  Dec 14 '09 at 21:02











                • @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                  – just somebody
                  Dec 14 '09 at 21:04











                • Well, it looks like you answered first, so you're getting my upvote.

                  – Robert Harvey
                  Dec 14 '09 at 21:05











                • removing my downvote: I misunderstood.

                  – Dan Davies Brackett
                  Dec 14 '09 at 21:06











                • On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                  – Rich
                  Dec 14 '09 at 21:57
















                not true: the || deals with the value at results[1]

                – Frunsi
                Dec 14 '09 at 21:02





                not true: the || deals with the value at results[1]

                – Frunsi
                Dec 14 '09 at 21:02













                @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                – just somebody
                Dec 14 '09 at 21:04





                @DDaviesBrackett: it doesn't: js> results = null; null js> results[1] || 0; typein:2: TypeError: results has no properties

                – just somebody
                Dec 14 '09 at 21:04













                Well, it looks like you answered first, so you're getting my upvote.

                – Robert Harvey
                Dec 14 '09 at 21:05





                Well, it looks like you answered first, so you're getting my upvote.

                – Robert Harvey
                Dec 14 '09 at 21:05













                removing my downvote: I misunderstood.

                – Dan Davies Brackett
                Dec 14 '09 at 21:06





                removing my downvote: I misunderstood.

                – Dan Davies Brackett
                Dec 14 '09 at 21:06













                On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                – Rich
                Dec 14 '09 at 21:57





                On second thoughts, I'm not sure whether the comparison to null is the most readable approach and I think I'd prefer something like return results instanceof Array ? ( results[1] || 0 ) : 0

                – Rich
                Dec 14 '09 at 21:57











                3














                the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.






                share|improve this answer























                • I'm getting an error "results is null" in firebug if I return results[1] || 0

                  – Phillip Senn
                  Dec 14 '09 at 21:07











                • What does && do? Can you explain this line of code please?

                  – Phillip Senn
                  Dec 14 '09 at 21:10











                • No need for the parens, that's the default precedence, so results && results[1] || 0.

                  – user663031
                  Sep 28 '14 at 8:00






                • 1





                  Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                  – Stephen Kennedy
                  Oct 17 '14 at 13:14















                3














                the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.






                share|improve this answer























                • I'm getting an error "results is null" in firebug if I return results[1] || 0

                  – Phillip Senn
                  Dec 14 '09 at 21:07











                • What does && do? Can you explain this line of code please?

                  – Phillip Senn
                  Dec 14 '09 at 21:10











                • No need for the parens, that's the default precedence, so results && results[1] || 0.

                  – user663031
                  Sep 28 '14 at 8:00






                • 1





                  Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                  – Stephen Kennedy
                  Oct 17 '14 at 13:14













                3












                3








                3







                the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.






                share|improve this answer













                the most terse solution would be to change return results[1] || 0; to return (results && results[1]) || 0.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 14 '09 at 21:03









                Dan Davies BrackettDan Davies Brackett

                7,64112749




                7,64112749












                • I'm getting an error "results is null" in firebug if I return results[1] || 0

                  – Phillip Senn
                  Dec 14 '09 at 21:07











                • What does && do? Can you explain this line of code please?

                  – Phillip Senn
                  Dec 14 '09 at 21:10











                • No need for the parens, that's the default precedence, so results && results[1] || 0.

                  – user663031
                  Sep 28 '14 at 8:00






                • 1





                  Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                  – Stephen Kennedy
                  Oct 17 '14 at 13:14

















                • I'm getting an error "results is null" in firebug if I return results[1] || 0

                  – Phillip Senn
                  Dec 14 '09 at 21:07











                • What does && do? Can you explain this line of code please?

                  – Phillip Senn
                  Dec 14 '09 at 21:10











                • No need for the parens, that's the default precedence, so results && results[1] || 0.

                  – user663031
                  Sep 28 '14 at 8:00






                • 1





                  Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                  – Stephen Kennedy
                  Oct 17 '14 at 13:14
















                I'm getting an error "results is null" in firebug if I return results[1] || 0

                – Phillip Senn
                Dec 14 '09 at 21:07





                I'm getting an error "results is null" in firebug if I return results[1] || 0

                – Phillip Senn
                Dec 14 '09 at 21:07













                What does && do? Can you explain this line of code please?

                – Phillip Senn
                Dec 14 '09 at 21:10





                What does && do? Can you explain this line of code please?

                – Phillip Senn
                Dec 14 '09 at 21:10













                No need for the parens, that's the default precedence, so results && results[1] || 0.

                – user663031
                Sep 28 '14 at 8:00





                No need for the parens, that's the default precedence, so results && results[1] || 0.

                – user663031
                Sep 28 '14 at 8:00




                1




                1





                Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                – Stephen Kennedy
                Oct 17 '14 at 13:14





                Too late for Phillip but I'll bite: && is a short circuit "and" operator developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

                – Stephen Kennedy
                Oct 17 '14 at 13:14











                2














                You could try this:



                if(typeof(results) == "undefined") 
                return 0;
                else





                share|improve this answer





























                  2














                  You could try this:



                  if(typeof(results) == "undefined") 
                  return 0;
                  else





                  share|improve this answer



























                    2












                    2








                    2







                    You could try this:



                    if(typeof(results) == "undefined") 
                    return 0;
                    else





                    share|improve this answer















                    You could try this:



                    if(typeof(results) == "undefined") 
                    return 0;
                    else






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 12 '13 at 9:32









                    Richard de Wit

                    3,91643543




                    3,91643543










                    answered Dec 14 '09 at 21:03









                    streetparadestreetparade

                    14k3291119




                    14k3291119





















                        1














                        return results==null ? 0 : ( results[1] || 0 );





                        share|improve this answer























                        • You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                          – user663031
                          Jun 18 '16 at 16:44















                        1














                        return results==null ? 0 : ( results[1] || 0 );





                        share|improve this answer























                        • You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                          – user663031
                          Jun 18 '16 at 16:44













                        1












                        1








                        1







                        return results==null ? 0 : ( results[1] || 0 );





                        share|improve this answer













                        return results==null ? 0 : ( results[1] || 0 );






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 14 '09 at 21:01









                        FrunsiFrunsi

                        6,37253042




                        6,37253042












                        • You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                          – user663031
                          Jun 18 '16 at 16:44

















                        • You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                          – user663031
                          Jun 18 '16 at 16:44
















                        You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                        – user663031
                        Jun 18 '16 at 16:44





                        You've just rewritten the code provided by the OP to use the ternary operator instead of if.

                        – user663031
                        Jun 18 '16 at 16:44











                        1














                        return (results||0) && results[1] || 0;


                        The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.






                        share|improve this answer



























                          1














                          return (results||0) && results[1] || 0;


                          The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.






                          share|improve this answer

























                            1












                            1








                            1







                            return (results||0) && results[1] || 0;


                            The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.






                            share|improve this answer













                            return (results||0) && results[1] || 0;


                            The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 14 '09 at 21:03









                            Teun DTeun D

                            3,99612838




                            3,99612838





















                                1














                                if (typeof(results)!='undefined') 
                                return results[1];
                                else
                                return 0;
                                ;


                                But you might want to check if results is an array. Arrays are of type Object so you will need this function



                                function typeOf(value) 
                                var s = typeof value;
                                if (s === 'object')
                                if (value)
                                if (value instanceof Array)
                                s = 'array';

                                else
                                s = 'null';


                                return s;



                                So your code becomes



                                if (typeOf(results)==='array')
                                return results[1];

                                else

                                return 0;






                                share|improve this answer





























                                  1














                                  if (typeof(results)!='undefined') 
                                  return results[1];
                                  else
                                  return 0;
                                  ;


                                  But you might want to check if results is an array. Arrays are of type Object so you will need this function



                                  function typeOf(value) 
                                  var s = typeof value;
                                  if (s === 'object')
                                  if (value)
                                  if (value instanceof Array)
                                  s = 'array';

                                  else
                                  s = 'null';


                                  return s;



                                  So your code becomes



                                  if (typeOf(results)==='array')
                                  return results[1];

                                  else

                                  return 0;






                                  share|improve this answer



























                                    1












                                    1








                                    1







                                    if (typeof(results)!='undefined') 
                                    return results[1];
                                    else
                                    return 0;
                                    ;


                                    But you might want to check if results is an array. Arrays are of type Object so you will need this function



                                    function typeOf(value) 
                                    var s = typeof value;
                                    if (s === 'object')
                                    if (value)
                                    if (value instanceof Array)
                                    s = 'array';

                                    else
                                    s = 'null';


                                    return s;



                                    So your code becomes



                                    if (typeOf(results)==='array')
                                    return results[1];

                                    else

                                    return 0;






                                    share|improve this answer















                                    if (typeof(results)!='undefined') 
                                    return results[1];
                                    else
                                    return 0;
                                    ;


                                    But you might want to check if results is an array. Arrays are of type Object so you will need this function



                                    function typeOf(value) 
                                    var s = typeof value;
                                    if (s === 'object')
                                    if (value)
                                    if (value instanceof Array)
                                    s = 'array';

                                    else
                                    s = 'null';


                                    return s;



                                    So your code becomes



                                    if (typeOf(results)==='array')
                                    return results[1];

                                    else

                                    return 0;







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Dec 14 '09 at 21:06

























                                    answered Dec 14 '09 at 21:00









                                    pixelinepixeline

                                    15.3k87497




                                    15.3k87497





















                                        1














                                        All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:



                                        //function that checks if an object is null
                                        var isNull = function(obj)
                                        return obj == null;


                                        if(isNull(results))
                                        return 0;
                                        else 0;



                                        Using the isNull function helps the code be more readable.






                                        share|improve this answer





























                                          1














                                          All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:



                                          //function that checks if an object is null
                                          var isNull = function(obj)
                                          return obj == null;


                                          if(isNull(results))
                                          return 0;
                                          else 0;



                                          Using the isNull function helps the code be more readable.






                                          share|improve this answer



























                                            1












                                            1








                                            1







                                            All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:



                                            //function that checks if an object is null
                                            var isNull = function(obj)
                                            return obj == null;


                                            if(isNull(results))
                                            return 0;
                                            else 0;



                                            Using the isNull function helps the code be more readable.






                                            share|improve this answer















                                            All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:



                                            //function that checks if an object is null
                                            var isNull = function(obj)
                                            return obj == null;


                                            if(isNull(results))
                                            return 0;
                                            else 0;



                                            Using the isNull function helps the code be more readable.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Sep 1 '14 at 8:34

























                                            answered Sep 1 '14 at 8:28









                                            Dan OchianaDan Ochiana

                                            2,0811722




                                            2,0811722





















                                                1














                                                I prefer the style



                                                (results || [, 0]) [1]





                                                share|improve this answer

























                                                • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                  – sanders
                                                  Sep 28 '14 at 8:34






                                                • 1





                                                  It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                  – user663031
                                                  Sep 28 '14 at 8:38











                                                • I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                  – Dave Scotese
                                                  Jun 18 '16 at 16:39















                                                1














                                                I prefer the style



                                                (results || [, 0]) [1]





                                                share|improve this answer

























                                                • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                  – sanders
                                                  Sep 28 '14 at 8:34






                                                • 1





                                                  It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                  – user663031
                                                  Sep 28 '14 at 8:38











                                                • I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                  – Dave Scotese
                                                  Jun 18 '16 at 16:39













                                                1












                                                1








                                                1







                                                I prefer the style



                                                (results || [, 0]) [1]





                                                share|improve this answer















                                                I prefer the style



                                                (results || [, 0]) [1]






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jun 18 '16 at 16:43

























                                                answered Sep 28 '14 at 8:07







                                                user663031



















                                                • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                  – sanders
                                                  Sep 28 '14 at 8:34






                                                • 1





                                                  It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                  – user663031
                                                  Sep 28 '14 at 8:38











                                                • I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                  – Dave Scotese
                                                  Jun 18 '16 at 16:39

















                                                • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                  – sanders
                                                  Sep 28 '14 at 8:34






                                                • 1





                                                  It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                  – user663031
                                                  Sep 28 '14 at 8:38











                                                • I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                  – Dave Scotese
                                                  Jun 18 '16 at 16:39
















                                                This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                – sanders
                                                Sep 28 '14 at 8:34





                                                This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

                                                – sanders
                                                Sep 28 '14 at 8:34




                                                1




                                                1





                                                It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                – user663031
                                                Sep 28 '14 at 8:38





                                                It does indeed provide an explicit answer to the question. It is not a critique or request for clarification. In what sense is it not an answer? It is a construct I use all the time to deal with the precise question asked by the OP, which is how to deal concisely with a null result from RegExp#exec.

                                                – user663031
                                                Sep 28 '14 at 8:38













                                                I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                – Dave Scotese
                                                Jun 18 '16 at 16:39





                                                I like this answer best because I can't find a way to misinterpret it AND, importantly, the default answer (0) is specified only once. Many coding errors are introduced when a particular magic number appears in more than one place.

                                                – Dave Scotese
                                                Jun 18 '16 at 16:39











                                                1














                                                Why not try .test() ? ... Try its and best boolean (true or false):



                                                $.urlParam = function(name)
                                                var results = new RegExp('[\?&]' + name + '=([^&#]*)');
                                                return results.test(window.location.href);



                                                Tutorial:
                                                http://www.w3schools.com/jsref/jsref_regexp_test.asp






                                                share|improve this answer



























                                                  1














                                                  Why not try .test() ? ... Try its and best boolean (true or false):



                                                  $.urlParam = function(name)
                                                  var results = new RegExp('[\?&]' + name + '=([^&#]*)');
                                                  return results.test(window.location.href);



                                                  Tutorial:
                                                  http://www.w3schools.com/jsref/jsref_regexp_test.asp






                                                  share|improve this answer

























                                                    1












                                                    1








                                                    1







                                                    Why not try .test() ? ... Try its and best boolean (true or false):



                                                    $.urlParam = function(name)
                                                    var results = new RegExp('[\?&]' + name + '=([^&#]*)');
                                                    return results.test(window.location.href);



                                                    Tutorial:
                                                    http://www.w3schools.com/jsref/jsref_regexp_test.asp






                                                    share|improve this answer













                                                    Why not try .test() ? ... Try its and best boolean (true or false):



                                                    $.urlParam = function(name)
                                                    var results = new RegExp('[\?&]' + name + '=([^&#]*)');
                                                    return results.test(window.location.href);



                                                    Tutorial:
                                                    http://www.w3schools.com/jsref/jsref_regexp_test.asp







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Nov 30 '16 at 18:28









                                                    KingRiderKingRider

                                                    1,2951520




                                                    1,2951520





















                                                        1














                                                        I'm using this function



                                                        function isNull() 
                                                        for (var i = 0; i < arguments.length; i++)
                                                        if (
                                                        typeof arguments[i] !== 'undefined'
                                                        && arguments[i] !== undefined
                                                        && arguments[i] != null
                                                        && arguments[i] != NaN
                                                        && arguments[i]
                                                        ) return arguments[i];




                                                        test



                                                        console.log(isNull(null, null, undefined, 'Target'));





                                                        share|improve this answer



























                                                          1














                                                          I'm using this function



                                                          function isNull() 
                                                          for (var i = 0; i < arguments.length; i++)
                                                          if (
                                                          typeof arguments[i] !== 'undefined'
                                                          && arguments[i] !== undefined
                                                          && arguments[i] != null
                                                          && arguments[i] != NaN
                                                          && arguments[i]
                                                          ) return arguments[i];




                                                          test



                                                          console.log(isNull(null, null, undefined, 'Target'));





                                                          share|improve this answer

























                                                            1












                                                            1








                                                            1







                                                            I'm using this function



                                                            function isNull() 
                                                            for (var i = 0; i < arguments.length; i++)
                                                            if (
                                                            typeof arguments[i] !== 'undefined'
                                                            && arguments[i] !== undefined
                                                            && arguments[i] != null
                                                            && arguments[i] != NaN
                                                            && arguments[i]
                                                            ) return arguments[i];




                                                            test



                                                            console.log(isNull(null, null, undefined, 'Target'));





                                                            share|improve this answer













                                                            I'm using this function



                                                            function isNull() 
                                                            for (var i = 0; i < arguments.length; i++)
                                                            if (
                                                            typeof arguments[i] !== 'undefined'
                                                            && arguments[i] !== undefined
                                                            && arguments[i] != null
                                                            && arguments[i] != NaN
                                                            && arguments[i]
                                                            ) return arguments[i];




                                                            test



                                                            console.log(isNull(null, null, undefined, 'Target'));






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Mar 9 at 9:20









                                                            FatihFatih

                                                            389612




                                                            389612





















                                                                0














                                                                You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.



                                                                For example:



                                                                var pass = "";
                                                                if(!pass)
                                                                return false;
                                                                else
                                                                return true;


                                                                This would return false because the string is empty. It would also return false if the variable pass was null.






                                                                share|improve this answer



























                                                                  0














                                                                  You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.



                                                                  For example:



                                                                  var pass = "";
                                                                  if(!pass)
                                                                  return false;
                                                                  else
                                                                  return true;


                                                                  This would return false because the string is empty. It would also return false if the variable pass was null.






                                                                  share|improve this answer

























                                                                    0












                                                                    0








                                                                    0







                                                                    You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.



                                                                    For example:



                                                                    var pass = "";
                                                                    if(!pass)
                                                                    return false;
                                                                    else
                                                                    return true;


                                                                    This would return false because the string is empty. It would also return false if the variable pass was null.






                                                                    share|improve this answer













                                                                    You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.



                                                                    For example:



                                                                    var pass = "";
                                                                    if(!pass)
                                                                    return false;
                                                                    else
                                                                    return true;


                                                                    This would return false because the string is empty. It would also return false if the variable pass was null.







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Oct 7 '16 at 15:27









                                                                    CarlosCarlos

                                                                    215




                                                                    215



























                                                                        draft saved

                                                                        draft discarded
















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid


                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.

                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function ()
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1903448%2fjavascript-isnull%23new-answer', 'question_page');

                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                                                        Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                                                        Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved