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:

javascriptlet 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:

javascriptlet 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':

javascriptlet 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:

javascriptlet test = 1;

if (Boolean(test) == true) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 1

Remember and write what values when cast to a boolean type give false.

Задание 2

Without running the code, determine what will be output to the console:

javascriptlet test = 1;
    
if (test == true) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 3

Without running the code, determine what will be output to the console:

javascriptlet test = 0;
    
if (test == true) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 4

Without running the code, determine what will be output to the console:

javascriptlet test = 1;
    
if (test == false) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 5

Without running the code, determine what will be output to the console:

javascriptlet test = 1;
    
if (test != true) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 6

Without running the code, determine what will be output to the console:

javascriptlet test = '';
    
if (test == false) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 7

Without running the code, determine what will be output to the console:

javascriptlet test;
    
if (test == true) {
  console.log('+++');
} else {
  console.log('---');
}
Задание 8

Without running the code, determine what will be output to the console:

javascriptlet test = 3 * 'a';
    
if (test == true) {
  console.log('+++');
} else {
  console.log('---');
}