📘
NavDoc by Bash School
GithubContact
📘
NavDoc by Bash School
  • 🎓Introduction
  • 🐢Getting Started
  • ⚡Changelog
  • 👨‍🚀Maintainers
  • 🛣️Roadmap
  • Fundamentals
    • The Internet
      • Introduction
      • What is a URL
      • What is a port
      • The DNS protocol
      • The TCP protocol
      • The UDP protocol
      • The Web
      • The HTTP protocol
      • Hyperlinks
      • What is a Web browser
      • What is a Web server
    • HTML
      • Your first HTML page
      • Text tags
      • Attributes
      • Links
      • Images
      • Lists
      • Head Tags
      • Container tags
    • CSS
      • Introduction
      • Colors
      • selectors
      • Cascade
      • Specificity
      • Units
      • Advanced selectors
      • Typography
      • The box model
      • The display property
      • Responsive design
  • JavaScript
    • Basics
      • Introduction
      • Literals , Identifiers, Variables
      • Comments
      • The difference between let, const and var
      • Types
      • Operators and expressions
      • Arithmetic operators
      • The assignment operator
      • Operators precedence
      • Strings
      • Numbers
      • Semicolons, white space and sensitivity
      • Arrays
      • Conditionals
      • Loops
      • Functions
      • Objects
      • Arrays + functions
      • OOPS
      • Asynchronous
      • Scope, hoisting, event loop
      • ES Modules
      • Errors and exceptions
      • Built-in objects
        • The global object
        • Object properties
        • Number
        • String
        • Math
        • JSON
        • Date
        • Intl
        • Set and Map
      • More operators
    • Nodejs
      • Getting Started
      • Installation
      • Hello World in Node
      • Modules
      • Packages
      • File Handling
      • HTTP Request
      • Processing Files
      • HTTP
    • Express.js
      • Getting Started
      • Middleware
      • Serve Static Assets
      • How to Send Files to the Client
      • Sessions
      • Validate Input
      • Sanitizing Data
      • Forms
      • File Uploads
    • React
      • Setting up a React project with Vite
      • React Components
      • Introduction to JSX
      • Using JSX to compose UI
      • The difference between JSX and HTML
      • Embedding JavaScript in JSX
      • Handling user events
      • Managing state
      • Component props
      • Data flow
      • Lifecycle events
      • Managing forms in React
      • Install the React Developer Tools
      • Installing Tailwind CSS in a React app
      • Build a counter in React
    • TypeScript
      • Key Benefits
      • Types of Languages
      • The Need for TypeScript
      • What is TypeScript?
      • The tsc Compiler
      • Basic Types in TypeScript
      • tsconfig
      • Interfaces
      • Types
      • Arrays in TypeScript
      • Enums
      • Exporting and importing
    • MongoDB
      • SQL vs. NoSQL Databases
      • Installing MongoDB
      • MongoDB Databases and Collections
      • Working with Documents
      • MongoDB Operators
      • Sorting, Indexing & Searching
      • Built-in Methods
Powered by GitBook
On this page
  • More assignment operators
  • Logical operators
  • Logical and
  • Logical or
  • Logical not (!)
  • Nullish coalescing
  • Optional chaining
  • Logical nullish assignment

Was this helpful?

Edit on GitHub
  1. JavaScript
  2. Basics

More operators

There is an operator for everything. Almost.

JavaScript has a ton of different operators you can use for various jobs and use cases.

We’ve already seen some operators in previous units, like conditionals.

In this unit I’ll explain some more super powerful and useful operators.

More assignment operators

We’ve seen how to use the assignment operator = to assign a value to a variable:

const a = 2
let b = 2
var c = 2

This operator has several shortcuts for all the arithmetic operators which let you assign to the first operand the result of the operations with the second operand.

They are:

  • +=: addition assignment

  • -=: subtraction assignment

  • *=: multiplication assignment

  • /=: division assignment

  • %=: remainder assignment

  • *=: exponentiation assignment

Examples:

let a = 0
a += 5 //a === 5
a -= 2 //a === 3
a *= 2 //a === 6
a /= 2 //a === 3
a %= 2 //a === 1

To be clear, the above operations are executed one after another, so a at the end is 1, not 0

Logical operators

JavaScript provides us 3 logical operators: and, or and not.

Logical and

Returns true if both operands are true:

<expression> && <expression>

For example:

a === true && b > 3

The cool thing about this operator is that the second expression is never executed if the first evaluates to false. Which has some practical applications, for example, to check if an object is defined before using it:

const car = { color: 'green' }
const color = car && car.color

Logical or

Returns true if at least one of the operands is true:

<expression> || <expression>

For example:

a === true || b > 3

This operator is very useful to fallback to a default value. For example:

const car = {}
const color = car.color || 'green'

makes color default to green if car.color is not defined.

Logical not (!)

Invert the value of a boolean:

let value = true
!value //false

Nullish coalescing

A powerful operator available in JavaScript is the nullish coalescing operator: ??.

Have you ever used || to set a default value if a variable was null or undefined?

For example, like this:

const myColor = color || 'red'

Well, nullish coalescing is going to replace || in there:

const myColor = color ?? 'red'

Why is this operator useful?

Well, there is a whole range of bugs that hide underneath the surface when using || to provide a fallback value.

In short, || handles values as falsy. ?? handles values as nullish (hence the name).

Which means that with || the second operand is evaluated if the first operand is undefined, null, false, 0, NaN or ''.

?? on the other hand limits this list to only undefined and null.

Optional chaining

The optional chaining operator is a very useful operator which we can use to work with objects and their properties or methods.

Have you ever used the && operator as a fallback? It’s one of my favorite JavaScript features.

In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this:

const car = null
const color = car && car.color

Even if car is null, you don’t have errors and color is assigned the null value.

You can go down multiple levels:

const car = {}
const colorName = car && car.color && car.color.name

In some other languages, using && might give you true or false, since it’s usually a logic operator.

Not in JavaScript, and it allows us to do some cool things.

Now this new optional chaining operator will let us be even more fancy:

const color = car?.color
const colorName = car?.color?.name

If car is null or undefined, the result will be undefined.

With no errors (while with && in case car was undefined we had a ReferenceError: car is not defined error)

Logical nullish assignment

Remember the nullish coalescing operator ??.

We can combine it with an assignment and we get the logical nullish assignment operator ??=.

Here’s an example, you have a variable color which is set to ‘yellow’.

Using the logical nullish assignment we can say “if this variable is nullish, set it to ‘red’.

let color = 'yellow'

color ??= 'red'

color

Try setting color to null or not initialize it with a value, color in the end will be red.

One place where this is particularly useful is when you pass an object to a function, and this object may or may not have some properties set:

const say = (something) => {
  something.content ??= 'hello'

  console.log(something.content)
}

say({ content: 'x' })

In this case it prints ‘x’ but try passing an empty object, it prints ‘hello’.

This is a simplified version of saying

const say = (something) => {
  if (!something.content)
    something.content = 'hello'
  }

  console.log(something.content)
}
PreviousSet and MapNextNodejs

Last updated 1 year ago

Was this helpful?