0

I'm new to javascript and having a little trouble understanding functions.

I need write a function that will receive a single numeric value, square the value and return the value for use. Name the function myUsefulFunction.

I got this far but now cant figure how to square the value

var aNumber = 18;

function myUsefulFunction(x){

    return aNumber = aNumber/x;

}

var amendedValue = doubleNumber(2);

console.log(amendedValue);

Any help would be greatly appreciated.

Obvious_Grapefruit
  • 640
  • 1
  • 8
  • 21
  • 1
    Does this answer your question: https://stackoverflow.com/questions/26593302/whats-the-fastest-way-to-square-a-number-in-javascript – dale landry Feb 23 '21 at 23:56
  • Does this answer your question? [What's the fastest way to square a number in JavaScript?](https://stackoverflow.com/questions/26593302/whats-the-fastest-way-to-square-a-number-in-javascript) – Markus Zeller Mar 14 '21 at 10:45

2 Answers2

1

To square would mean to multiply by itself. Could try this.

const myUsefulFunction= (num) => {
  return num * num;
}

console.log(myUsefulFunction(10));

This will print out 100

kar
  • 4,791
  • 12
  • 49
  • 74
1

In Javascript, there are several ways to square numbers. For instance, there are ways you can get 3 squared.

Math.pow(3, 2) // Math.pow raises the base to any power Math.pow(base, power)

3 ** 2 // ** is a shorthand and does the same thing as Math.pow, base ** power

3 * 3 // just multiplies 3 to itself

All three of these are equally valid, and they're all widely used.

So if you want to create a function that squares a number, you can do something like this:

function myUsefulFunction(x) {
    return x * x
}

Then you can use this function:

console.log(myUsefulFunction(3)) // 9
console.log(myUsefulFunction(4)) // 16
console.log(myUsefulFunction(-5)) // 25
console.log(myUsefulFunction(2.5)) // 6.25
Nick
  • 5,108
  • 2
  • 25
  • 58