ialexander ialexander - 5 months ago 22
Javascript Question

Replacing charAt with join causes strange output

I have a JS example where I am playing with primitive types. I started by trying to understand when Javascript turns a primitive into an object but veered into replacing some prototype functions with others. In my example you can see that I'm replacing the charAt function with Join. I expected that it would simply join the array into a string and return it to me. Instead, it is adding 1's into the output. It would make sense if the 1's would correspond with the array index of each char, if it had them in there at all (a0l1e2r3t4(516)7) but instead it yields: a1l1e1r1t1(111) which I didn't expect. Where are the extra 1s coming from?

String.prototype.getVal= function() {
return this;
}

var a = "alert(1)";
var b = a.getVal();

console.log(a); //"alert(1)"
console.log(typeof a); //"string" (still a primitive)
console.log(b); //"String {0: "a", 1: "l", 2: "e", 3: "r", 4: "t", 5: "(", 6: "1", 7: ")", length: 8, [[PrimitiveValue]]: "alert(1)"}"
console.log(typeof b); //"object"
a.constructor.prototype.charAt = [].join;
console.log("CharAt using Join:", b.charAt(1));//a1l1e1r1t1(111)?

Answer

The JavaScript join method takes one argument, which is the separator. Since you passed in 1, it is joining all the characters of your string alert(1) using that separator.

a + 1
l + 1
e + 1
r + 1
t + 1
( + 1
1 + 1
)

We expect nine total occurrences of 1, which is correct according to your output.

REF: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

For a better visual, call your new charAt using a comma or a space.