JavaScript Booleans

The boolean (not Boolean) is a primitive data type in JavaScript. It can have only two values: true or false. It is useful in controlling program flow using conditional statements like if else , switch , while loop , etc.

The followings are boolean variables.

The following example demonstrates how a boolean value controls the program flow using the if condition .

The comparison expressions return boolean values to indicate whether the comparison is true or false. For example, the following expressions return boolean values.

Boolean Function

JavaScript provides the Boolean() function that converts other types to a boolean type. The value specified as the first parameter will be converted to a boolean value. The Boolean() will return true for any non-empty, non-zero, object, or array.

If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty string), or no parameter passed then the Boolean() function returns false .

The new operator with the Boolean() function returns a Boolean object.

Any boolean object, when passed in a conditional statement, will evaluate to true .

Boolean vs boolean

The new Boolean() will return a Boolean object, whereas it returns a boolean without the new keyword. The boolean (lower case) is the primitive type, whereas Boolean (upper case) is an object in JavaScript. Use the typeof operator to check the types.

Boolean Methods

Primitive or Boolean object includes following methods.

Method Description
toLocaleString() Returns string of boolean value in local browser environment.

toString() Returns a string of Boolean.

valueOf() Returns the value of the Boolean object.

javascript boolean type assignment

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • JavaScript Minifier
  • JSON Formatter
  • XML Formatter

JavaScript Booleans Explained – How to use Booleans in JavaScript

JavaScript Booleans Explained – How to use Booleans in JavaScript

Booleans are a primitive datatype commonly used in computer programming languages. By definition, a boolean has two possible values: true or false .

In JavaScript, there is often implicit type coercion to boolean. If for example you have an if statement which checks a certain expression, that expression will be coerced to a boolean:

There are only a few values that will be coerced to false:

  • false (not really coerced as it already is false)
  • "" (empty string)

All other values will be coerced to true. When a value is coerced to a boolean, we also call that either ‘falsy’ or ‘truthy’.

One way that type coercion is used is with the use of the or ( || ) and and ( && ) operators:

As you can see, the or operator checks the first operand. If this is true or truthy, it returns it immediately (which is why we get ‘word’ in the first case & true in the second case). If it is not true or truthy, it returns the second operand (which is why we get ‘word’ in the third case).

With the and operator it works in a similar way, but for ‘and’ to be true, both operands need to be truthy. So it will always return the second operand if both are true/truthy, otherwise it will return false. That is why in the fourth case we get true and in the last case we get ‘word’.

The Boolean Object

There is also a native JavaScript object that wraps around a value. The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted, 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string “false”, create an object with an initial value of true.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

More Details

Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. If true, this will execute the function. For example, the condition in the following if statement evaluates to true:

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:

If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true.

Do not use a Boolean object in place of a Boolean primitive.

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

The boolean primitive is a logical data type with only two values: true and false .

Boolean object

All values in JavaScript are implicitly true or false . The Boolean object can be used to coerce a value to a true or false boolean, based on the implicit true or false state of that value:

Values that result in false include 0 , null , undefined , NaN , an empty string ( "" ), an omitted value, and a false boolean. All other values result in true .

Avoid using the Boolean object as a constructor. It creates an object containing a boolean value, not the boolean primitive you might expect:

Because all objects are inherently truthy , the resulting boolean object always loosely evaluates to true, even if it contains a false value:

Check your understanding

Which of the following returns false ?

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-03-31 UTC.

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript typeof Operator

JavaScript null and undefined

JavaScript Type Conversion

JavaScript Comparison and Logical Operators

  • JavaScript Number.isInteger()

JavaScript Booleans

In JavaScript, booleans are the primitive data types that can either be true or false . For example,

Note : If you wrap true or false in a quote, then they are considered as a string.

For example,

The boolean values are mostly used for Comparison and Logical Operators . For example,

Equal to operator == returns true if the operands are equal.

Not equal to operator != returns true if all the operands are not equal.

Logical AND && returns true if both the operand values are true , else evaluates to false .

The boolean values are used in if...else statements and for loops as well.

Here's a list of values that gets converted to specific boolean values.

Data type Boolean Value
false
null false
NaN false
'' false
false
true
true
true

JavaScript Boolean Methods

Here is a list of built-in boolean methods in JavaScript.

Method Description
returns a boolean value by converting boolean to a string
returns the primitive value of a boolean

Example: Using toString()

Example: Using valueOf()

JavaScript Boolean() Function

The Boolean() function is used to convert various data types to boolean values. For example,

Everything with a value returns true . For example,

In JavaScript, undefined , null , 0 , NaN , '' converts to false . For example,

Note : If you want to learn more about the boolean conversion, visit JavaScript Type Conversion .

  • Boolean Objects

You can also create a boolean value using the new keyword. For example,

Note : It is recommended to avoid using boolean objects. Using boolean objects slows down the program.

Table of Contents

  • Introduction
  • Boolean Methods
  • Boolean() Function

Video: JavaScript Boolean

Sorry about that.

Related Tutorials

JavaScript Tutorial

EXPLORE OUR

javascript boolean type assignment

Mastering Booleans in JavaScript: Logical Operations Guide

Two Women Looking at the Code at Laptop

ARTICLE SUMMARY

They play a crucial role in decision-making and control flow within programming. Understanding how to work with Booleans and perform logical operations is essential for writing efficient and reliable JavaScript code . In this article, we’re exploring the concept of Booleans, their syntax, and various logical operations that can be performed with them.

UNDERSTANDING BOOLEANS IN JAVASCRIPT:

In JavaScript, a Boolean value can be either true or false. These values represent the two possible states of logical truth. Booleans are commonly used in conditional statements, loops, and comparisons to control the flow of execution based on certain conditions.

DECLARING AND ASSIGNING BOOLEAN VALUES:

To declare and assign a Boolean variable, you can use the following syntax:

let isTrue = true; let isFalse = false;

Here, the variables isTrue and isFalse are assigned the Boolean values true and false, respectively.

COMPARISON OPERATORS AND BOOLEAN RESULTS:

JavaScript provides several comparison operators that return Boolean values when used to compare two values. These operators include:

  • Equality (==): Checks if two values are equal and returns true if they are, false otherwise.
  • Inequality (!=): Checks if two values are not equal and returns true if they are not, false otherwise.
  • Strict Equality (===): Checks if two values are equal in both value and data type and returns true if they are, false otherwise.
  • Strict Inequality (!==): Checks if two values are not equal in either value or data type and returns true if they are not, false otherwise.
  • Greater Than (>): Checks if the value on the left is greater than the value on the right and returns true if it is, false otherwise.
  • Less Than (<): Checks if the value on the left is less than the value on the right and returns true if it is, false otherwise.
  • Greater Than or Equal To (>=): Checks if the value on the left is greater than or equal to the value on the right and returns true if it is, false otherwise.
  • Less Than or Equal To (<=): Checks if the value on the left is less than or equal to the value on the right and returns true if it is, false otherwise.

LOGICAL OPERATORS AND BOOLEAN OPERATIONS:

JavaScript provides logical operators that allow you to perform logical operations on Boolean values or expressions. The three main logical operators are:

  • Logical AND (&&): Returns true if both operands are true, and false otherwise.
  • Logical OR (||): Returns true if at least one of the operands is true, and false if both operands are false.
  • Logical NOT (!): Negates the Boolean value of an operand. If the operand is true, it returns false, and if the operand is false, it returns true.

These logical operators can be used to combine Boolean values, create complex conditions, and make decisions based on multiple criteria.

EXAMPLE USAGE:

Booleans in JavaScript

Booleans are a fundamental concept in JavaScript and serve as the building blocks for decision-making and logical operations in programming. By understanding the syntax of Booleans and utilizing logical operators effectively, you can create robust and flexible JavaScript code . Practice using Booleans in various scenarios to master their implementation and take full advantage of their power in your JavaScript project s.

Women's Financial Wellbeing Power Hack (900 × 600 px)

Power Hack: Empowering Women’s Financial Wellbeing

IWD 2024 Power Hack (900 × 600 px)(1)

Celebrate Women’s Day with SheCanCode’s Power Hack

Person Using Macbook Pro, with a book on Python coding

NumPy Cheat Sheet for Python

javascript boolean type assignment

RELATED ARTICLES

Asian Woman Programmer Typing Source Codes Programming

Explore Our Site

Discover new content, join our community.

javascript boolean type assignment

Nick McCullum Headshot

Nick McCullum

Software Developer & Professional Explainer

How to Write Boolean Variables in JavaScript

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

Along with strings and numbers, booleans are one of the most important data types in JavaScript.

This lesson will teach you how to write boolean variables in JavaScript.

What is a Boolean Value in JavaScript

A boolean variable is used to identify whether a condition is true or false.

Accordingly, boolean values can only assume two values:

Here is an example of how to create a boolean variable with a value of true :

Similarly, here is an example of how to create a boolean variable with a value of false :

Notice how I used the let keyword when creating these two variables, and not my normal default const keyword.

This is because JavaScript boolean variables are generally intended to be modified over the course of a program.

Said differently, boolean variables are designed to be toggled to change the functionality of your applications.

We will learn how to do this in our next lesson, when we learn about how to write if statements in JavaScript.

For now, let's move on to learning how to calculate boolean values in JavaScript instead of manually assigning them with the true or false keywords.

How to Calculate Boolean Values in JavaScript

It is possible to calculate Boolean values in JavaScript using comparison operators , which output true or false depending on whether some mathematical condition is met.

Here are the major comparison operators in JavaScript:

  • < : less than
  • > : greater than
  • <= : less than or equal to
  • >= : greater than or equal to

Here are a few examples of how you can use comparison operators to generate true or false values in JavaScript:

We can also test equality in JavaScript. There are two ways to do this: using the == operator and using the === operator. Here are two examples:

You are probably wondering what the difference is between the == and === equality operators.

The === operator checks for equality between both value and type . The == operator only checks for the equality of value.

Here is an example so you can see this concept in action:

In practice, you should almost always use the === operator when calculating equality in JavaScript applications.

Final Thoughts

In this lesson, you learned how to write boolean values in JavaScript.

Here is a summary of the topics we covered:

  • The two values that can be assigned to a boolean variable
  • Comparison operators in JavaScript
  • The two JavaScript operators available for testing equality

Home » JavaScript Tutorial » JavaScript Boolean

JavaScript Boolean

Summary : in this tutorial, you will learn about the JavaScript Boolean object and the differences between the Boolean object and the  boolean primitive type.

JavaScript boolean primitive type

JavaScript provides a boolean primitive type that has two values of true and false . The following example declares two variables that hold boolean values of false and true :

When you apply the   typeof operator to a variable that holds a primitive boolean value, you get the boolean as the following example:

JavaScript Boolean object

In addition to the boolean primitive type, JavaScript also provides you with the global Boolean()  function, with the letter B in uppercase, to cast a value of another type to boolean.

The following example shows how to use the Boolean() function to convert a string into a boolean value. Because the string is not empty, it returns true .

The Boolean is also a wrapper object of the boolean primitive type. It means that when you pass either true or false to the Boolean constructor, it’ll create a Boolean object. For example:

To get the primitive value back, you call the valueOf() method of the Boolean object as follows:

However, if you call the toString() method of a Boolean object, you get a string value  "true" or "false" . For example:

JavaScript boolean vs. Boolean

Consider this example:

First, active is an object so you can add a property to it:

However, you cannot do it with the primitive boolean variable like the completed variable:

Second, the typeof of Boolean object returns object , whereas the  typeof of a primitive boolean value returns boolean .

Third, when applying the   instanceof operator to a Boolean object, it returns true . However, it returns false if you apply the   instanceof  operator to a boolean value.

It is a good practice never to use the Boolean object because it will create much confusion, especially when using in an expression. For example:

How the script works.

  • First, create falseObj as a Boolean object wrapper for the false value.
  • Second, use falseObj in the   if statement. Because falseObj is an object, and JavaScript engine coerces it to a boolean value of true . As a result, the statement inside the if block is executed.

The following table summarizes the differences between JavaScript Boolean and boolean :

OperatorbooleanBoolean
  booleanobject
  Booleanfalsetrue

It is recommended that you use the Boolean() function to convert a value of a different type to a Boolean type, but you should never use the Boolean as a wrapper object of a primitive boolean value.

In this tutorial, you have learned about the JavaScript Boolean object and the differences between the Boolean object and boolean primitive type.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Boolean() constructor

The Boolean() constructor creates Boolean objects. When called as a function, it returns primitive values of type Boolean.

Note: Boolean() can be called with or without new , but with different effects. See Return value .

The initial value of the Boolean object.

Return value

When Boolean() is called as a function (without new ), it returns value coerced to a boolean primitive .

When Boolean() is called as a constructor (with new ), it coerces value to a boolean primitive and returns a wrapping Boolean object, which is not a primitive.

Warning: You should rarely find yourself using Boolean as a constructor.

Description

The value passed as the first parameter is converted to a boolean value . If the value is omitted or is 0 , -0 , 0n , null , false , NaN , undefined , or the empty string ( "" ), then the object has an initial value of false . All other values, including any object, an empty array ( [] ), or the string "false" , create an object with an initial value of true .

Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with the value false . This property is legacy and non-standard and should not be used.

Creating Boolean objects with an initial value of false

Note how converting a Boolean object to a primitive with Boolean() always yields true , even if the object holds a value of false . You are therefore always advised to avoid constructing Boolean wrapper objects.

If you need to take the primitive value out from the wrapper object, instead of using the Boolean() function, use the object's valueOf() method instead.

Creating Boolean objects with an initial value of true

Specifications.

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Udacity

Javascript Booleans: True or False Values

A core mechanic of Javascript is the ability to distinguish between true and false values. The Javascript standard defines true and false values as a unique data type called a Javascript boolean.

Javascript booleans may be true , false , or (in certain contexts) a value that evaluates to either true or false . It is important to manage boolean contexts properly because many Javascript constructs rely on them.

This article describes what Javascript booleans are and how to use them appropriately in different programming contexts.

Javascript Boolean Basics

Javascript booleans are a primitive type, which means they do not need to be explicitly created as an object. Use the reserved keywords true or false to assign a boolean value to a variable. The same logic applies when creating a boolean in JSON .

Never explicitly specify a boolean value as a string or as an object. Strings are not the correct data type for boolean expressions, while creating booleans as objects results in unnecessary overhead and complicates code.

Javascript control statements that only execute under certain conditions rely on booleans to evaluate those conditions. This is a vital mechanism in structures including while loops and if else statements , as the following example demonstrates. In this example, assume that someBoolean() is a Javascript function that returns a boolean value.

‘Truthy’ and ‘Falsy’ Values

Implicit Javascript booleans are values that evaluate to true or false in the context of a Javascript language structure like a while loop. These implicit values, since they’re not strictly true or false, are commonly known as “truthy” or “falsy” (or “falsey”).

“Truthy” values usually come from objects with a defined value or structure. For example, an empty array, most numbers, empty objects, and non-empty strings (including those composed of only whitespace) evaluate to an implicit true . The following examples show some less intuitive “truthy” values.

“Falsy” values usually come from objects without a defined value or structure. For example, null values, undefined values, and the empty string evaluate to an implicit false . The following examples show some less intuitive “falsy” values.

Assume that all values are “truthy” unless they are explicitly defined as “falsy.” Explicitly defined “falsy” values can sometimes vary between browsers and Javascript implementations, so when in doubt, consult the available documentation.

Managing Javascript Booleans

Since Javascript booleans can be explicit or implicit, you should always be aware whether you are using strict Javascript operators to evaluate boolean expressions. “Truthy” and “falsy” expressions only evaluate as equal to explicit booleans if you are not using strict comparisons.

In this example, the first comparison considers the string “1” equal to true because it uses the non-strict equals operator ( == ). The second comparison considers the string “1” unequal to true because it uses the strict equals operator ( === ).

The flexibility of using non-strict comparisons with “truthy” and “falsy” expressions can be both helpful and harmful. It may make programming easier, but maintenance may be tougher in the long term because it could be hard to tell which values are being compared.

Javascript booleans are a core data type that many other parts of Javascript rely on. Distinguishing between explicit booleans and “truthy” or “falsy” values is a common source of programming errors, so managing booleans properly is important.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript booleans and other programming concepts.

Jessica Reuter Castrogiovanni

Popular Nanodegrees

Programming for data science with python, data scientist nanodegree, self-driving car engineer, data analyst nanodegree, android basics nanodegree, intro to programming nanodegree, ai for trading, predictive analytics for business nanodegree, ai for business leaders, data structures & algorithms, school of artificial intelligence, school of cyber security, school of data science, school of business, school of autonomous systems, school of executive leadership, school of programming and development, related articles.

javascript boolean type assignment

7 Reasons to Pick Up JavaScript Today

Javascript promises.

javascript boolean type assignment

Hoisting in JavaScript

javascript boolean type assignment

Parsing JSON in JavaScript.

[et_bloom_locked optin_id=”optin_4″]

Click below to download your preferred Career Guide

Web Developer Career Guide Cloud Career Guide Data Career Guide Robotics Career Guide

[/et_bloom_locked]

DEV Community

DEV Community

Pepe Benitez

Posted on Jun 2, 2021

Boolean Logic in Javascript 🤓

Hi programming can be overwhelming 😫 but once you are comfortable with some basic concepts, it starts to feel like a superpower 🦸‍♀️ and javascript is one of the coolest languages to learn 💯, in this document you can find a summary of using boolean logic in javascript. we will cover:, what are booleans, conditional statements.

  • Truthy and Falsy values
  • Comparison operators
  • Logical operators

If you need help with your setup, you can find some help here 👈

Booleans are part of what we call primitive data types in javascript.

This data type only has two possible values— either  true  or  false  (without quotes). It’s helpful to think of booleans as on and off switches or as the answers to a “yes” or “no” question.

Boolean - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

if-else decisions can be modeled in code by creating conditional statements. A conditional statement checks a specific condition(s) and performs a task based on the condition(s).

If Statement

In programming, we can perform a task based on a condition using an if statement:

Notice in the example above, we have an  if statement. The  if  statement is composed of:

  • The  if  keyword followed by a set of parentheses  ()  which is followed by a  code block , or  block statement , indicated by a set of curly braces  {} .
  • Inside the parentheses  () , a condition is provided that evaluates to  true  or  false .
  • If the condition evaluates to  true , the code inside the curly braces  {}  runs, or  executes .
  • If the condition evaluates to  false , the block won’t execute.

If..else Statements

If we wanted to add some default behavior to the if statement, we can add an else statement to run a block of code when the condition evaluates to false.

An  else  statement must be paired with an  if statement, and together they are referred to as an  if...else  statement.

In the example above, the  else  statement:

  • Uses the  else  keyword following the code block of an  if  statement.
  • Has a code block that is wrapped by a set of curly braces  {} .
  • The code inside the  else  statement code block will execute when the  if  statement’s condition evaluates to  false .

if...else  statements allow us to automate solutions to yes-or-no questions, also known as  binary decisions .

If.. else if.. else Statements

We can add more conditions to our if...else with an else if statement. The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition.

The else if statements allow you to have multiple possible outcomes. if/else if/else statements are read from top to bottom, so the first condition that evaluates to true from the top to bottom is the block that gets executed.

Truthy and Falsy Values

Sometimes, you’ll want to check if a variable exists and you won’t necessarily want it to equal a specific value — you’ll only check to see if the variable has been assigned a value.

The code block in the if statement will run because myVariable has a truthy value; even though the value of myVariable is not explicitly the value true, when used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value.

So which values are  falsy — or evaluate to  false when checked as a condition? The list of falsy values includes:

  • Empty strings like  ""  or  ''
  • null  which represent when there is no value at all
  • undefined  which represent when a declared variable lacks a value
  • NaN , or Not a Number

Truthy and Falsy Assignment

In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment:

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

Comparison Operators

When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called  comparison operators .

Here is a list of some handy comparison operators and their syntax:

  • Less than:  <
  • Greater than:  >
  • Less than or equal to:  <=
  • Greater than or equal to:  >=
  • Is equal to:  ===
  • Is not equal to:  !==

Comparison operators compare the value on the left with the value on the right.

We can also use comparison operators on different data types like strings

All comparison statements evaluate to either  true  or  false  and are made up of:

  • Two values that will be compared.
  • An operator that separates the values and compares them accordingly ( > ,  < ,  <= , >= , === , !== ).

Comparisons and samenes

In javascript we use === to compare elements. == can also work but it is not strict (it does not compare data types)

Equality comparisons and sameness

Logical Operators

Working with conditionals means that we will be using booleans,  true  or  false  values. In JavaScript, there are operators that work with boolean values known as  logical operators . We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:

  • the  and  operator ( && )

When we use the && operator, we are checking that two things are true

  • the  or  operator ( || )

If we only care about either condition being true, we can use the || operator

  • the  not  operator, otherwise known as the  bang  operator ( ! )

The ! not operator reverses, or negates, the value of a boolean

We can use booleans, or statements that evaluate to booleans, to run loops for a set of defined values, like the elements of an array or a range of numbers, or while a condition evaluates to true. We can user For loops and While loops respectively.

The For Loop

The typical  for  loop includes an  iterator variable  that usually appears in all three expressions. The iterator variable is initialized, checked against the stopping condition, and assigned a new value on each loop iteration. Iterator variables can have any name, but it’s best practice to use a descriptive variable name.

A  for  loop contains three expressions separated by  ;  inside the parentheses:

  • an  initialization  starts the loop and can also be used to declare the iterator variable.
  • a  stopping condition  is the condition that the iterator variable is evaluated against— if the condition evaluates to  true  the code block will run, and if it evaluates to  false  the code will stop.
  • an  iteration statement  is used to update the iterator variable on each loop.

The  for  loop syntax looks like this:

The While Loop

We start our loop with the keyword while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop.

The syntax of a for loop is ideal when we know how many times the loop should run, but we don’t always know this in advance. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice.

Do...While Statements

A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this:

First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.

Note that the while and do...while loop are different! Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.

Ternary Operator

In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement.

We can use a ternary operator to perform the same functionality:

  • The condition,  isNightTime , is provided before the  ? .
  • Two expressions follow the  ?  and are separated by a colon  : .
  • If the condition evaluates to  true , the first expression executes.
  • If the condition evaluates to  false , the second expression executes.

Like  if...else  statements, ternary operators can be used for conditions which evaluate to  true  or  false .

Useful resources on Javascript

JavaScript | MDN

freeCodeCamp.org

JavaScript Tutorial: Learn JavaScript For Free | Codecademy

JavaScript Code to go

Hi! My name is Pepe 👾, and I am from Panama in Central America 🌴🌞🌴 You can find me in linkedin , twitter or github.

  • If you found this useful feel free to share it!
  • If you have any questions, recommendations or general comments feel free to drop me a message!

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

thesanjeevsharma profile image

Debouncing and Throttling

Sanjeev Sharma - Aug 9

irhose profile image

The Impact of Poor Endpoint Monitoring and Backend Error Tracking: A CTO's Perspective

Irhose - Jul 29

manoj_gayakwad_4291cfbcd5 profile image

One of the best free one-time password (OTP) sender APIs

Manoj Gayakwad - Aug 1

swhabitation profile image

How to Fix the Annoying White Space Issue in iOS Safari: A Beginner's Guide with Easy Solutions

swhabitation - Jul 27

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript Boolean

JavaScript Boolean represents true or false values. It’s used for logical operations, condition testing, and variable assignments based on conditions. Values like 0, NaN, empty strings, undefined, and null are false; non-empty strings, numbers other than 0, objects, and arrays are true.

Note: A variable or object which has a value is treated as a true boolean value. ‘ 0 ‘, ‘NaN’, empty string, ‘undefined’, and ‘null’ is treated as false boolean values. 

Here a1 and a2 store the boolean value i.e. true and false respectively. 

Note: The below variables are initialized with strings, not boolean values.  

Boolean() function in JavaScript

The Boolean() function in JavaScript converts any value to its corresponding Boolean representation: truthy values become true, and falsy values become false.

Syntax:   

Example 1:  The below program will give true values as output.

Example 2: Below program will give true values as output.

Example 3:  Below program will give false values as output. 

JavaScript Boolean object:  

The boolean object in javascript is an object wrapper for boolean values. Booleans in JavaScript can also be defined using the new keyword. 

Below are examples of the JavaScript Boolean method.

Example 1: Below program will give false values for the first 4 variables & true for last 2 values as output.

Example 2:  Below program will give true for the first value & false for the second value as output.

Note: v1 = = = v2 is not true as the type of v1 and v2(object) is not the same.

Supported Browsers

  • Google Chrome 5.0
  • Mozilla 4.0

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript .

JavaScript Boolean – FAQs

What is a boolean in javascript.

A Boolean is a primitive data type in JavaScript that can have one of two values: true or false. It is used to represent logical values and control the flow of the program.

What values are considered truthy or falsy in JavaScript?

Falsy values: false, 0, -0, 0n, “” (empty string), null, undefined, NaN. Truthy values: All values that are not falsy, including objects, non-zero numbers, non-empty strings, and arrays.

How do you use Booleans in conditional statements?

Booleans are commonly used in conditional statements like if, else, while, and for loops to control the flow of the program.

How do you compare Boolean values?

You can compare Boolean values using standard comparison operators (==, !=, ===, !==). The strict equality operators (===, !==) are recommended to avoid type coercion.

How do Boolean objects differ from Boolean primitives?

Boolean objects are created using the Boolean constructor and are objects, while Boolean primitives are simply true or false. Boolean objects are always truthy, even if they represent false.

Please Login to comment...

Similar reads.

  • Web Technologies
  • JavaScript-Boolean

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript data types, javascript has 8 datatypes.

String Number Bigint Boolean Undefined Null Symbol Object

The Object Datatype

The object data type can contain both built-in objects , and user defined objects :

Built-in object types can be:

objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.

A JavaScript variable can hold any type of data.

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expressions from left to right. Different sequences can produce different results:

JavaScript:

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.

Advertisement

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

You will learn more about strings later in this tutorial.

JavaScript Numbers

All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

Exponential Notation

Extra large or extra small numbers can be written with scientific (exponential) notation:

Most programming languages have many number types:

Whole numbers (integers): byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point): float (32-bit), double (64-bit).

Javascript numbers are always one type: double (64-bit floating point).

You will learn more about numbers later in this tutorial.

JavaScript BigInt

All JavaScript numbers are stored in a 64-bit floating-point format.

JavaScript BigInt is a new datatype ( ES2020 ) that can be used to store integer values that are too big to be represented by a normal JavaScript Number.

You will learn more about BigInt later in this tutorial.

JavaScript Booleans

Booleans can only have two values: true or false .

Booleans are often used in conditional testing.

You will learn more about booleans later in this tutorial.

JavaScript Arrays

JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars , containing three items (car names):

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

You will learn more about arrays later in this tutorial.

JavaScript Objects

JavaScript objects are written with curly braces {} .

Object properties are written as name:value pairs, separated by commas.

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

You will learn more about objects later in this tutorial.

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

You will learn more about typeof later in this tutorial.

In JavaScript, a variable without a value, has the value undefined . The type is also undefined .

Any variable can be emptied, by setting the value to undefined . The type will also be undefined .

Empty Values

An empty value has nothing to do with undefined .

An empty string has both a legal value and a type.

Test Yourself With Exercises

Use comments to describe the correct data type of the following variables:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Can you conditionally assign a type based on a boolean value?

I asked myself the question in the title while dealing with this issue: I have function getResponse from a library which either returns { a: number } if it's an Android phone or { b: number } if it's an iOS phone.

I had this code and the assignment to value here gives me a type error:

I solved the issue with a type guard by creating a type predicate isAndroidResponse

and using it as follows:

However, I have two issues with this solution which make me doubt whether it really is a "good" solution for my problem:

In the type predicate I'm not using the passed response variable.

It is a lot of code! I would love to have much less code, by perhaps just do something along these lines (which is not correct TS code):

This brings me to my follow-up question : Is my usage of a type predicate a feasible solution or am I misusing it in this case?

I created this TS playground for the described example.

Andru's user avatar

  • Are you going to compile the code twice, once for true and once for false ? –  jcalz Commented Sep 19, 2021 at 19:38
  • Also, your minimal reproducible example might be a little too minimal, since my inclination here would be to inspect response and not worry about isAndroid anymore, like this . If you go further and make the response type of getResponse() a discriminated union with an isAndroid discriminant property like this , then you could just check the discriminant. –  jcalz Commented Sep 19, 2021 at 19:47
  • @jcalz The getResponse function comes from a third-party React Native lib. It will return a different response object dependent on the platform (iOS vs. Android) which is determined at runtime. isAndroid can give me this information outside of the lib. Your first solution to inspect response directly indeed is an option - however, that code does not "explain" the platform distinction. Your second option (discriminated union) is not possible because I can't amend the third-party lib. Would wrapping a discriminant property around the given response be a feasible approach? –  Andru Commented Sep 20, 2021 at 14:42
  • 1 Yeah, you could either wrap or merge the discriminant property to get that behavior. I think your original method of using a type guard function is probably fine but it's definitely strange for it not to depend on the value being passed in... it's essentially a distributed discriminated union; your isAndroid boolean floats out there seemingly unrelated to the response. The explicit wrapped/merged discriminated union might be a little less confusing and easier to support. If either of the above linked solutions helps I'm happy to write it up. –  jcalz Commented Sep 20, 2021 at 15:44
  • 1 I will do so, but it's a term I just made up. Maybe "nonlocal" is a better term. But I will explain in my answer. –  jcalz Commented Sep 20, 2021 at 17:59

Conceptually, you have a boolean value isAndroid which acts as a discriminant for the union type that comes out of getResponse() . It means that the return type of getResponse() is like a discriminated union , but one where the discriminant property is floating disconnected from the return value itself. I'll call this a "nonlocal discriminated union" for want of a standard term.

TypeScript really isn't set up to understand nonlocal discriminated unions, so you will need to work around it in some way.

If you really care about minimizing excess code, the best you can do is to use some type assertions to just tell the compiler what it can't verify by itself:

This isn't type safe, (e.g., nothing stops you from changing the test from isAndroid to !isAndroid ) but neither is the implementation of your isAndroidResponse() user-defined type guard function , nor is any solution that defines isAndroid prior to the call to getResponse() .

If you are only writing getResponse() once or twice in your code, I would recommend type assertions.

If you are going to write getResponse() many places in your code, then maybe you do want to refactor so that the unsafe part is encapsulated in a single function, like isAndroidResponse() .

If you do want to do this, my opinion (and this is just an opinion) is that your isAndroidResponse() implementation is fine. It might surprise people since it seems weird that you'd be able to do anything without inspecting the response argument. But if you comment it, that might be okay.

Another approach is to make the nonlocal discriminated union into a true discriminated union, by adding isAndroid as a discriminant property of the response:

The unsafe code is confined to the implementation of getResponseʹ() (since we had to assert the return type), but now you can forget about the original isAndroid flag and instead leverage the support the language has for discriminated unions.

Playground link to code

jcalz's user avatar

  • 1 Was first wondering why the type cast as Response in the last example is necessary but then realized that it is because TypeScript can't know that the nonlocal boolean value isAndroid determines the structure of the discriminant union. Btw: Thanks for this great answer @jcalz which helped me learn a lot about TypeScript (like so many of your other TS related answers)! :-) –  Andru Commented Sep 21, 2021 at 13:26
  • 1 Right, exactly. If the compiler had any idea that isAndroid was correlated to the return value of getResponse() , there wouldn't be a problem in the first place. No matter what you do here, you'll need to tell the compiler about the correlation. This involves some unsafe code somewhere , since when you tell the compiler about something like this, it'll just believe you even if you're lying or mistaken. Type assertions, function overload implementations, user-defined type guard function implementations, and assertion function implementations are all unsafe in this way. –  jcalz Commented Sep 21, 2021 at 13:52

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript typescript or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Design patterns - benefits of using with Apex code
  • How to open a single app in a particular language while the system language is English?
  • Can I replace 2 Zinsco single pole 35amp breakers with one 35amp 2-pole?
  • Weird lines in the Aeneid (Book I, lines 444-445)
  • How many kinds of contradictions are there?
  • Refereeing papers by people you are very close to
  • It was all he could do not to smoke
  • If pressure is caused by the weight of water above you, why is pressure said to act in all direction, not just down?
  • 80s/90s sci fi children's novel about a future TV star on Earth who is visited by a space woman
  • Will lights plugged into cigarette lighter drain the battery to the point that the truck won't start?u
  • Double accentuation (Homeric Greek)
  • How can flipflops sense the edges of the signals?
  • Cycloheptatrienyl anion is antiaromatic or non-aromatic?
  • Short story probably in Omni magazine in the 1980s set in a cyberpunk bar… but it's 1899 or so
  • Can I use specific preprocess hooks for a node type or a view mode?
  • sed (or awk): print captured group or placeholder if it doesn't exist
  • Creating specific flash memory area in STM32G0 microcontroller
  • I don't do something AFTER I did something
  • How do I resolve license terms conflict when forking?
  • Can an elf and a firbolg breed?
  • Is there mutable aliasing in this list of variable references?
  • Is there such a thing as icing in the propeller?
  • Operator norm of sum of tensor products
  • Emphasizing the decreasing condition in the Integral Test or in the AST (in Calculus II): is it worth the time?

javascript boolean type assignment

IMAGES

  1. JavaScript Booleans

    javascript boolean type assignment

  2. Javascript Tutorial 5 Arrays & Booleans

    javascript boolean type assignment

  3. Javascript Data Types (String, Number, Boolean, Array, Object)

    javascript boolean type assignment

  4. JavaScript Boolean

    javascript boolean type assignment

  5. Booleans in JavaScript

    javascript boolean type assignment

  6. JavaScript

    javascript boolean type assignment

COMMENTS

  1. JavaScript Booleans

    Boolean Values. Very often, in programming, you will need a data type that can only have one of two values, like. YES / NO. ON / OFF. TRUE / FALSE. For this, JavaScript has a Boolean data type. It can only take the values true or false.

  2. Declaring a boolean in JavaScript using just var

    If I declare a JavaScript boolean variable like this: var IsLoggedIn; And then initialize it with either true or 1, is that safe? Or will initializing it with 1 make the variable a number?

  3. Boolean

    A value's truthiness is important when used with logical operators, conditional statements, or any boolean context. There are two ways to achieve the same effect in JavaScript. Double NOT: !!x negates x twice, which converts x to a boolean using the same algorithm as above. The Boolean() function: Boolean(x) uses the same algorithm as above to ...

  4. JavaScript Boolean Type

    The JavaScript boolean primitive type has two literal values: true and false. The following example declares two variables and initializes their values to true and false: let running = false; Code language: JavaScript (javascript) The boolean's literal values are case-sensitive. This means that the True and False are valid identifiers but ...

  5. JavaScript Booleans (Primitive Type and Object)

    JavaScript Booleans The boolean (not Boolean) is a primitive data type in JavaScript. It can have only two values: true or false. It is useful in controlling program flow using conditional statements like if else, switch, while loop, etc.

  6. How to use Booleans in JavaScript

    Boolean Booleans are a primitive datatype commonly used in computer programming languages. By definition, a boolean has two possible values: true or false. In JavaScript, there is often implicit type coercion to boolean. If for example you have an if statement which checks a certain expression, that expression will be

  7. Booleans

    The Boolean object can be used to coerce a value to a true or false boolean, based on the implicit true or false state of that value: Boolean( "A string literal" ); > true. Values that result in false include 0, null, undefined, NaN, an empty string ( "" ), an omitted value, and a false boolean. All other values result in true.

  8. JavaScript Booleans

    In JavaScript, booleans are the primitive data types that can either be true or false. For example, const b = false; Note: If you wrap true or false in a quote, then they are considered as a string. For example, console.log(typeof a); // string. The boolean values are mostly used for Comparison and Logical Operators.

  9. Mastering Booleans in JavaScript: Logical Operations Guide

    Booleans are a fundamental concept in JavaScript and serve as the building blocks for decision-making and logical operations in programming. By understanding the syntax of Booleans and utilizing logical operators effectively, you can create robust and flexible JavaScript code.

  10. How to Write Boolean Variables in JavaScript

    Along with strings and numbers, booleans are one of the most important data types in JavaScript. This lesson will teach you how to write boolean variables in JavaScript.

  11. Learn Booleans in JavaScript

    A JavaScript boolean let's you know whether something is TRUE or FALSE, on or off, yes or no, etc. Learn how to use boolean values in your JavaScript coding today!

  12. JavaScript Boolean vs. boolean: Explained By Examples

    JavaScript Boolean Summary: in this tutorial, you will learn about the JavaScript Boolean object and the differences between the Boolean object and the boolean primitive type.

  13. Boolean () constructor

    The Boolean() constructor creates Boolean objects. When called as a function, it returns primitive values of type Boolean.

  14. Javascript Booleans: True or False Values

    A core mechanic of Javascript is the ability to distinguish between true and false values. The Javascript standard defines true and false values as a unique data type called a Javascript boolean. Javascript booleans may be true, false, or (in certain contexts) a value that evaluates to either true or false.

  15. Boolean Logic in Javascript

    In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators: the and operator ( &&) When we use the && operator, we are checking that two things are true.

  16. JavaScript Boolean

    JavaScript Boolean represents true or false values. It's used for logical operations, condition testing, and variable assignments based on conditions. Values like 0, NaN, empty strings, undefined, and null are false; non-empty strings, numbers other than 0, objects, and arrays are true.

  17. Javascript boolean assignment

    No, there's no compound assignment for boolean operations in JS. So yes, you have to use x = x && y form. It's worth nothing that true & true == true, true & false == false and false & false == false - they might not be boolean values, but the equality holds. Ok but for example, I used this: $ ("...").toggleClass ("myclass",test) and test was ...

  18. javascript

    You can store a true/false value or an object with any number of pairs of boolean type values into a variable of type YourType.

  19. JavaScript Data Types

    JavaScript Types are Dynamic JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

  20. How to add boolean attribute using JavaScript

    Boolean attributes. For boolean attributes, set the attribute with the same-named value: element.setAttribute('disabled', 'disabled'); Removing a boolean attribute works the same way as other attributes: element.removeAttribute('disabled'); However, neither of your two examples are boolean attributes!

  21. javascript

    Conceptually, you have a boolean value isAndroid which acts as a discriminant for the union type that comes out of getResponse(). It means that the return type of getResponse() is like a discriminated union, but one where the discriminant property is floating disconnected from the return value itself. I'll call this a "nonlocal discriminated ...