Introduction
In this lab, we will explore the copySign function in JavaScript, which returns the absolute value of the first number but with the sign of the second number. We will learn how to use the Math.sign() method to check for the sign of the two numbers and how to conditionally return the appropriate value. By the end of this lab, you will have a better understanding of how to manipulate numbers in JavaScript.
Function to Copy the Sign of One Number to Another
To start practicing coding, open the Terminal/SSH and type node.
The copySign function returns the absolute value of the first number, but with the sign of the second number. To accomplish this:
- Use
Math.sign()to check if the two numbers have the same sign. - Return
xif they do,-xotherwise.
Here is the code for the copySign function:
const copySign = (x, y) => (Math.sign(x) === Math.sign(y) ? x : -x);
You can test the function using the following code:
copySign(2, 3); // 2
copySign(2, -3); // -2
copySign(-2, 3); // 2
copySign(-2, -3); // -2
Summary
Congratulations! You have completed the Copy Sign to Number lab. You can practice more labs in LabEx to improve your skills.