You are on page 1of 2

11/6/2019 Mutable vs Immutable Objects | Interview Cake

Interview Cake

← course home (/table-of-contents)

Mutable vs Immutable
Objects

A mutable object can be changed after it's created, and an immutable object can't.

In Javascript, everything (except for strings) is mutable by default:

JavaScript
const array = [4, 9];

array[0] = 1;
// array is now [1, 9]

Freezing an object makes it immutable, though:

JavaScript
const array = [4, 9];

// Make it immutable

Object.freeze(array);

array[0] = 1;

// array is still [4, 9]

Strings can be mutable or immutable depending on the language.

Strings are immutable in Javascript:

https://www.interviewcake.com/concept/javascript/mutable?course=fc1&section=general-programming 1/2
11/6/2019 Mutable vs Immutable Objects | Interview Cake

JavaScript
const testString = 'mutable?';

testString[7] = '!';
// String is still 'mutable?'

// (but no error is raised!)

But in some other languages, like Swift, strings can be mutable:

Swift
var testString = "mutable?"

if let range = testString.range(of: "?") {

testString.replaceSubrange(range, with: "!")


// testString is now "mutable!"

Mutable objects are nice because you can make changes in-place, without allocating a new
object. But be careful—whenever you make an in-place change to an object, all references to that
object will now re ect the change.

 course home (/table-of-contents)


Next up: Rectangular Love  (/question/rectangular-love?
course=fc1&section=general-programming)

Want more coding interview help?

Check out interviewcake.com for more advice, guides, and practice questions.

https://www.interviewcake.com/concept/javascript/mutable?course=fc1&section=general-programming 2/2

You might also like