JavaScript
is a widely used programming language, which is very popular in web development
as well as on the server side. We can easily do various mathematical tasks with
JavaScript. In today's blog, we will see how to "square" a number
with the help of JavaScript. For example, if we multiply a number by itself, we
get its square. For example, 3×3 = 9, so the square of 3 is 9. Let's see the
above task through code below –
Problem
– Find the "square" of any number through JavaScript?
Code –
function squareNumber(number) {
return number * number;
}
// Example
const num = 5;
const result = squareNumber(num);
console.log(`The square of ${num} is: ${result}`);
Explanation
-
- First, we created a function called squareNumber. The function of this function is to take a number as input and return it by square.
- By doing number * number in the function, we get the square of that number.
- We declared a constant called num where we put the number 5. Then I passed the variable num to the squareNumber function and saved the result in another variable called result.
- Finally, I showed the square of the number through console.log().
Bookmark
the website! If you like the post and don't forget to share it with your
friends so that they don't miss it. Be sure to like and comment so that we can
constantly come up with new problems along with solutions and if you have any
coding-related problems, let me know in the comment box and I will try to solve
them, InshaAllah.