How does the modulus operator handle strings in Javascript

Nik :

I know how modulus works in general, but it is not clear to me how the operator handles strings. Recently, I had to write a script which checks if a name (string) contains an even number of letters. This actually worked, using modulus 2 and checking if result was 1 or 0:

function isNameEven(firstName) {
    if (firstName % 2 === 0) {
        return true;
    }
    else {
        return false;
    }
}

So I'm assuming the letters in the string were counted?

Quentin :

The result is always NaN

const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";

console.log(oneLetter % 2);
console.log(twoLetters % 2);
console.log(threeLetters % 2);

Your function doesn't work if you pass it a string that can't be implicitly converted to a number that isn't NaN.

function isNameEven(firstName) {
  if (firstName % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";

console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));

You could check the length property of the string though.

function isNameEven(firstName) {
  if (firstName.length % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";

console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29694&siteId=1