Reputation:
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"));
Upvotes: 0
Views: 71
Reputation: 1166
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'));
Upvotes: 0
Reputation: 1382
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);
}
}
Upvotes: 1