I just found this really cool way to split a string, but I'm not sure why it works can anyone please explain it to me. .split`` instead of .split("")
let str = "Justin"
console.log(str.split``)
// ["J", "u", "s", "t", "i", "n"]
I just found this really cool way to split a string, but I'm not sure why it works can anyone please explain it to me. .split`` instead of .split("")
let str = "Justin"
console.log(str.split``)
// ["J", "u", "s", "t", "i", "n"]
It's a result of tagged templates, str.split
is treated as a tag of the template (``
), and thus is called with the empty string as its first argument.
is a tagged template, which is equivalent to:
This works because
String.prototype.split(separator[, limit])
will convert theseparator
to a string in ยง21.1.3.21 step 7 if it doesn't implement theSymbol.split
method (checked in step 2), and[""].toString() === ""
.