Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu June 07, 2024 › #error #Javascript

TypeError: Cannot read properties of undefined reading toFixed

In this article, you are going to learn how to fix the TypeError: Cannot read properties of undefined reading toFixed error in JavaScript. This error occurs when you try to use the toFixed method on a variable that is undefined or null.

Method 1: Checking for Undefined or Null Value

This method involves checking if the variable is undefined or null before using the toFixed method.

<script>
  let num = 5;
  if (num !== undefined && num !== null) {
    let result = num.toFixed(2);
    console.log(result);
  }
  else {
    console.log("num is undefined or null");
  }
</script>
  1. The if statement is used to check if the variable num is undefined or null.
  2. If num is not undefined or null, the toFixed method is used to format the number.
  3. If num is undefined or null, a message is logged to the console indicating that it is undefined or null.

Method 2: Using the Optional Chaining Operator

This method involves using the optional chaining operator (?.) to check if the variable is undefined or null before using the toFixed method.

<script>
 let num = undefined;
 let result = num?.toFixed(2);
 console.log(result);
</script>
  1. The optional chaining operator (?.) is used to check if the variable num is undefined or null.
  2. If num is not undefined or null, the toFixed method is used to format the number.
  3. If num is undefined or null, the expression returns undefined instead of throwing an error.

Method 3: Using a Default Value

This method involves using a default value if the variable is undefined or null.

<script>
 let num = undefined;
 let result = (num || 0).toFixed(2);
 console.log(result);
</script>

Explanation

  1. The || operator is used to provide a default value of 0 if num is undefined or null.
  2. The toFixed method is used to format the number.
  3. If num is undefined or null, the default value of 0 is used instead.
save
listen
AI Answer
Write Your Answer
loading
back
View All