Joshua Joshua - 2 months ago 10
Javascript Question

Javascript - I thought this would change

I'm currently trying to get to grips with passing by reference vs. value, and from what I understand, JS objects are passed by reference.

If that is the case, why does the second console.log statement not produce a capitalised version of the object property?

Any clarification would be great!!!



var string = {
text: 'This is a string inside an object',
};


console.log(string.text);

string.text.toUpperCase();

console.log(string.text);




Answer

The String#toUpperCase method wouldn't update the original string it just returns the capitalized string. So you need to update the property value by the returned value.

var string = {
  text: 'This is a string inside an object',
};


console.log(string.text);

string.text = string.text.toUpperCase();

console.log(string.text);

Comments