mutation inside a function in javascript

n00b question here:

Suppose you call a function that updates a number or string like this

var x = "well";
var helloify = function(str){
  str += "hello"
};

I'd expect this behavior:

helloify(x);
console.log(x)
\\ "well hello"

But instead I get

\\ "well"

doesn't "+=" change the value of "x"? does this change only persist in the scope of the function but not in the global environment?

thanks!

--confused

Answers:

Answer

When you call helloify(x); you pass the value of x (a string) not a reference to x.

str += "hello" modifies str and leaves x alone.


NB: Objects are only addressed by reference, so if x had been a reference to an object then you would have modified the single object addressed by both variables. Simple strings are not objects though.

Answer

This is because of how parameters are send, because of how strings are handled, and because of what the += operator really does.

Parameters are sent by value, so the function doesn't get the string variable, it gets a copy of the reference to the string object.

Strings are immutable, which means that you will never change a string object1. When you alter a string, that will actually create a new string with the new value.

The str += "hello" is short for str = str + "hello". This means that it will create a new string with the value str + "hello" and put the reference to that string object in the variable str.

As the parameter is not the variable that you sent into the function but a copy, assigning a new string to the parameter won't change the variable that you used in the function call.


1 The Javascript engine might actually change a string object if it knows that the string will never be used any more, i.e. when it can safely do so while keeping the behaviour of immutable strings.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.