Logo

JavaScript: Immutability

What will the last call print?

const name = 'Tirion';
console.log(name.toUpperCase()); // => TIRION
console.log(name); // => ?

The answer to this question depends on how well you understood the lesson about the immutability of primitive data types. Calling the .toUpperCase() method returns a new value with all letters converted to uppercase but doesn't (and can't) change the original string. So the constant (or variable, it doesn't matter here) will contain the original 'Tirion' value. This logic holds true for methods of all primitive types. Moreover, attempting to change the value of a property of this data will lead to nothing:

const name = 'Tirion';
console.log(name.length); // => 6
name.length = 100;
console.log(name.length); // => 6

You can replace the value with a new one instead of changing it. This requires variables:

let name = 'Tirion';
name = name.toUpperCase();
console.log(name); // => TIRION

Instructions

User input data often contains extra spaces at the end or beginning of a string. They are usually cut out with .trim(), for example, ' hello\n ' becomes 'hello'. Update the firstName variable by assigning the same value to it, but using the .trim() method. Print the result.

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!