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

182
Vistas
using charat with if and else in javascript?

Sorry if this was asked before but I am unsure why this code is not working? Is if and else not possible using charat?

let str = new String ('Hello');
if (str.charAt(0) == 'H')
  //console.log('H')
  console.log(str.charAt(0))
else if  (str.charAt(1) == 'e')
  console.log(str.charAt(1))

Thank you,

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

0

According to MDN,

The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.

So once your str.charAt(0) == 'H' is true,JS will console.log H and move on. It will only execute the else if if the first if is false.

let str = new String('Hello');
if (str.charAt(0) == 'b')
  console.log(str.charAt(0))
else if (str.charAt(1) == 'e')
  console.log(str.charAt(1))

You could see by changing the str.charAt(0) == 'H' to a wrong character, it will output e because the first if is wrong and JS will check the else if statement

about 4 years ago · Juan Pablo Isaza Denunciar

0

It is working correct, because when you'll use if then it will check the condition inside the if block. When you'll use else if then it will only be checked if the above if condition didn't satisfies.

If you want to run code in 2 block independently then you should use if instead of else if.

Acc. to your code first if block will run and it will print H i.e, console.log(str.charAt(0))

let str = new String('Hello');
if (str.charAt(0) == 'H')
  //console.log('H')
  console.log(str.charAt(0))
if (str.charAt(1) == 'e')
  console.log(str.charAt(1))

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