Michael Hoyt
Michael Hoyt

Reputation: 21

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,

Upvotes: 1

Views: 466

Answers (2)

Uttam
Uttam

Reputation: 776

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))

Upvotes: 1

James
James

Reputation: 2787

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

Upvotes: 2

Related Questions