JavaScript SquareWe will understand the JavaScript square in this article. Squaring a numberWhen the number is multiplied by itself then it is called squaring a number. Example: Let us consider the number "a". We can multiply the number "a" by itself like this (a * a). In mathematics, it is represented as the following: a^2 (It is called a is to the power 2.) Squaring a number has many practical applications such as finding the distance, area, etc. In JavaScript, we can multiply a number by itself by utilizing various methods, which are given below:
Utilizing the multiplication operatorThe easiest way to square a number is to utilize the multiplication operator. Let us understand how to utilize the multiplication operator with the help of the demonstration. Code: Output: Here is the output in which we can witness the square of the number "6". Utilizing a functionThe next way to square a number is to construct a function. We will create a function in the demonstration below which will take the number as an input. This function will return the square of the number. Code: Output: Here is the output where we can clearly witness a square of the number "10" done with the assistance of constructing a function. Utilizing the Math.pow() methodAnother way to multiply the number by itself is to utilize the Math.pow() method. It is the built-in Math object in JavaScript which is utilized to do various mathematical functions. The Math.pow() is one such method that helps in finding the power of a number. Syntax: This method consists of two arguments which are as follows: number: It is the base number. exponent: It is the power of the base number which will be 2 because we want to find the square. Code: Output: We can gaze at the square of the number "9" done with the assistance of Math.pow(). Utilizing the exponentiation operatorThe exponentiation operator (**) is another method to multiply a number by itself. Syntax: Code: Output: We can clearly witness the multiplication of the number "5" by itself in the output given downwards. Squaring an arrayWhen the elements present in the array are squared then it is called squaring an array. In JavaScript, we can square an array utilizing various methods, which are given below:
Utilizing the map() functionThe map() function is utilized with the exponentiation operator (**) to square an array. We will understand the utilization of the map() function to square an array with the help of the following demonstration. Code: Output: Here in the output provided downwards we can witness the square of an array done utilizing map() function. Utilizing the for loopWe can utilize the "for" loop to square an array. We will understand the utilization of the "for" loop for squaring an array with the assistance of the following demo. Code: Output: Here in the output provided downwards we can witness the square of an array done utilizing for loop. Conclusion:
Next TopicNested Ternary Operator in JavaScript |