Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

346
Vistas
Why is code giving error if I try to access the array returned by str.split(), immediately in next line

Why does it happen that the below code throws the error Uncaught ReferenceError: Cannot access 'arr' before initialization

function swap(str,a,b){
    let arr = str.split("")
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // throws error "Uncaught ReferenceError: Cannot access 'arr' before initialization"

But as soon as I insert any dummy statement between line 2 and 3, surprisingly code starts to work

function swap(str,a,b){
    let arr = str.split("")
    23456; // this could be anything like a variable declaration, or any valid javascript statement
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // returns "abedc" as expected

I am surprised to see why does this even work now ? It should have given error in both the cases, or should have worked in both cases. I'm sure that in the 1st case, split is not finishing it's work till the time line 3 is executed and in 2nd case, it is getting enough time because of 1 extra statement in between. But I would still love to get a clear explanation as to why it is behaving like this. I'm not sure if this is same for all browsers, but I've tried it on Chrome and Safari on mac, and both of them gave same error.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The semicolon is making the difference. JavaScript thinks you want to access the result of str.split("")[arr[a],arr[b]] like an array. This is why JavaScript autoformatters will insert a semicolon at the beginning of the next line like this:

function swap(str,a,b){
    let arr = str.split("")
    ;[arr[a],arr[b]] = [arr[b],arr[a]]  // <--- semicolon in front of this line
    return arr.join("")
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think your syntax is off a bit split will return an array and trailing it with brackets is translated as if you are trying to access an element of the array I believe you are missing the semi colon only

let arr = str.split("")[arr[a],arr[b]] = [arr[b],arr[a]]

function swap(str,a,b){
    let arr = str.split("");
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}

console.log(swap('some tpyo', 6, 7))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda