Progress bar trick with Number()

So, there is a quiz app(Vite + React + TS (react-ts-msw-quiz-app.vercel.app)) that shows a single question and four answers. If I click on the answer, I want the progress bar to be updated.

So here is the solution. Look how the progress bar increases when an answer is clicked. Check how the Number() function is being used. Just remember undefined is not equal to null .

import { FC } from "react";

interface ProgressProps {
  numQuestion: number;
  index: number;
  points: number;
  maxPoints: number;
  answer: number | null;
}
export const Progress: FC<ProgressProps> = ({
  numQuestion,
  index,
  points,
  maxPoints,
  answer,
}) => {
  return (
    <header className="progress">
      <progress max={numQuestion} value={index + Number(answer !== null)} />
      <p>
        Question{" "}
        <strong>
          {index + 1}/{numQuestion}
        </strong>
      </p>
      <p>
        <strong>
          {points} / {maxPoints}
        </strong>
      </p>
    </header>
  );
};

Explaination of Number()

So, inside the number I am comparing if the answer is not a null. I made sure that answer is not undefined and is always a number or null. By default the value of the answer is null, so (answer !== null) will be true. Number() will convert the true to 1. If the condition is false, then Number will convert the false to 0.

If you are still confused, run the following function call in a javascript environment like in the browser console. Open the browser console, and type this.

Number(true) // returns 1

Number(false) // returns 0

0
Subscribe to my newsletter

Read articles from Aniket Pandharabale directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aniket Pandharabale
Aniket Pandharabale