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

101
Vistas
JS Assign the value of variable depending on conditional

I don't know why this doesn't work. Any ideas?

   let a = 0
    if (a == 0) {return let a = value0}
    else if (a == 1) {return let a = value1}
    else {return let a = valuex}
    console.log(a)

The console always says 0. What should I do?

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

0

You shouldn't return from if branches, just assign a value to a:

let a = 0
if (a == 0) {a = value0}
else if (a == 1) {a = value1}
else {a = valuex}
console.log(a)
about 4 years ago · Juan Pablo Isaza Denunciar

0

You are declaring a variable every time inside the condition. So variables will be scoped into brackets not outside of that brackets. So the global variable will not change in your case. And remove return. Solution is

let a = 0
if (a == 0) {
   a = value; 
}
else if (a == 1) {
   a = value1;
}
else {
   a = value;
}
console.log(a)
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem here is the scope of 'a'. let allows us to declare variables that are limited to the scope of a block statement,and once the block closes, it's scope ends.

let a = 0
//You don't need to redeclare a by using let
//Also you don't need to return anything since it's not a function
if (a == 0) { a = value0}
else if (a == 1) { a = value1}
else { a = valuex}
console.log(a)
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