JavaScript program to calculate potential energy if mass and height are given
This article explores various JavaScript methods for calculating potential energy from mass and height, offering insights into direct formulas and functional programming techniques.
Given a mass m and a height h, the task is to find an object’s potential energy (PE) and the task is to find the potential energy PE. Potential Energy can be calculated using the formula:
Potential Energy = m * g * h
// Where g is the acceleration due to gravity and its value is 9.8 m/s^2.
Table of Content
- Using formula
- Using arrow function
Using formula
In this approach, we take the values of mass and height and calculate the potential energy directly using the formula mentioned above.
Example: Implementation to calculate to calculate potential energy using direct formula approach.
const mass = 10;
const height = 5;
const gravity = 9.8;
const potentialEnergy = mass * gravity * height;
console.log(`The potential energy is ${potentialEnergy}.`);
Output
The potential energy is 490.
Using arrow function
In this approach we are using an arrow function to calculate potential energy.
Syntax:
const functionName = (parameter1, parameter2, ...) => expression;
const calculatePotentialEnergy =
(mass, height) => mass * 9.8 * height;
const mass = 12;
const height = 6;
const potentialEnergy = calculatePotentialEnergy(mass, height);
console.log(`The potential energy is ${potentialEnergy}.`);
Output
The potential energy is 705.6.