JavaScript - Why does the increment operator modify immutable strings?












0















In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string.



However, I was playing around in jsconsole and found an exception



string = "string";
string + 37;
=> "string37"
string;
=> "string"


The original string hadn't changed here. Here's what happens when I apply the increment operator on the string. Here I am expecting to see string returned.



string++;
=> NaN
string
=> NaN


I was trying to see whether this would return strinh, like it would in some other languages.



Regardless of whether string++ would work, it shouldn't modify existing string objects. Yet it did just that. Does anyone know why?










share|improve this question



























    0















    In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string.



    However, I was playing around in jsconsole and found an exception



    string = "string";
    string + 37;
    => "string37"
    string;
    => "string"


    The original string hadn't changed here. Here's what happens when I apply the increment operator on the string. Here I am expecting to see string returned.



    string++;
    => NaN
    string
    => NaN


    I was trying to see whether this would return strinh, like it would in some other languages.



    Regardless of whether string++ would work, it shouldn't modify existing string objects. Yet it did just that. Does anyone know why?










    share|improve this question

























      0












      0








      0


      0






      In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string.



      However, I was playing around in jsconsole and found an exception



      string = "string";
      string + 37;
      => "string37"
      string;
      => "string"


      The original string hadn't changed here. Here's what happens when I apply the increment operator on the string. Here I am expecting to see string returned.



      string++;
      => NaN
      string
      => NaN


      I was trying to see whether this would return strinh, like it would in some other languages.



      Regardless of whether string++ would work, it shouldn't modify existing string objects. Yet it did just that. Does anyone know why?










      share|improve this question














      In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string.



      However, I was playing around in jsconsole and found an exception



      string = "string";
      string + 37;
      => "string37"
      string;
      => "string"


      The original string hadn't changed here. Here's what happens when I apply the increment operator on the string. Here I am expecting to see string returned.



      string++;
      => NaN
      string
      => NaN


      I was trying to see whether this would return strinh, like it would in some other languages.



      Regardless of whether string++ would work, it shouldn't modify existing string objects. Yet it did just that. Does anyone know why?







      javascript string immutability nan






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 4 '15 at 18:11









      Richard HamiltonRichard Hamilton

      16.6k63464




      16.6k63464
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Here is a simple example:



          var baz = "string";
          baz = 5;


          Certainly we have not modified the value of the string "string" by assigning baz to 5. Instead, we have simply done away with the string altogether and put the value 5 in its place. Similarly, your example does not alter any strings by assigning your variable to NaN.



          You expect the variable string to be a constant, but it's not. Furthermore, constant variables and immutable values are different things. You haven't changed the immutable string "string" into NaN; you have substituted the immutable value "string" for a completely different value, NaN.



          Your operations create new values by using the immutable string as an operand.



          Consider a real constant variable in an environment that supports the const keyword:



          > const foo = 5;
          > foo++
          5


          Now consider a constant variable that is an object:



          > const bar = {};
          > bar.baz = 5
          > bar
          { baz: 5 }
          > bar = 10;
          > bar
          { baz: 5 }


          In this case, we mutated the value (because the value is not immutable) but could not alter which value the variable contains. Your example does not use constant variables, so the variable string can freely change its value.






          share|improve this answer


























          • This answer is perfectly explained. I will accept this

            – Richard Hamilton
            Jun 4 '15 at 18:31



















          3














          That ++ operator works similarly to:



          string = string + 1;


          So, you are re-assigning to that variable. (while the original string remains immutable)



          If you run string = string + 1 yourself, you'll notice it results in string1. This is because the 1 is being converted into a string and then treated as an "append". (again, never modifying the original string value)



          However, the ++ does not attempt to coerce anything, it simply attempts to add a non-number (ie: string) to a number (1) and the result is NaN.






          share|improve this answer


























          • A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

            – Richard Hamilton
            Jun 4 '15 at 18:23








          • 1





            @user4703663 The string was not modified, but the variable now contains a different value.

            – apsillers
            Jun 4 '15 at 18:25






          • 1





            Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

            – Dominic Barnes
            Jun 4 '15 at 18:25













          • Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

            – Dominic Barnes
            Jun 4 '15 at 18:30











          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%2f30651138%2fjavascript-why-does-the-increment-operator-modify-immutable-strings%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Here is a simple example:



          var baz = "string";
          baz = 5;


          Certainly we have not modified the value of the string "string" by assigning baz to 5. Instead, we have simply done away with the string altogether and put the value 5 in its place. Similarly, your example does not alter any strings by assigning your variable to NaN.



          You expect the variable string to be a constant, but it's not. Furthermore, constant variables and immutable values are different things. You haven't changed the immutable string "string" into NaN; you have substituted the immutable value "string" for a completely different value, NaN.



          Your operations create new values by using the immutable string as an operand.



          Consider a real constant variable in an environment that supports the const keyword:



          > const foo = 5;
          > foo++
          5


          Now consider a constant variable that is an object:



          > const bar = {};
          > bar.baz = 5
          > bar
          { baz: 5 }
          > bar = 10;
          > bar
          { baz: 5 }


          In this case, we mutated the value (because the value is not immutable) but could not alter which value the variable contains. Your example does not use constant variables, so the variable string can freely change its value.






          share|improve this answer


























          • This answer is perfectly explained. I will accept this

            – Richard Hamilton
            Jun 4 '15 at 18:31
















          2














          Here is a simple example:



          var baz = "string";
          baz = 5;


          Certainly we have not modified the value of the string "string" by assigning baz to 5. Instead, we have simply done away with the string altogether and put the value 5 in its place. Similarly, your example does not alter any strings by assigning your variable to NaN.



          You expect the variable string to be a constant, but it's not. Furthermore, constant variables and immutable values are different things. You haven't changed the immutable string "string" into NaN; you have substituted the immutable value "string" for a completely different value, NaN.



          Your operations create new values by using the immutable string as an operand.



          Consider a real constant variable in an environment that supports the const keyword:



          > const foo = 5;
          > foo++
          5


          Now consider a constant variable that is an object:



          > const bar = {};
          > bar.baz = 5
          > bar
          { baz: 5 }
          > bar = 10;
          > bar
          { baz: 5 }


          In this case, we mutated the value (because the value is not immutable) but could not alter which value the variable contains. Your example does not use constant variables, so the variable string can freely change its value.






          share|improve this answer


























          • This answer is perfectly explained. I will accept this

            – Richard Hamilton
            Jun 4 '15 at 18:31














          2












          2








          2







          Here is a simple example:



          var baz = "string";
          baz = 5;


          Certainly we have not modified the value of the string "string" by assigning baz to 5. Instead, we have simply done away with the string altogether and put the value 5 in its place. Similarly, your example does not alter any strings by assigning your variable to NaN.



          You expect the variable string to be a constant, but it's not. Furthermore, constant variables and immutable values are different things. You haven't changed the immutable string "string" into NaN; you have substituted the immutable value "string" for a completely different value, NaN.



          Your operations create new values by using the immutable string as an operand.



          Consider a real constant variable in an environment that supports the const keyword:



          > const foo = 5;
          > foo++
          5


          Now consider a constant variable that is an object:



          > const bar = {};
          > bar.baz = 5
          > bar
          { baz: 5 }
          > bar = 10;
          > bar
          { baz: 5 }


          In this case, we mutated the value (because the value is not immutable) but could not alter which value the variable contains. Your example does not use constant variables, so the variable string can freely change its value.






          share|improve this answer















          Here is a simple example:



          var baz = "string";
          baz = 5;


          Certainly we have not modified the value of the string "string" by assigning baz to 5. Instead, we have simply done away with the string altogether and put the value 5 in its place. Similarly, your example does not alter any strings by assigning your variable to NaN.



          You expect the variable string to be a constant, but it's not. Furthermore, constant variables and immutable values are different things. You haven't changed the immutable string "string" into NaN; you have substituted the immutable value "string" for a completely different value, NaN.



          Your operations create new values by using the immutable string as an operand.



          Consider a real constant variable in an environment that supports the const keyword:



          > const foo = 5;
          > foo++
          5


          Now consider a constant variable that is an object:



          > const bar = {};
          > bar.baz = 5
          > bar
          { baz: 5 }
          > bar = 10;
          > bar
          { baz: 5 }


          In this case, we mutated the value (because the value is not immutable) but could not alter which value the variable contains. Your example does not use constant variables, so the variable string can freely change its value.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 4 '15 at 18:31

























          answered Jun 4 '15 at 18:24









          apsillersapsillers

          83k9163191




          83k9163191













          • This answer is perfectly explained. I will accept this

            – Richard Hamilton
            Jun 4 '15 at 18:31



















          • This answer is perfectly explained. I will accept this

            – Richard Hamilton
            Jun 4 '15 at 18:31

















          This answer is perfectly explained. I will accept this

          – Richard Hamilton
          Jun 4 '15 at 18:31





          This answer is perfectly explained. I will accept this

          – Richard Hamilton
          Jun 4 '15 at 18:31













          3














          That ++ operator works similarly to:



          string = string + 1;


          So, you are re-assigning to that variable. (while the original string remains immutable)



          If you run string = string + 1 yourself, you'll notice it results in string1. This is because the 1 is being converted into a string and then treated as an "append". (again, never modifying the original string value)



          However, the ++ does not attempt to coerce anything, it simply attempts to add a non-number (ie: string) to a number (1) and the result is NaN.






          share|improve this answer


























          • A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

            – Richard Hamilton
            Jun 4 '15 at 18:23








          • 1





            @user4703663 The string was not modified, but the variable now contains a different value.

            – apsillers
            Jun 4 '15 at 18:25






          • 1





            Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

            – Dominic Barnes
            Jun 4 '15 at 18:25













          • Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

            – Dominic Barnes
            Jun 4 '15 at 18:30
















          3














          That ++ operator works similarly to:



          string = string + 1;


          So, you are re-assigning to that variable. (while the original string remains immutable)



          If you run string = string + 1 yourself, you'll notice it results in string1. This is because the 1 is being converted into a string and then treated as an "append". (again, never modifying the original string value)



          However, the ++ does not attempt to coerce anything, it simply attempts to add a non-number (ie: string) to a number (1) and the result is NaN.






          share|improve this answer


























          • A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

            – Richard Hamilton
            Jun 4 '15 at 18:23








          • 1





            @user4703663 The string was not modified, but the variable now contains a different value.

            – apsillers
            Jun 4 '15 at 18:25






          • 1





            Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

            – Dominic Barnes
            Jun 4 '15 at 18:25













          • Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

            – Dominic Barnes
            Jun 4 '15 at 18:30














          3












          3








          3







          That ++ operator works similarly to:



          string = string + 1;


          So, you are re-assigning to that variable. (while the original string remains immutable)



          If you run string = string + 1 yourself, you'll notice it results in string1. This is because the 1 is being converted into a string and then treated as an "append". (again, never modifying the original string value)



          However, the ++ does not attempt to coerce anything, it simply attempts to add a non-number (ie: string) to a number (1) and the result is NaN.






          share|improve this answer















          That ++ operator works similarly to:



          string = string + 1;


          So, you are re-assigning to that variable. (while the original string remains immutable)



          If you run string = string + 1 yourself, you'll notice it results in string1. This is because the 1 is being converted into a string and then treated as an "append". (again, never modifying the original string value)



          However, the ++ does not attempt to coerce anything, it simply attempts to add a non-number (ie: string) to a number (1) and the result is NaN.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 4 '15 at 18:28

























          answered Jun 4 '15 at 18:14









          Dominic BarnesDominic Barnes

          23.9k75582




          23.9k75582













          • A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

            – Richard Hamilton
            Jun 4 '15 at 18:23








          • 1





            @user4703663 The string was not modified, but the variable now contains a different value.

            – apsillers
            Jun 4 '15 at 18:25






          • 1





            Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

            – Dominic Barnes
            Jun 4 '15 at 18:25













          • Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

            – Dominic Barnes
            Jun 4 '15 at 18:30



















          • A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

            – Richard Hamilton
            Jun 4 '15 at 18:23








          • 1





            @user4703663 The string was not modified, but the variable now contains a different value.

            – apsillers
            Jun 4 '15 at 18:25






          • 1





            Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

            – Dominic Barnes
            Jun 4 '15 at 18:25













          • Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

            – Dominic Barnes
            Jun 4 '15 at 18:30

















          A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

          – Richard Hamilton
          Jun 4 '15 at 18:23







          A number added to a string returns a string. In my case, string = string + 1 and string += 1 both return string1. string++ returns NaN. If I call string again, NaN appears. This means the string was modified

          – Richard Hamilton
          Jun 4 '15 at 18:23






          1




          1





          @user4703663 The string was not modified, but the variable now contains a different value.

          – apsillers
          Jun 4 '15 at 18:25





          @user4703663 The string was not modified, but the variable now contains a different value.

          – apsillers
          Jun 4 '15 at 18:25




          1




          1





          Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

          – Dominic Barnes
          Jun 4 '15 at 18:25







          Well, the ++ operator isn't completely identical to that code. string + 1 ends up casting 1 as a string, appending to the original and returning a new value. The ++ doesn't perform that casting, instead it tries to add a non-number to a number, resulting in NaN

          – Dominic Barnes
          Jun 4 '15 at 18:25















          Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

          – Dominic Barnes
          Jun 4 '15 at 18:30





          Regardless, the point is that the string variable simply contains a new value, but the original string value was never mutated.

          – Dominic Barnes
          Jun 4 '15 at 18:30


















          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%2f30651138%2fjavascript-why-does-the-increment-operator-modify-immutable-strings%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

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python