javascriptarraysfor-loopif-statementcharat

Looping an array with if and else as well as charAt


I am new to Javascript and I have some experience in C and I cannot figure out what I am doing wrong here. So far Javascript is really confusing and I don't understand it as C is the only programming language I know besides HTML & CSS and I tried these two codes but none of them work.

I am trying to use a for loop and if else statement with charAt. The goal is to look at the first character in an array of names and if the character is a 'j' or 'J' print out "Goodbye" + name and if not print out "Hello" + name. Do I need to convert to ASCII? any insight or recommendations would be great thank you. Here is what I have tried below.

var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];

for (var i = 0; i < names.length; i++) {
  if (names[i].charAt(0) == 'j' || 'J') {
    console.log("Goodbye " + names[i]);
  } else(names[i].charAt(0) !== 'j' || 'J']) {
  console.log("Hello " + names[i]);
}
}

var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];

var myFunc = function(letter) {
  for (var i = 0; i < letter.length; i++) {
    if (letter[i].charAt(0) == 'j' || 'J') {
      console.log("Goodbye " + letter[i]);
    }
    if (letter[i].charAt(0) !== 'j' || 'J') {
      console.log("Hello " + letter[i]);
    }
  }
}
myFunc(names);


Solution


  • The first problem is:
     if(letter[i].charAt(0)=='j' || 'J'){}
    

    When talking about js it is like C in conditionals: 0 for false and anything for true.
    In your code you should put:

    if(letter[i].charAt(0)=='j' || letter[i].charAt(0)=='J'){}
    
    

    Because this is how it is checking if that is the two letters.
    The second is:

    if(letter[i].charAt(0)!='j' || 'J'){}
    

    The same thing happens. And to solve it I advise you to use the symbol && instead of ||:

    if (letter[i].chatAt(0)!='j' && letter[i].charAt(0)!='J'){}
    

    And here I leave you the complete code:

    var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"]; 
    var myFunc = function (letter) { 
    for (var i = 0; i < letter.length; i++) { 
    if (letter[i].charAt(0) == 'j' || letter[i].charAt(0)=='J') { 
    console.log("Goodbye " + names[i]); 
    } 
    if (letter[i].charAt(0) != 'j' && letter[i].charAt(0)!='J') {
    console.log("Hello " + names[i]); }
     } 
     } 
    
    myFunc(names);
    
    

    Instead of treating char to char as you would in C I advise you to use this for loop to iterate over the entire array:

    for(let i in letter){
    if (letter[i].charAt(0)=='J'){}
    }
    

    I assure you that in the long run this will save you more time.