Prevent value of 0 evaluating to false when using logical OR












3















I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:



Session['Score'] = 0; 


Later I have an assignment like so:



Score = Session['Score'] || 'not set';


The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:



Score = false || 'not set';


which means Score will evaluate to 'not set' instead of 0!



How can I get around this issue?










share|improve this question

























  • why not use a ternary ? you could use a negative value instead btw.

    – Zohir Salak
    Nov 24 '18 at 22:15
















3















I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:



Session['Score'] = 0; 


Later I have an assignment like so:



Score = Session['Score'] || 'not set';


The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:



Score = false || 'not set';


which means Score will evaluate to 'not set' instead of 0!



How can I get around this issue?










share|improve this question

























  • why not use a ternary ? you could use a negative value instead btw.

    – Zohir Salak
    Nov 24 '18 at 22:15














3












3








3


0






I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:



Session['Score'] = 0; 


Later I have an assignment like so:



Score = Session['Score'] || 'not set';


The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:



Score = false || 'not set';


which means Score will evaluate to 'not set' instead of 0!



How can I get around this issue?










share|improve this question
















I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:



Session['Score'] = 0; 


Later I have an assignment like so:



Score = Session['Score'] || 'not set';


The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:



Score = false || 'not set';


which means Score will evaluate to 'not set' instead of 0!



How can I get around this issue?







javascript boolean logical-operators short-circuiting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 0:26









Ivar

2,851113140




2,851113140










asked Nov 24 '18 at 21:56









JamesJames

315113




315113













  • why not use a ternary ? you could use a negative value instead btw.

    – Zohir Salak
    Nov 24 '18 at 22:15



















  • why not use a ternary ? you could use a negative value instead btw.

    – Zohir Salak
    Nov 24 '18 at 22:15

















why not use a ternary ? you could use a negative value instead btw.

– Zohir Salak
Nov 24 '18 at 22:15





why not use a ternary ? you could use a negative value instead btw.

– Zohir Salak
Nov 24 '18 at 22:15












4 Answers
4






active

oldest

votes


















3














You can do this with destructuring assignment:



let { Score = 'not set' } = Session;


If it's not set:






const Session = { };
let { Score = 'not set' } = Session;
console.log( Score );





If it is set to any value other than undefined, including falsy ones:






const Session = { Score: 0 };
let { Score = 'not set' } = Session;
console.log( Score );








share|improve this answer

































    3














    The cleanest way is probably to set the value and then check if it is falsy but not equal to 0



    let score = Session['Score'];

    if (!score && score !== 0) {
    score = 'not set';
    }


    As mentioned by Patrick Roberts, you could also choose to use the ternary operator in combination with the in operator:



    Score = 'Score' in Session ? Session.Score : 'not set'





    share|improve this answer





















    • 1





      'Score' in Session ? Session.Score : 'not set'?

      – Patrick Roberts
      Nov 24 '18 at 22:13



















    1














    You could be more explicit about your intent by creating a few functions:



    function getScore(s)
    {
    var result = s["Score"];
    if (result == null) {
    result = 0;
    }
    return result;
    }

    function addScore(s, v)
    {
    var result = s["Score"];
    if (result == null) {
    result = 0;
    }
    result += v;
    s["Score"] = result;
    return result;
    }

    var Session = {};
    document.write("Score ");
    document.write(getScore(Session));
    document.write("<p/>");
    addScore(Session, 10);
    document.write("Score ");
    document.write(getScore(Session));


    Expected output:



    Score 0

    Score 10





    share|improve this answer































      0














      Use a string instead:



      Session['Score'] = "0";

      Score = Session['Score'] || 'not set';





      share|improve this answer





















      • 1





        @PatrickRoberts Really? Why? I thought that a string would fix it.

        – Jack Bashford
        Nov 24 '18 at 22:07













      • Really? You posted this as an answer without trying it first to see that it works?

        – Patrick Roberts
        Nov 24 '18 at 22:08











      • I don't have the code, and I don't know the OP's context, so I can't test it.

        – Jack Bashford
        Nov 24 '18 at 22:08











      • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

        – Patrick Roberts
        Nov 24 '18 at 22:10













      • Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

        – Jack Bashford
        Nov 24 '18 at 22:10











      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%2f53462705%2fprevent-value-of-0-evaluating-to-false-when-using-logical-or%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      You can do this with destructuring assignment:



      let { Score = 'not set' } = Session;


      If it's not set:






      const Session = { };
      let { Score = 'not set' } = Session;
      console.log( Score );





      If it is set to any value other than undefined, including falsy ones:






      const Session = { Score: 0 };
      let { Score = 'not set' } = Session;
      console.log( Score );








      share|improve this answer






























        3














        You can do this with destructuring assignment:



        let { Score = 'not set' } = Session;


        If it's not set:






        const Session = { };
        let { Score = 'not set' } = Session;
        console.log( Score );





        If it is set to any value other than undefined, including falsy ones:






        const Session = { Score: 0 };
        let { Score = 'not set' } = Session;
        console.log( Score );








        share|improve this answer




























          3












          3








          3







          You can do this with destructuring assignment:



          let { Score = 'not set' } = Session;


          If it's not set:






          const Session = { };
          let { Score = 'not set' } = Session;
          console.log( Score );





          If it is set to any value other than undefined, including falsy ones:






          const Session = { Score: 0 };
          let { Score = 'not set' } = Session;
          console.log( Score );








          share|improve this answer















          You can do this with destructuring assignment:



          let { Score = 'not set' } = Session;


          If it's not set:






          const Session = { };
          let { Score = 'not set' } = Session;
          console.log( Score );





          If it is set to any value other than undefined, including falsy ones:






          const Session = { Score: 0 };
          let { Score = 'not set' } = Session;
          console.log( Score );








          const Session = { };
          let { Score = 'not set' } = Session;
          console.log( Score );





          const Session = { };
          let { Score = 'not set' } = Session;
          console.log( Score );





          const Session = { Score: 0 };
          let { Score = 'not set' } = Session;
          console.log( Score );





          const Session = { Score: 0 };
          let { Score = 'not set' } = Session;
          console.log( Score );






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 22:34

























          answered Nov 24 '18 at 22:28









          PaulproPaulpro

          114k15225230




          114k15225230

























              3














              The cleanest way is probably to set the value and then check if it is falsy but not equal to 0



              let score = Session['Score'];

              if (!score && score !== 0) {
              score = 'not set';
              }


              As mentioned by Patrick Roberts, you could also choose to use the ternary operator in combination with the in operator:



              Score = 'Score' in Session ? Session.Score : 'not set'





              share|improve this answer





















              • 1





                'Score' in Session ? Session.Score : 'not set'?

                – Patrick Roberts
                Nov 24 '18 at 22:13
















              3














              The cleanest way is probably to set the value and then check if it is falsy but not equal to 0



              let score = Session['Score'];

              if (!score && score !== 0) {
              score = 'not set';
              }


              As mentioned by Patrick Roberts, you could also choose to use the ternary operator in combination with the in operator:



              Score = 'Score' in Session ? Session.Score : 'not set'





              share|improve this answer





















              • 1





                'Score' in Session ? Session.Score : 'not set'?

                – Patrick Roberts
                Nov 24 '18 at 22:13














              3












              3








              3







              The cleanest way is probably to set the value and then check if it is falsy but not equal to 0



              let score = Session['Score'];

              if (!score && score !== 0) {
              score = 'not set';
              }


              As mentioned by Patrick Roberts, you could also choose to use the ternary operator in combination with the in operator:



              Score = 'Score' in Session ? Session.Score : 'not set'





              share|improve this answer















              The cleanest way is probably to set the value and then check if it is falsy but not equal to 0



              let score = Session['Score'];

              if (!score && score !== 0) {
              score = 'not set';
              }


              As mentioned by Patrick Roberts, you could also choose to use the ternary operator in combination with the in operator:



              Score = 'Score' in Session ? Session.Score : 'not set'






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 24 '18 at 22:18

























              answered Nov 24 '18 at 22:12









              IvarIvar

              2,851113140




              2,851113140








              • 1





                'Score' in Session ? Session.Score : 'not set'?

                – Patrick Roberts
                Nov 24 '18 at 22:13














              • 1





                'Score' in Session ? Session.Score : 'not set'?

                – Patrick Roberts
                Nov 24 '18 at 22:13








              1




              1





              'Score' in Session ? Session.Score : 'not set'?

              – Patrick Roberts
              Nov 24 '18 at 22:13





              'Score' in Session ? Session.Score : 'not set'?

              – Patrick Roberts
              Nov 24 '18 at 22:13











              1














              You could be more explicit about your intent by creating a few functions:



              function getScore(s)
              {
              var result = s["Score"];
              if (result == null) {
              result = 0;
              }
              return result;
              }

              function addScore(s, v)
              {
              var result = s["Score"];
              if (result == null) {
              result = 0;
              }
              result += v;
              s["Score"] = result;
              return result;
              }

              var Session = {};
              document.write("Score ");
              document.write(getScore(Session));
              document.write("<p/>");
              addScore(Session, 10);
              document.write("Score ");
              document.write(getScore(Session));


              Expected output:



              Score 0

              Score 10





              share|improve this answer




























                1














                You could be more explicit about your intent by creating a few functions:



                function getScore(s)
                {
                var result = s["Score"];
                if (result == null) {
                result = 0;
                }
                return result;
                }

                function addScore(s, v)
                {
                var result = s["Score"];
                if (result == null) {
                result = 0;
                }
                result += v;
                s["Score"] = result;
                return result;
                }

                var Session = {};
                document.write("Score ");
                document.write(getScore(Session));
                document.write("<p/>");
                addScore(Session, 10);
                document.write("Score ");
                document.write(getScore(Session));


                Expected output:



                Score 0

                Score 10





                share|improve this answer


























                  1












                  1








                  1







                  You could be more explicit about your intent by creating a few functions:



                  function getScore(s)
                  {
                  var result = s["Score"];
                  if (result == null) {
                  result = 0;
                  }
                  return result;
                  }

                  function addScore(s, v)
                  {
                  var result = s["Score"];
                  if (result == null) {
                  result = 0;
                  }
                  result += v;
                  s["Score"] = result;
                  return result;
                  }

                  var Session = {};
                  document.write("Score ");
                  document.write(getScore(Session));
                  document.write("<p/>");
                  addScore(Session, 10);
                  document.write("Score ");
                  document.write(getScore(Session));


                  Expected output:



                  Score 0

                  Score 10





                  share|improve this answer













                  You could be more explicit about your intent by creating a few functions:



                  function getScore(s)
                  {
                  var result = s["Score"];
                  if (result == null) {
                  result = 0;
                  }
                  return result;
                  }

                  function addScore(s, v)
                  {
                  var result = s["Score"];
                  if (result == null) {
                  result = 0;
                  }
                  result += v;
                  s["Score"] = result;
                  return result;
                  }

                  var Session = {};
                  document.write("Score ");
                  document.write(getScore(Session));
                  document.write("<p/>");
                  addScore(Session, 10);
                  document.write("Score ");
                  document.write(getScore(Session));


                  Expected output:



                  Score 0

                  Score 10






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 24 '18 at 22:11









                  Richard HodgesRichard Hodges

                  56.2k658102




                  56.2k658102























                      0














                      Use a string instead:



                      Session['Score'] = "0";

                      Score = Session['Score'] || 'not set';





                      share|improve this answer





















                      • 1





                        @PatrickRoberts Really? Why? I thought that a string would fix it.

                        – Jack Bashford
                        Nov 24 '18 at 22:07













                      • Really? You posted this as an answer without trying it first to see that it works?

                        – Patrick Roberts
                        Nov 24 '18 at 22:08











                      • I don't have the code, and I don't know the OP's context, so I can't test it.

                        – Jack Bashford
                        Nov 24 '18 at 22:08











                      • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                        – Patrick Roberts
                        Nov 24 '18 at 22:10













                      • Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                        – Jack Bashford
                        Nov 24 '18 at 22:10
















                      0














                      Use a string instead:



                      Session['Score'] = "0";

                      Score = Session['Score'] || 'not set';





                      share|improve this answer





















                      • 1





                        @PatrickRoberts Really? Why? I thought that a string would fix it.

                        – Jack Bashford
                        Nov 24 '18 at 22:07













                      • Really? You posted this as an answer without trying it first to see that it works?

                        – Patrick Roberts
                        Nov 24 '18 at 22:08











                      • I don't have the code, and I don't know the OP's context, so I can't test it.

                        – Jack Bashford
                        Nov 24 '18 at 22:08











                      • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                        – Patrick Roberts
                        Nov 24 '18 at 22:10













                      • Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                        – Jack Bashford
                        Nov 24 '18 at 22:10














                      0












                      0








                      0







                      Use a string instead:



                      Session['Score'] = "0";

                      Score = Session['Score'] || 'not set';





                      share|improve this answer















                      Use a string instead:



                      Session['Score'] = "0";

                      Score = Session['Score'] || 'not set';






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 24 '18 at 22:14

























                      answered Nov 24 '18 at 21:57









                      Jack BashfordJack Bashford

                      9,40431540




                      9,40431540








                      • 1





                        @PatrickRoberts Really? Why? I thought that a string would fix it.

                        – Jack Bashford
                        Nov 24 '18 at 22:07













                      • Really? You posted this as an answer without trying it first to see that it works?

                        – Patrick Roberts
                        Nov 24 '18 at 22:08











                      • I don't have the code, and I don't know the OP's context, so I can't test it.

                        – Jack Bashford
                        Nov 24 '18 at 22:08











                      • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                        – Patrick Roberts
                        Nov 24 '18 at 22:10













                      • Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                        – Jack Bashford
                        Nov 24 '18 at 22:10














                      • 1





                        @PatrickRoberts Really? Why? I thought that a string would fix it.

                        – Jack Bashford
                        Nov 24 '18 at 22:07













                      • Really? You posted this as an answer without trying it first to see that it works?

                        – Patrick Roberts
                        Nov 24 '18 at 22:08











                      • I don't have the code, and I don't know the OP's context, so I can't test it.

                        – Jack Bashford
                        Nov 24 '18 at 22:08











                      • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                        – Patrick Roberts
                        Nov 24 '18 at 22:10













                      • Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                        – Jack Bashford
                        Nov 24 '18 at 22:10








                      1




                      1





                      @PatrickRoberts Really? Why? I thought that a string would fix it.

                      – Jack Bashford
                      Nov 24 '18 at 22:07







                      @PatrickRoberts Really? Why? I thought that a string would fix it.

                      – Jack Bashford
                      Nov 24 '18 at 22:07















                      Really? You posted this as an answer without trying it first to see that it works?

                      – Patrick Roberts
                      Nov 24 '18 at 22:08





                      Really? You posted this as an answer without trying it first to see that it works?

                      – Patrick Roberts
                      Nov 24 '18 at 22:08













                      I don't have the code, and I don't know the OP's context, so I can't test it.

                      – Jack Bashford
                      Nov 24 '18 at 22:08





                      I don't have the code, and I don't know the OP's context, so I can't test it.

                      – Jack Bashford
                      Nov 24 '18 at 22:08













                      var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                      – Patrick Roberts
                      Nov 24 '18 at 22:10







                      var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); Seems simple enough to create some context there.

                      – Patrick Roberts
                      Nov 24 '18 at 22:10















                      Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                      – Jack Bashford
                      Nov 24 '18 at 22:10





                      Wait a second. Look at my test web.edusercontent.com/d73ter2hovoc1fki8rqcb6m8dk/index.html

                      – Jack Bashford
                      Nov 24 '18 at 22:10


















                      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%2f53462705%2fprevent-value-of-0-evaluating-to-false-when-using-logical-or%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      Refactoring coordinates for Minecraft Pi buildings written in Python