Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!