JavaScript: String comparison
Comparison operations work not only with numbers but also with strings. In JavaScript, strings are compared lexicographically: character by character from left to right by the numeric codes of the characters (Unicode).
console.log('apple' < 'banana'); // => true
console.log('cat' > 'dog'); // => false
console.log('abc' === 'abc'); // => true
console.log('hello' !== 'world'); // => trueHere 'apple' < 'banana', because the code of the character a (97) is less than the code of b (98), and it is the first differing character that decides the outcome of the comparison. You can find out the code of a character with the charCodeAt() method:
console.log('a'.charCodeAt(0)); // => 97
console.log('b'.charCodeAt(0)); // => 98The comparison is case-sensitive: the code of 'Z' (90) is less than the code of 'a' (97). Here are a few examples where the first letters are in different cases:
console.log('Zebra' < 'apple'); // => true — 'Z'(90) < 'a'(97)
console.log('apple' < 'Banana'); // => false — 'a'(97) > 'B'(66)
console.log('Apple' < 'apple'); // => true — 'A'(65) < 'a'(97)Let's write a function that checks whether a word starts with a given letter. To do this, we take the first character of the string and compare it with the required letter:
const startsWithLetter = (word, letter) => word[0] === letter;
console.log(startsWithLetter('apple', 'a')); // => true
console.log(startsWithLetter('banana', 'a')); // => falseComparison operations are expressions just like arithmetic ones. You can substitute ready-made values and other expressions into them, for example word[0] above. You can also use the .length property:
console.log('apple'.length > 3); // => true, because the length is 5
console.log('hi'.length > 3); // => false, because the length is 2First 'apple'.length is evaluated (resulting in the number 5), and then this number is compared with 3. That is, the operands of the expression are computed first, and then the comparison is performed.
Useful predicates
Strings in JavaScript have built-in predicate methods. They return true or false and help check various properties of a string:
console.log('hello'.startsWith('he')); // => true — the string starts with 'he'
console.log('hello'.endsWith('lo')); // => true — the string ends with 'lo'
console.log('hello'.includes('ell')); // => true — the string contains 'ell'Such methods let you check strings against the required conditions right in the code, without writing additional functions.
Instructions
During registration on a website, the program checks that the password is long enough — more than 5 characters. Write a function isLongWord() that returns true if the length of the passed word is more than 5 characters, and false otherwise.
Example usage:
isLongWord('apple'); // => false
isLongWord('banana'); // => trueTips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test } from 'vitest';
import f from './index.js';
test('test', () => {
expect(f('apple')).toBe(false);
expect(f('banana')).toBe(true);
expect(f('pineapple')).toBe(true);
});Teacher's solution will be available in:
20:00
