How to Add Numbers in JavaScriptWe will understand how to add numbers in JavaScript in this article. JavaScript NumbersIn JavaScript, the numbers are stored in double-precision 64-bit binary format IEEE 754. Methods utilized to add two numbersFollowing are the methods that we can utilize to add two numbers in JavaScript:
We will understand each method one by one. Utilizing the + operatorThe + operator is utilized to add numbers in JavaScript. Demonstration:We will utilize the + operator for adding two numbers. Code: Output: We can witness that the two numbers are added. Utilizing functionWe will utilize a function to add numbers in JavaScript. Demonstration:We will define a function, give it a name and add two numbers. Code: Output: We can witness the addition of two numbers utilizing a function in the output downwards. Utilizing arrow functionWe will define an arrow function to add two numbers. This function is utilized to add parameters and returns the sum. Syntax of arrow function: Code: Output: Here in the output downwards we can witness the addition of two numbers utilizing an arrow function. Utilizing addition assignment (+=) operatorWe will utilize the addition assignment (+=) operator. This operator sums up the left and right operand values. After that, it gives the addition result to the left operand. Code: Output: Here is the output in which we can witness the utilization of addition assignment operator to get the sum of two numbers. Addition of floating-point numbersFloating-point numbers are decimal numbers that contain decimal points, such as 2.421. Demonstration-1:We will add two floating-point numbers in this demo. Code: In the above JavaScript code, "a" and "b" are two variables that contains floating-point value. The "c" is another variable that stores the result of sum of "a" and "b". Output: We can witness that the output of "a" and "b" is 8.151 which means decimal points are retained. We can utilize the "toFixed" function to control the decimal point number. Syntax: toFixed() is the function and 3 is the value up to which we want to fix the number of decimal points. Demonstration-2:We will add two numbers and utilize the toFixed() function to control the decimal points. Code: Output: We can clearly witness that the decimal point is fixed to 2 even if we have utilized a 3-decimal point number. Demonstration-3:We can get the result of adding two numbers with more precision which means we can round numbers with the help of the Math.round() method. Code: Output: We can witness that the decimal point is removed and we have got the round number. Conclusion:We have understood how to add numbers in JavaScript in this article. We can add numbers utilizing + operator, utilizing function, utilizing arrow function and utilizing addition assignment (+=) operator. Next TopicJavaScript Array Exercises |