Copy Sign to Number

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28218{{"`Copy Sign to Number`"}} javascript/data_types -.-> lab-28218{{"`Copy Sign to Number`"}} javascript/arith_ops -.-> lab-28218{{"`Copy Sign to Number`"}} javascript/comp_ops -.-> lab-28218{{"`Copy Sign to Number`"}} end

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:

  1. Use Math.sign() to check if the two numbers have the same sign.
  2. Return x if they do, -x otherwise.

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.

Other JavaScript Tutorials you may like