Comparing values with a boolean type in JavaScript
In the previous example, we used the operator
=== for comparison. In this case, our
variable was compared for equality to true
both by value and by type.
For such a comparison, you can also use the
operator ==. If the variable test
always has one of the values true or
false, then nothing will change:
let test = true; // here we write either true or false
if (test == true) {
console.log('+++');
} else {
console.log('---');
}
But if any values can fall into the variable
test, then everything becomes much
more complicated.
In this case, if the variable test
contains a non-boolean value, then this value
will first be converted to a boolean and only
then will be compared.
Let, for example, the variable test
contain the number 1. In this case,
it is first converted to a boolean type,
that is, to true. And then the
comparison will be done:
let test = 1;
if (test == true) {
console.log('+++'); // it will work
} else {
console.log('---');
}
But, for example, the number 0 is
converted to false. And our condition
will result in 'false':
let test = 0;
if (test == true) {
console.log('+++');
} else {
console.log('---'); // it will work
}
In fact, such a comparison can be explicitly rewritten in the following form:
let test = 1;
if (Boolean(test) == true) {
console.log('+++');
} else {
console.log('---');
}
Remember and write what values when cast
to a boolean type give false.
Without running the code, determine what will be output to the console:
let test = 1;
if (test == true) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test = 0;
if (test == true) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test = 1;
if (test == false) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test = 1;
if (test != true) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test = '';
if (test == false) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test;
if (test == true) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test = 3 * 'a';
if (test == true) {
console.log('+++');
} else {
console.log('---');
}