Click here to Skip to main content
15,899,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I have the following code, x is initially displayed as an object via typeof(). However, I had assumed objects were passed by reference but the function will not change x. Is this because when it is passed down to the function changestring it is converted to a string data type?

Thanks,

Brian.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var x = new String("This is a string object");
alert(typeof(x));
changestring(x);
alert(x);

function changestring(x)
{
	x = "Altered String";
}
</script>
</head>

<body>
</body>
</html>
Posted

1 solution

When passing a a primitive type variable like a string or a number, the value is passed by value. This means that any changes to that variable in the function are completely separate from anything that happens outside the function.

Clear Explanation: Javascript: Pass by reference[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900