0

I practice simple js lessons and have problem with this part below Function should return array index 0 instead of letter A but actually returns - undefined And i cant figure it why ?

function parseGuesses(guess) {
    var alphabet = ["A", "B", "C", "D", "E", "F", "G"];
    if (guess === null || guess.length !== 2) {
        alert("Ups proszę podać literę i cyfrę");
    } else { firstChar = guess.charAt(0);
        var row = alphabet.indexOf(firstChar);
    }
}
console.log(parseGuesses("A2"));
2
  • 6
    You don't use the return keyword, so nothing will be returned. Commented Sep 26, 2020 at 13:37
  • 2
    Also firstChar should be declared with var or preferably let. Commented Sep 26, 2020 at 13:38

2 Answers 2

1

As Ivar said the function you wrote isn't returning anything so by default it would return undefine so to change the return value of the function you should write it like so:

function parseGuesses(guess) {
  var alphabet = ["A", "B", "C", "D", "E", "F", "G"];
  if (guess === null || guess.length !== 2) {
    alert("Ups proszę podać literę i cyfrę");
  } else {
    let firstChar = guess.charAt(0); // you should also declare when you create a new variable
    return alphabet.indexOf(firstChar);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

It logs undefined because your function does not return anything.

Your function should have return keyword typically used at last line of the function like this.

function parseGuesses(guess) {

  // operation of something ....

  return something
}

Then logs it to the console

console.log(parseGuesses("A2"))

Modified from you code

 function parseGuesses(guess) {
  var alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
  let firstChar, row;
  if (!guess || guess.length > 2) {
    alert('Ups proszę podać literę i cyfrę');
  } else {
    firstChar = guess.charAt(0);
    row = alphabet.indexOf(firstChar);
  }
  return [firstChar, row]; // return an array after those operation above
}
console.log(parseGuesses('A2'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.