JavaScript: Negation
Along with the logical operators AND (&&) and OR (||), the "negation" operation is often used. It flips a boolean value to its opposite. In JavaScript, negation corresponds to the unary operator !:
!true; // false
!false; // trueFor example, if you have a function that checks whether a number is even, you can use negation to check for oddness:
const isEven = (number) => number % 2 === 0;
isEven(10); // true
!isEven(10); // falseWe simply added ! to the left of the function call and got the opposite result. Negation lets you express the intended rules in code without writing new functions.
Double negation
But what if you write !!isEven(10)? Surprisingly, the code works. In logic, double negation is equivalent to no negation at all:
isEven(10); // true
!isEven(10); // false
!!isEven(10); // trueCombining with && and ||
! can be combined with && and ||. Among the logical operators, negation has the highest precedence, so it is applied first:
!true || true; // (!true) || true => false || true => true
!true && false; // (!true) && false => false && false => falseParentheses change the order of evaluation:
!(true || true); // !true => false
!(true && false); // !false => trueA practical example: a function checks whether a driver can get behind the wheel — a license and sobriety are required:
const canDrive = (hasLicense, isDrunk) => hasLicense && !isDrunk;
console.log(canDrive(true, false)); // => true (has a license, sober)
console.log(canDrive(true, true)); // => false (has a license, but drunk)
console.log(canDrive(false, false)); // => false (no license)De Morgan's laws
When working with complex logical expressions, you sometimes need to invert them or rewrite them in an equivalent, more readable form. For this there are De Morgan's laws — two rules that describe how negation distributes over a compound expression:
!(a && b) === !a || !b
!(a || b) === !a && !bThe first law: the negation of a conjunction equals the disjunction of the negations. Let's check:
!(true && false); // !false => true
!true || !false; // false || true => trueThe second law: the negation of a disjunction equals the conjunction of the negations:
!(true || false); // !true => false
!true && !false; // false && true => falseIn practice, De Morgan's laws help simplify conditions. For example, instead of !(isAdmin || isModerator) you can write !isAdmin && !isModerator — which reads as "not an administrator and not a moderator".
Instructions
Write two functions:
isPalindrome(str)— returnstrueif the string is a palindrome (reads the same in both directions).isNotPalindrome(str)— returnstrueif the string is not a palindrome.
isPalindrome('level'); // => true
isPalindrome('hello'); // => false
isNotPalindrome('level'); // => false
isNotPalindrome('hello'); // => trueUse the .split(''), .reverse(), .join('') methods to reverse the string.
Tips
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('wow')).toBe(false);
expect(f('hexlet')).toBe(true);
expect(f('asdffdsa')).toBe(false);
expect(f('Wow')).toBe(false);
});Teacher's solution will be available in:
20:00
