Home > Software design >  Javascript - Why String Mutation doesn't Throw an error?
Javascript - Why String Mutation doesn't Throw an error?

Time:11-11

I'm learning tricky parts of Javascript, and without judging, trying to understand how the language works, but as a developer with Java and Python background(even with Typescript) I'm struggling.

I do understand the string primitives are immutable but why this code doesn't throw an error, doesn't it make the language very error-prone?

const str = "hello";
str[0] = 1;
console.log(str) // "hello"

CodePudding user response:

JavaScript was created to be a companion scripting language to Java with a lower barrier to entry and with the then-fashionable Web Philosophy of "be forgiving of imprecise input" (cf HTML vs. XML).

Indeed the only reason that JavaScript ironically ended-up delivering what Java was promising in the 1990s is that JavaScript's creator has an outsized brain and covertly made a very, very good language (and only about ten people realised this until about 2005).

There are plenty of silent footguns in sloppy mode, which is an artefact of JavaScript's history, and there is nothing anyone can do about this now ("don't break the Web!")

You cannot use the square bracket syntax to modify code units within a string.

Whether the variable is declared with const or let is immaterial here.

In non-strict mode this fails silently (oops!): but no-one uses non-strict mode for production-facing code. ES5 (2009) introduced pragma-based opt-in strict mode that makes this an error.

ES2015 introduced modules, within which all code is strict (although there are a couple of unusual tricks you can do to break out of it in exceptional cases).

(() => { 
    'use strict'; 
    let str = 'hello'; 
    str[0] = 1; 
    console.log('foo'); 
})();

  • Related