w3resource

JavaScript: Check whether a point lies strictly inside a given circle

JavaScript Basic: Exercise-120 with Solution

Write a JavaScript program to check whether a point lies strictly inside a given circle.

Input:
Center of the circle (x, y)
Radius of circle: r
Point inside a circle (a, b)

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title> Check whether a point lies strictly inside a given circle</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function check_a_point(a, b, x, y, r) {
    var dist_points = (a - x) * (a - x) + (b - y) * (b - y);
    r *= r;
    if (dist_points < r) {
        return true;
    }
    return false;
}

console.log(check_a_point(0, 0, 2, 4, 6));
console.log(check_a_point(0, 0, 6, 8, 6));

Sample Output:

true
false

Flowchart:

Flowchart: JavaScript - Check whether a point lies strictly inside a given circle

ES6 Version:

function check_a_point(a, b, x, y, r) {
  var dist_points = (a - x) * (a - x) + (b - y) * (b - y);
  r *= r;

  if (dist_points < r) {
    return true;
  }

  return false;
}

console.log(check_a_point(0, 0, 2, 4, 6));
console.log(check_a_point(0, 0, 6, 8, 6));

Live Demo:

See the Pen javascript-basic-exercise-120 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to check whether a given integer has an increasing digits sequence.
Next: Write a JavaScript program to check whether a given matrix is lower triangular or not.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Classes/function constructors

class Person {
  constructor() {
    this.name = 'Owen';
  }
}

Person = class AnotherPerson {
  constructor() {
    this.name = 'Eddie';
  }
};

const member = new Person();
console.log(member.name);

We can set classes equal to other classes/function constructors. In this case, we set Person equal to AnotherPerson. The name on this constructor is Eddie, so the name property on the new Person instance member is "Eddie".

Ref: https://bit.ly/3jFRBje