Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
Javascript Booleans and Equality JavaScript

04. Javascript Guide Booleans and Equality

  • September 20, 2022September 20, 2022
  • by Coder Kai

Javascript, just like any other language uses boolean to represent logical true or false. It has two reserved keywords true and false to represent a boolean value. Booleans are mostly comparative results as it will compare a value to another and check equality generally. Javascript compared to other languages have both strict and loose comparisons that we should mind when using. Lets start to explore more on Javascript Booleans and Equality

1. Javascript Booleans and Equality

A typical example of comparing a value in javascript is the following.

const a = 4, b = 5, c = 4, d = 'foo', e = '4';
console.log(a == b); // 4 == 5 -> false
console.log(a == c); // 4 == 4 -> true
console.log(a == d); // 4 == 'foo' -> false
console.log(a == e); // 4 == '4' -> true
console.log(a === e); // 4 === '4' false

If you are not familiar with equality operators == (loose) and === (strict) in JS, you might find it difficult to apprehend the above. We can discuss further it in the operators section in the future.

In above examples, a has value four and either of the sides matches with the value in equality it evaluates the result as true while the contrary is false. This is used to decisions and structures in programming languages and its the very fundamental of all programming languages. A typical if the condition is commonly used when programming as a control structure. Example

if (weather === 'SUNNY') {
  openWaterValve();
} else {
  startFans();
}

If the weather is sunny it will open the water valve and it will start the fans otherwise. This can be programmatically coded as above.

Also, all the javascript values can be converted to booleans and since javascript is loosely typed, its a convenient way to code. But it could also bring down very dramatic behaviors to codes and this should be really remembered when coding.

2. Truthy and Falsy values

Javascript has the following values which will convert to false when evaluated as a boolean.

undefined
null
0
-0
NaN
""

For example

const a = null, b = 0;
if (a || b) {
  console.log('Someone is true');
} else {
  console.log('Both are false'); 
}

We call the above values that are not false but can be evaluated as false with a logical operation as falsy values. All the others including arrays, objects, functions etc. are known as truthy values. Its because they are not actually true or false but they act like that when converted.

Example:

const token = null;
if (token !== null) {
  // fetch data
}

This can be coded as following as the null value will be converted to false.

const token = null;
if (token) {
  // fetch data
}

Note that this check is not strict. So if you assign any falsy value like null or undefined it will not proceed.
Other point is if you have an empty object {} or empty array [] it will proceed as its not falsy.

const token = {}
if (token) {
  // this will proceed
}

3. Boolean AND, OR operation

Boolean AND operation(&&) will proceed only if both sides of the operator are true or truthy. Most importantly it will execute a function only if the left hand side values are truthy before it comes to checking the function. As an example

const a = true, b = 1;
if (a && b) {
  console.log('Both are true')
}

const user = isAuthenticated && getUser();
// isAuthenticated is evaluated first and if its only true, getUser() is called

Boolean OR (||) operation will proceed if any one of the conditions is true or truthy. It will go on checking every condition until it finds a true value otherwise. Important point is

  1. It will stop if as soon as it finds the true value when proceeding left to right
  2. I will continue until it finds a true value from left to right

One example you can code with this

const user = null;
// somewhere else
const loggedInUser = user || getUser(); // if user is null it will call get user

4. Unary ! operator

This performs a boolean NOT operation. Basically, if the value is truthy it will evaluate to false and if the value is falsy it will evaluate to true

let user = null;
if (!user) {
  user = fetchUser();
}

5. !! Not Not pseudo operator

This will convert the truthy or falsy value to true and false boolean values. This is not an operator this is a repetition of the ! operator. For example

const user = null;

const report = {
  isUserAvailable: !!user, // resolves to boolean `false` value
}

6. ?? Nullish coalescing operator

This quite comes in handy when you want to use null assignments with ternary operators. It will return the right hand side value if the left hand side value is null or undefined only. For example

// null or undefined
const user = null;
const loggedUser = user ?? getUser(); // calls getUser()

// falsy values
const userCount = 0;
const loggedUserCount = userCount || getUserCount() // returns 0

This is different from the || operator. || the operator will return right side for all the falsy values. For the second example it will call getUserCount()function although the value is already a number.

If you like to know more on javascript strings, check following link

03. Javascript Guide – Strings
Chakra UI Animations
05 Global, null and undefined values in Javascript
Coder Kai
A humble developer
Boolean in Javascript Javascript Guide Not Not operator Question Question operator truthy and falsy

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
How to add Chakra UI Animations
Chakra UI Animations
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
How to fetch data with useEffect
How to fetch data with…
add styles to stripe elements
How to add styles to…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
debounce with react hooks
Avoid multiple clicks using debounce…
Numbers inJavascript
02. Javascript Guide – Numbers
Introduction to Javascript
01. Javascript Guide – Introduction…
Nginx Load Balancer with docker…
Create React App Using npx
  • Pingback: Globals undefined and null values in javascript when programming()

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • sign up for binance on 07. Immutable and Mutable Values in Javascript
  • Dang k'y d nhn 100 USDT on Using multiple refs for an array of React Elements
  • b^onus de inscric~ao na binance on How to optimize React.js app load time using react lazy

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress