OneBite.Dev - Coding blog in a bite size

square a number in javascript

Code snippet for how to how to square a number in javascript with sample and detail explanation

JavaScript, an essential language in web development, offers different ways to perform mathematical operations. This article will guide you through step-by-step instructions on how to square a number using JavaScript.

Code Snippet

Here’s the simple script to square a number in JavaScript.

function squareNumber(num) {
    return num * num;
}

console.log(squareNumber(5));  // Outputs: 25

In this code snippet, we created a function squareNumber that takes one parameter num. This function returns the result of the parameter multiplied by itself. We then call this function with a number and output the result.

Code Explanation

Let’s break down the code further:

  1. function squareNumber(num) { return num * num; } – This is a function declaration. The function squareNumber is being defined here. It has one parameter num, which is the number to be squared.

Inside the function, num * num; is the mathematical operation that squares-the number. It simply means multiplying the number by itself. The return keyword sends the result back to where the function was called.

  1. console.log(squareNumber(5)); – Here’s where we’re calling the function. The number inside the brackets i.e. 5 is the argument. This means we’re asking the function to square the number 5. The result, 25 is being printed on the console with the help of console.log().

That’s it! You’ve just learned how to square a number in JavaScript. Remember, a bit of practice goes a long way when it comes to coding. So, try squaring different numbers and see what results you get!

javascript