Can somebody explain this code to me?

This code works and does exactly what I want, however I don’t understand the last part of

equals.onclick = function () {
const pressureValue = Number(pressure.value)
const areaValue = Number(area.value)
const result = force1(pressureValue, areaValue)

forceResult.innerHTML = result + " lbs"

Questions:

What exactly is this? a function? something else?

why does it have an = function () ?? Is it a function or a made up name?

Then you have this:
const pressureValue = Number(pressure.value)
const areaValue = Number(area.value)

What exaclty is
Number(pressure.value) ??
Number (area.value) ??
I understand they are part of the variable, but what do the items in parenthesis do?

If you want to see the entire code I’ll leave a link to the codepen code below.

It is basically a pressure x area = Force formula.

I created the variables of pressure, area, equals, forceResults, and the function force1… but I have not much idea of the logics behind the equals.onclick part of the code, as I didn’t write that part…

Number is the object wrapper for the Number type. This:

const pressureValue = Number(pressure.value)

is a way to convert pressure.value to a number. There are other ways, but this is one of them. From the above documentation:

Number('123')  // returns the number 123
Number('123') === 123  // true

Number("unicorn")  // NaN
Number(undefined)  // NaN

Yeah, the whole JS type system and what object wrappers are a bit weird (at least to me) but just keep at it.

Does that answer your question?

This is just a way to create an anonymous function and store it in that property.

I think you also could have done:

function myFunc() {
 // ...
}
equals.onclick = myFunc;

So, what is the proper name for that equals.onclick = piece of code? Is that a function made for the variable of equals? equals is the button that you press to get the results.

On my next to nothing knowledge about coding it got me confused because just above that piece of code I wrote a function (shown below) to throw the math results… but I couldn’t find a way to display it on the equals.onclick part of the code…

function force1 (pressure, area) {
  return pressure * area;

The proper name for that particular type of function is an event handler. The onClick is an event that happens when someone clicks on that particular element in the page, and that line tells javascript how to handle that click event… With an event handler function.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.