Distance Between Two Points

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of calculating the distance between two points in JavaScript. We will use the Math.hypot() method to calculate the Euclidean distance between two points and implement it in a function. This lab will help you understand how to use mathematical formulas in JavaScript to solve problems.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28276{{"`Distance Between Two Points`"}} javascript/data_types -.-> lab-28276{{"`Distance Between Two Points`"}} javascript/arith_ops -.-> lab-28276{{"`Distance Between Two Points`"}} javascript/comp_ops -.-> lab-28276{{"`Distance Between Two Points`"}} end

Calculating the Distance Between Two Points

To calculate the distance between two points, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Math.hypot() to calculate the Euclidean distance between two points.
  3. Implement the code below, replacing the x0, y0, x1, and y1 values with the coordinates of your points.
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);

Here's an example of how to use this function:

distance(1, 1, 2, 3); // ~2.2361

This will output the distance between the points (1, 1) and (2, 3).

Summary

Congratulations! You have completed the Distance Between Two Points lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like