Home » JavaScript Tutorial

Booleans in JavaScript

JavaScript Boolean: Here, we are going to learn about the Boolean data type in JavaScript with examples.
Submitted by Siddhant Verma, on October 03, 2019

JavaScript Boolean

Boolean is a data type that stores only two values: true and false.

Alternately, true is represented by 1 and false by 0. However, anything other than false is considered true. This means that if you define your false to be 0 everything other than 0 will be considered true. More accurately, a variable or an object having some value is treated as true and 0, NaN, empty string, undefined, null is treated as false.

Even without explicitly using boolean, we use it unknowingly various times since most conditional statements work on executing a certain piece of code if their condition returns true. If you have ever used while loop, you are indirectly using the booleans.

We declare a boolean as we declare normal variables.

Boolean in JavaScript Example 1

Note: how b and bool both store the value true? But, bool is a boolean and b is not. We need not use ' ' a or " " while defining boolean values otherwise will be considered a string.

We can use the inbuilt Boolean() function to check if something has a true value or a false value. Anything passed as a parameter to the Boolean() function is evaluated for true and false.

Boolean in JavaScript Example 2

You can also evaluate expressions using this method.

Boolean in JavaScript Example 3

You can also use JavaScript's boolean object for wrapping boolean values in an object declared using the "new" keyword.

Boolean in JavaScript Example 4

This boolean object has a constructor property, a toString() method and a valueOf() method. Let's have a brief overview of what they do and how to use them.

    var b=new Boolean("");
    console.log(b);
    console.log(b.constructor);

It returns something ƒ Boolean() { [native code] }. This is nothing but the constructor function for this object.

The toString() method simply returns a string with 'true' or 'false' depending on the type of boolean passed to the object and valueOf() method returns a boolean indicating true or false depending on the value that boolean stores.

Boolean in JavaScript Example 5






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.