TypeScript Math sqrt()

In this chapter, we will explore the Math.sqrt() method in TypeScript. This method returns the square root of a given number. Understanding how to use Math.sqrt() is useful for performing mathematical calculations that involve square roots.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The Math.sqrt() method returns the square root of a given number. If the number is negative, the method returns NaN (Not-a-Number) since the square root of a negative number is not a real number.

2. Syntax

Math.sqrt(x);

Parameters

  • x: A number whose square root is to be calculated.

Return Value

The method returns the square root of the given number. If the number is negative, it returns NaN.

3. Examples

Let's look at some examples to understand how Math.sqrt() works in TypeScript.

Example 1: Basic Usage

In this example, we use Math.sqrt() to calculate the square root of a positive number.

let num: number = 16;
let result = Math.sqrt(num);
console.log(result); // Output: 4

Example 2: Square Root of Zero

In this example, we use Math.sqrt() to calculate the square root of zero.

let num: number = 0;
let result = Math.sqrt(num);
console.log(result); // Output: 0

Example 3: Square Root of a Negative Number

In this example, we use Math.sqrt() to calculate the square root of a negative number. The result should be NaN.

let num: number = -16;
let result = Math.sqrt(num);
console.log(result); // Output: NaN

Example 4: Square Root of a Decimal Number

In this example, we use Math.sqrt() to calculate the square root of a decimal number.

let num: number = 2.25;
let result = Math.sqrt(num);
console.log(result); // Output: 1.5

Example 5: Using Math.sqrt() with Variables

In this example, we use Math.sqrt() with a variable to calculate the square root.

let num: number = 9;
let result = Math.sqrt(num);
console.log(result); // Output: 3

Example 6: Using Math.sqrt() with Expressions

In this example, we use Math.sqrt() with expressions to calculate the square root of the result of an expression.

let num1: number = 3;
let num2: number = 4;
let result = Math.sqrt(num1 * num1 + num2 * num2);
console.log(result); // Output: 5

4. Conclusion

In this chapter, we explored the Math.sqrt() method in TypeScript, which is used to return the square root of a given number. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use Math.sqrt() effectively can help in various mathematical calculations and scenarios where square root operations are required.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare