javascriptbooleantruthiness

Is there a way to clarify the true and false statements in this JS?


I've been working on learning JS, and I can't seem to figure out why my boolean values keep coming back either always true or always false.

So I believe I understand the basics of the truthy/falsy situation in JS, but I can't seem to get it right. I know that there are data type issues, (can't make different data types do different things).

function lastCharacter(char1, char2) {
  if (char1[-1] === '' && char2[-1] === '') {
    return true;
  } else {
    return false;
  }
}

console.log(lastCharacter('apple', 'pumpkine'));

Or

function lastCharacter(char1, char2) {
  if (char1[-1] === char2[-1]) {
    return true;
  } else {
    return false;
  }
}

console.log(lastCharacter('apple', 'pumpkina'));

Define a function lastCharacter that accepts two strings as arguments. lastCharacter should return true if both strings end with the same character. Otherwise, lastCharacter should return false.

They either return always true or always false. Can anyone help me?


Solution

  • There are no negative array indexes in JavaScript, instead of char1[-1] you have to use char1[char1.length - 1].

    Accessing one of a strings characters (e.g. "abc[1]) will always have a length of 1, it will never be equal to "". Your second function makes more sense.

    Also

     if(condition) { return true; } else { return false; }
    

    is equal to

     return condition;