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.
-
1Does this answer your question: stackoverflow.com/questions/26593302/…dale landry– dale landry2021年02月23日 23:56:40 +00:00Commented Feb 23, 2021 at 23:56
-
Does this answer your question? What's the fastest way to square a number in JavaScript?Markus Zeller– Markus Zeller2021年03月14日 10:45:59 +00:00Commented Mar 14, 2021 at 10:45
2 Answers 2
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
Comments
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