0

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"]
Aalexander
  • 4,987
  • 3
  • 11
  • 34
Justin Meskan
  • 618
  • 1
  • 9
  • 32

2 Answers2

1

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.

xavc
  • 1,245
  • 1
  • 8
  • 14
1
let str = "Justin"
console.log(str.split``)

is a tagged template, which is equivalent to:

let str = "Justin"
const strings = Object.freeze(Object.assign([""], { raw: [""] }))
console.log(str.split(strings))

This works because String.prototype.split(separator[, limit]) will convert the separator to a string in §21.1.3.21 step 7 if it doesn't implement the Symbol.split method (checked in step 2), and [""].toString() === "".

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153