Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda