o7planning

# Dart Boolean Tutorial with Examples

## 1- Boolean

In the Dart programming language, bool is a supported data type, which only includes 2 values, true and false.
bool is also the name of the class representing this data type.
Syntax to declare a variable of bool type:
``````
bool myVariable1 = true;

bool myVariable2 = false;
``````
Example:
bool_ex1.dart
``````
void main() {
bool value;
value = 100 > 25;
print(value); // true
}
``````
Output:
``````
true
``````

## 2- Dart Boolean vs Javascript Boolean

The Dart programming language borrows a lot of ideas from JavaScript, which is why it is so easily converted into JavaScript code. However, the bool data type in Dart and JavaScript has a few differences.
• In JavaScript the values false, 0, "", null, undefined, NaN and Number.Infinite are considered false. Other values are considered true.
• In Dart, only true and false are considered bool, other values cannot be converted to bool.
In JavaScript you can write code like below, which is accepted as valid:
Javascript code
``````
var test = "abc";

if(test) {
console.log("OK! test is true");
} else {
console.log("Ohh no, test is false");
}
``````
Output:
``````
OK! test is true
``````
However, you can't write a similar code in Dart:
Dart code (ERROR!)
``````
void main() {
var test = "abc";

if (test) { // ERROR at compile time.
print("OK! test is true");
} else {
print("Ohh no, test is false");
}
}
``````
You will get an error message from the Dart compiler:
``````
Error compiling to JavaScript:
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:4:7:
Error: A value of type 'String' can't be assigned to a variable of type 'bool'.
if (test) { // ERROR at compile time.
^
Error: Compilation failed.
``````

#### View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.