Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log The Next CEO of Stack OverflowWhat is the naming convention in Python for variable and function names?How to execute a JavaScript function when I have its name as a stringWhat is a practical use for a closure in JavaScript?Javascript by reference vs. by valueWhy aren't ◎ܫ◎ and ☺ valid JavaScript variable names?What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?Is the recommendation to include CSS before JavaScript invalid?variable not writable in inner functionjavascript variable returning NaNFunction returns NaN when it shouldn't

How do I transpose the first and deepest levels of an arbitrarily nested array?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Make solar eclipses exceedingly rare, but still have new moons

Are there any limitations on attacking while grappling?

Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Why do airplanes bank sharply to the right after air-to-air refueling?

Grabbing quick drinks

Is there a difference between "Fahrstuhl" and "Aufzug"

Are there any unintended negative consequences to allowing PCs to gain multiple levels at once in a short milestone-XP game?

How do I reset passwords on multiple websites easily?

Is there a way to save my career from absolute disaster?

If/When UK leaves the EU, can a future goverment conduct a referendum to join the EU?

WOW air has ceased operation, can I get my tickets refunded?

How do I make a variable always equal to the result of some calculations?

If a black hole is created from light, can this black hole then move at speed of light?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

Would a completely good Muggle be able to use a wand?

Should I tutor a student who I know has cheated on their homework?

Which kind of appliances can one connect to electric sockets located in an airplane's toilet?

Does it take more energy to get to Venus or to Mars?

Preparing Indesign booklet with .psd graphics for print

Interfacing a button to MCU (and PC) with 50m long cable

If the heap is zero-initialized for security, then why is the stack merely uninitialized?



Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log



The Next CEO of Stack OverflowWhat is the naming convention in Python for variable and function names?How to execute a JavaScript function when I have its name as a stringWhat is a practical use for a closure in JavaScript?Javascript by reference vs. by valueWhy aren't ◎ܫ◎ and ☺ valid JavaScript variable names?What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?Is the recommendation to include CSS before JavaScript invalid?variable not writable in inner functionjavascript variable returning NaNFunction returns NaN when it shouldn't










7















What's happening here? I get a different result if I declare a variable after console.log in the inner function



I understand that var has a functional scope and inner function can access the variable from their parent






function outer() 
var a = 2;

function inner()
a++;
console.log(a) //log NaN
var a = 8

inner()

outer()








function outer() 
var a = 2;

function inner()
a++;
console.log(a) //log 3
var b = 8

inner()

outer()





The log returns NaN in the first example and log 3 in the second example










share|improve this question




























    7















    What's happening here? I get a different result if I declare a variable after console.log in the inner function



    I understand that var has a functional scope and inner function can access the variable from their parent






    function outer() 
    var a = 2;

    function inner()
    a++;
    console.log(a) //log NaN
    var a = 8

    inner()

    outer()








    function outer() 
    var a = 2;

    function inner()
    a++;
    console.log(a) //log 3
    var b = 8

    inner()

    outer()





    The log returns NaN in the first example and log 3 in the second example










    share|improve this question


























      7












      7








      7


      1






      What's happening here? I get a different result if I declare a variable after console.log in the inner function



      I understand that var has a functional scope and inner function can access the variable from their parent






      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log NaN
      var a = 8

      inner()

      outer()








      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log 3
      var b = 8

      inner()

      outer()





      The log returns NaN in the first example and log 3 in the second example










      share|improve this question
















      What's happening here? I get a different result if I declare a variable after console.log in the inner function



      I understand that var has a functional scope and inner function can access the variable from their parent






      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log NaN
      var a = 8

      inner()

      outer()








      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log 3
      var b = 8

      inner()

      outer()





      The log returns NaN in the first example and log 3 in the second example






      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log NaN
      var a = 8

      inner()

      outer()





      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log NaN
      var a = 8

      inner()

      outer()





      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log 3
      var b = 8

      inner()

      outer()





      function outer() 
      var a = 2;

      function inner()
      a++;
      console.log(a) //log 3
      var b = 8

      inner()

      outer()






      javascript function






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago









      Nick Parsons

      10.3k2926




      10.3k2926










      asked 1 hour ago









      ClaudeClaude

      476




      476






















          3 Answers
          3






          active

          oldest

          votes


















          11














          This is due to hoisting



          The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined



          undefined++ returns NaN, hence your result.



          Your code is equivalent to:



          function outer() 
          var a=2;

          function inner()
          var a;
          a++;
          console.log(a); //log NaN
          a = 8;


          inner();


          outer();


          Rewriting your code in this way makes it easy to see what's going on.






          share|improve this answer
































            3














            Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:






            function outer() 
            var a = 2;

            function inner()
            a++;
            console.log(a);

            inner();

            outer();








            share|improve this answer






























              -2














              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code



              var a=0;
              function outer()
              a=2;
              function inner()
              a=a+1;
              console.log(a)
              a = 8

              inner()

              outer()





              share|improve this answer




















              • 3





                How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                – Shidersz
                1 hour ago











              • They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                – Darshit Shah
                1 hour ago











              • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                – double-beep
                42 mins ago











              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%2f55428371%2fwhy-do-variable-in-an-inner-function-return-nan-when-there-is-the-same-variable%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              11














              This is due to hoisting



              The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined



              undefined++ returns NaN, hence your result.



              Your code is equivalent to:



              function outer() 
              var a=2;

              function inner()
              var a;
              a++;
              console.log(a); //log NaN
              a = 8;


              inner();


              outer();


              Rewriting your code in this way makes it easy to see what's going on.






              share|improve this answer





























                11














                This is due to hoisting



                The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined



                undefined++ returns NaN, hence your result.



                Your code is equivalent to:



                function outer() 
                var a=2;

                function inner()
                var a;
                a++;
                console.log(a); //log NaN
                a = 8;


                inner();


                outer();


                Rewriting your code in this way makes it easy to see what's going on.






                share|improve this answer



























                  11












                  11








                  11







                  This is due to hoisting



                  The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined



                  undefined++ returns NaN, hence your result.



                  Your code is equivalent to:



                  function outer() 
                  var a=2;

                  function inner()
                  var a;
                  a++;
                  console.log(a); //log NaN
                  a = 8;


                  inner();


                  outer();


                  Rewriting your code in this way makes it easy to see what's going on.






                  share|improve this answer















                  This is due to hoisting



                  The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined



                  undefined++ returns NaN, hence your result.



                  Your code is equivalent to:



                  function outer() 
                  var a=2;

                  function inner()
                  var a;
                  a++;
                  console.log(a); //log NaN
                  a = 8;


                  inner();


                  outer();


                  Rewriting your code in this way makes it easy to see what's going on.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 1 hour ago









                  Shidersz

                  9,3362933




                  9,3362933










                  answered 1 hour ago









                  jrojro

                  584115




                  584115























                      3














                      Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:






                      function outer() 
                      var a = 2;

                      function inner()
                      a++;
                      console.log(a);

                      inner();

                      outer();








                      share|improve this answer



























                        3














                        Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:






                        function outer() 
                        var a = 2;

                        function inner()
                        a++;
                        console.log(a);

                        inner();

                        outer();








                        share|improve this answer

























                          3












                          3








                          3







                          Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:






                          function outer() 
                          var a = 2;

                          function inner()
                          a++;
                          console.log(a);

                          inner();

                          outer();








                          share|improve this answer













                          Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:






                          function outer() 
                          var a = 2;

                          function inner()
                          a++;
                          console.log(a);

                          inner();

                          outer();








                          function outer() 
                          var a = 2;

                          function inner()
                          a++;
                          console.log(a);

                          inner();

                          outer();





                          function outer() 
                          var a = 2;

                          function inner()
                          a++;
                          console.log(a);

                          inner();

                          outer();






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 1 hour ago









                          Jack BashfordJack Bashford

                          13.8k31848




                          13.8k31848





















                              -2














                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code



                              var a=0;
                              function outer()
                              a=2;
                              function inner()
                              a=a+1;
                              console.log(a)
                              a = 8

                              inner()

                              outer()





                              share|improve this answer




















                              • 3





                                How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                                – Shidersz
                                1 hour ago











                              • They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                                – Darshit Shah
                                1 hour ago











                              • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                                – double-beep
                                42 mins ago















                              -2














                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code



                              var a=0;
                              function outer()
                              a=2;
                              function inner()
                              a=a+1;
                              console.log(a)
                              a = 8

                              inner()

                              outer()





                              share|improve this answer




















                              • 3





                                How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                                – Shidersz
                                1 hour ago











                              • They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                                – Darshit Shah
                                1 hour ago











                              • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                                – double-beep
                                42 mins ago













                              -2












                              -2








                              -2







                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code



                              var a=0;
                              function outer()
                              a=2;
                              function inner()
                              a=a+1;
                              console.log(a)
                              a = 8

                              inner()

                              outer()





                              share|improve this answer















                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code



                              var a=0;
                              function outer()
                              a=2;
                              function inner()
                              a=a+1;
                              console.log(a)
                              a = 8

                              inner()

                              outer()






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 39 mins ago

























                              answered 1 hour ago









                              Darshit ShahDarshit Shah

                              33




                              33







                              • 3





                                How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                                – Shidersz
                                1 hour ago











                              • They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                                – Darshit Shah
                                1 hour ago











                              • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                                – double-beep
                                42 mins ago












                              • 3





                                How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                                – Shidersz
                                1 hour ago











                              • They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                                – Darshit Shah
                                1 hour ago











                              • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                                – double-beep
                                42 mins ago







                              3




                              3





                              How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                              – Shidersz
                              1 hour ago





                              How does this piece of code explains the issue? Can you provide an explanation of the code you have posted?

                              – Shidersz
                              1 hour ago













                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                              – Darshit Shah
                              1 hour ago





                              They can’t access the inner function value so we have to defined globally. After globally you can use A value anywhere in the code

                              – Darshit Shah
                              1 hour ago













                              While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                              – double-beep
                              42 mins ago





                              While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

                              – double-beep
                              42 mins ago

















                              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%2f55428371%2fwhy-do-variable-in-an-inner-function-return-nan-when-there-is-the-same-variable%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

                              Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

                              Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

                              How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2