Are there differences between access using charAt or bracket?

3

As of this another question on the site and its answers, I had a question about how to access the characters of a chain.

On the one hand it is suggested to use charAt (eg cadena.charAt(0) ) to access the character that is in the indicated position, which is correct ... but I have always used the bracket notation (pe cadena[0] ) to access the character of a specific position.

Doing some online research, I have found that bracket access is not supported by older versions of IE (versions that are no longer officially supported, so it would not be a problem), and doing performance tests it seems that access with bracket gets similar (or better) results than charAt for an example such as:

let valor = 100333;
let valorString = valor.toString().charAt(0);
let valorCorchete = (valor.toString())[0];

console.log(valorString);
console.log(valorCorchete);

So, is there any difference between reading a character using charAt or using brackets? Are there cases in which it would be more advisable to use one over the other?

    
asked by Alvaro Montoro 25.04.2018 в 19:27
source

1 answer

4

In ECMAScript 3 there was no option to use brackets to access positions of a string, it was added in version 5 of the standard. Therefore, it was not previously considered safe to use brackets because some browsers did not support it.

Today the use of the sugar syntax brackets is considered, a shortcut to access the positions of a shorter string than using .charAt() . The behavior is almost the same , varying in extreme cases that are not usually given:

let texto='hola';

console.log(texto.charAt(undefined));
console.log(texto[undefined]);

console.log(texto.charAt(NaN));
console.log(texto[NaN]);

console.log(texto.charAt(null));
console.log(texto[null]);

console.log(texto.charAt('a'));
console.log(texto['a']);

I guess that checking that the given position is a readable number (and otherwise assume 0) is what causes charAt () to be slower.

Some purists consider that the correct thing is to use .charAt (position) to avoid confusion with arrays and to avoid the temptation to try to modify a string in that way:

let texto='hola';

console.log(texto[3]);
texto[3]='n'; //no falla, pero no tiene ningún efecto
console.log(texto[3]);

Strings are immutable and, in addition, there is no char in Javascript, so accepting to modify a position in that way would cause many headaches (imagine that something like texto[2]='abc'; had some effect should scare us!)

    
answered by 25.04.2018 / 19:47
source