You can return a boolean value from a JavaScript function. Create a function and use the if statement to evaluate the given value to the function. And return true or false according to the conditions.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
for conditions statement
if (expression) {
return true;
}
else {
return false;
}
JavaScript function returns a boolean
Simple example code passing the newly defined quarter variable a function with a parameter of ‘n’ that I then divide by 4 to see if it returns 1 for true, or 0 (else) for false.
<!DOCTYPE html>
<html>
<body>
<script>
var quarter = function(n) {
if (n % 4 == 0){
return true;
} else {
return false;
}
};
console.log(quarter(4))
console.log(quarter(1))
</script>
</body>
</html>
Output:
Return a boolean true or false in a JavaScript function
A function that checks if a person is old enough to vote by checking their age. This function is called isOldEnoughToVote(age) and takes an argument age. It checks if the age is greater than or equal to 18. If returns true or false based on that comparison.
function isOldEnoughToVote(age) {
return age >= 18;
}
console.log(isOldEnoughToVote(17)); // false
console.log(isOldEnoughToVote(18)); // true
Or, if you like more Arrow functions
const isOldEnoughToVote = (age) => age >= 18;
// The first => is an arrow function's "Fat Arrow"
// The second >= is an greater-or-equal operator
console.log(isOldEnoughToVote(17)); // false
console.log(isOldEnoughToVote(18)); // true
If you need to return two strings "true"
and "false"
you can do it like:
function isOldEnoughToVote(age) {
if (age < 18) {
return "false";
} else {
return "true";
}
}
console.log(isOldEnoughToVote(17)); // "false"
console.log(isOldEnoughToVote(18)); // "true"
Or by using an Arrow Function and the Ternary operator ?:
const isOldEnoughToVote = (age) => age < 18 ? "false" : "true";
console.log(isOldEnoughToVote(17)); // "false"
console.log(isOldEnoughToVote(18)); // "true"
Source: stackoverflow.com
Comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version