Optional Chaining in JavaScript

?.Optional Chaining operator

Image from twitter by Daniel Rosenwasser (@Daniel Rosenwasser).

Optional chaining will eliminate the need for manually checking if a property is available in an object. With option chaining the checking will be done internally.

Example without Optional chaining.

const planet1 =  {
    name: 'Earth',
    size: '6,371 km'
  }

const planet2 = {
    name: 'Mars',
    // size: '3,389.5 km'
  }

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  console.log(`Size: ${planet.size.toUpperCase()}`)
}

printPlanetInfo(planet1)
printPlanetInfo(planet2)

When we pass an planet object which doesn’t have the size property:

To solve the above problem what we do is, we will add check if size property available in the planet object

const planet1 =  {
    name: 'Earth',
    size: '6,371 km'
  }

const planet2 = {
    name: 'Mars',
    // size: '3,389.5 km'
  }

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  planet.size = ( planet && planet.size &&
                  planet.size.toUpperCase())
                || "undefined"
  console.log(`Size: ${planet.size}`)
}

printPlanetInfo(planet1)
printPlanetInfo(planet2)

Using Optional Chaining

The optional chaining will check if an object left to the operator is valid (not null and undefined). If the property is valid then it executes the right side part of the operator otherwise return undefined.

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  planet.size = ( planet?.size?.toUpperCase() ) || "undefined"
  console.log(`Size: ${planet.size}`)
}

The native JavaScript equivalent code for above optional chaining operator is

(property == undefined || property == null) ? undefined : property

Using variables as property name

We can use variables as property name in optional chaining

const planet = {
  name: 'Earth',
  size: '6,371 km'
}

planet?.size

// We can also use with expressions

planet?.["s"+"ize"] 

Functional call with optional chaining

You can use optional chaining to call a method which may not exist.

const planet = {
  name: 'Earth',
  size: '6,371 km'
  getSize() {
    return this.size;
  }
}

planet?.getSize?.()

Reference: MDN.

Tree Data Structure

Usually when we start to study data structures, we study first trees and then graph. Can I give you two tips ? First read about graph theory. Try to answer for yourself the two following questions:

  • What are acyclic and cyclic graphs ?
  • What are directed, undirected and bidirectional graphs ?

Right. Are you a bit more confused now ? 🙂 Let’s blow the candles and see the knowledge emerging like magic. Let’s list some conditions to say: “Hey it is a tree !”

  • Just like in real life, there are many types of trees data structures that we can have.
  • In graph theory, a tree is a nonlinear data structure, compared to arrays, linked lists, stacks and queues which are linear data structures.
  • One of the disadvantages of using an array or linked list to store data is the time necessary to search for an item. Since both the arrays and Linked Lists are linear structures the time required to search a “linear” list is proportional to the size of the data set.
  • Every tree is a graph, but not every graph is a tree.
    • A is the root but it also a parent. In graph theory, a loop (also called a self-loop or a “bucle”) is an edge that connects a vertex to itself. A tree don’t have loop.
  • A child has just one parent.
  • A tree is acyclic(contains no cycles).