basic math with javascript

I'm new to JavaScript and i made this website that calculates the slope of a straight line, the formula is y2-y1/x2-x1, i was wondering how i can make it work with negative numbers without making it 4 inputs.
No description
No description
3 Replies
MarkBoots
MarkBoots14mo ago
you could accept the x/y input values separated by a comma. and split those by that comma. (or another character) so for example input a: "1, -1" input b: "-2, 3"
const [x1, y1] = document.querySelector("#ainput").value.split(",").map(Number)
const [x2, y2] = document.querySelector("#binput").value.split(",").map(Number)

console.log({x1, y1, x2, y2});
// { x1:1, y1:-1, x2:-2, y2:3 }

const slope = (y2 - y1) / (x2 - x1);

alert("The slope is equal to " + slope);
const [x1, y1] = document.querySelector("#ainput").value.split(",").map(Number)
const [x2, y2] = document.querySelector("#binput").value.split(",").map(Number)

console.log({x1, y1, x2, y2});
// { x1:1, y1:-1, x2:-2, y2:3 }

const slope = (y2 - y1) / (x2 - x1);

alert("The slope is equal to " + slope);
Omar ;)
Omar ;)OP14mo ago
ah okay, thanks
ἔρως
ἔρως14mo ago
remember to check for NaN before displaying the result by the way, don't just add a div with a button and then attach a click event handler to it use a form instead of the div, and set the type="submit" on the button then, in javascript, handle the submit event
Want results from more Discord servers?
Add your server