Boolean Value

Course- Javascript >

Data of the Boolean type can have one of only two values, true or false. Boolean variables are most often used to store the result of a logical operation in your code that returns a true/false or yes/no result:

var answer = confirm("Do you want to continue?"); // answer will
contain
true or false                 
                 

When you want to assign a Boolean value of true or false, it’s important to remember NOT to enclose the value in quotes, or the value will be interpreted as a string literal:

var success = false; // correct
var success = "false"; // incorrect                 
                 

If you write code that expects Boolean values in computations, JavaScript automatically converts true to 1 and false to 0.

var answer = confirm("Do you want to continue?"); // answer will contain true or false alert(answer * 1); // will display either 0 or 1

It works the other way, too. JavaScript interprets any nonzero value as true, and zero as false. JavaScript interprets all of the following values as false:

  • Boolean false (you don’t say?)
  • undefined
  • null
  • 0 (zero)
  • NaN
  • “” (empty string)

Try it Yourself: A Simple Spam Detector Function

<!DOCTYPE html>
<html>
<head>
<title>Spam Detector</title>
</head>
<body>
<script>
function detectSpam(input) {
input = input.toLowerCase();
return input.indexOf("fake");
}
var mystring = prompt("Enter a string");
alert(detectSpam(mystring));
</script>
</body>
</html>                 
                 
entering a string spam detector function
output a string spam detector function

The Negation Operator (!)

JavaScript interprets the ! character, when placed before a Boolean variable, as “not,” that is, “the opposite value.” Take a look at this code snippet:

var success = false;
alert(!success); // alerts 'true'