Matt Blair

Matt Blair

I read that you learn more from a poor example than from a correct one. I don't believe this but that means my site will be a success.

2-Minute Read

I’ve been learning quite a bit about JavaScript in writing algorithms from Cracking the Coding Interview. I learned something new about strings in JavaScript and how they can be accessed. From MDN:

Character access There are two ways to access an individual character in a string. The first is the charAt method:

 return 'cat'.charAt(1); // returns "a"

The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:

 return 'cat'[1]; // returns "a"

Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature. For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.

I highlighted the important part. I know that strings are immutable in JavaScript, but why give me array access if you won’t let me use it? So if you want to use the array accessor with a string, there is a way to do it, but it requires a bit of overhead.

var sentence = "this is a proper JavaScript string.";
sentence = sentence.split(""); //split into array
sentence[18] = 'j'; //changing values to lowercase
sentence[22] = 's';
sentence = sentence.join(""); //make the array a string again

Recent Posts

Categories

About

This theme was developed for Hugo.