In this article, we are going to learn how to add Two Numbers in JavaScript. Adding two numbers in JavaScript involves performing arithmetic addition on numeric values, resulting in their sum.
There are several methods that can be used to Add Two Numbers in JavaScript, these are listed below:
- Using + operator
- Using function
- Using Arrow function
- Using Addition Assignment(+=) function
Using + Operator
In this session involves we add two numbers in JavaScript using the + operator to perform arithmetic addition on numeric variables, resulting in their sum.
syntax:
x + y;
Example:
In this example, we are adding two numbers using + operator.
var a = 10;
var b = 10;
var sum = a + b;
console.log("Sum",sum);
//Output:
// Sum:20
Using function
In this session involves, we are adding two numbers using a function in JavaScript defining a custom function that takes two parameters, adds them, and returns the result.
Syntax:
function additionFunction(a, b) { return a + b; }
function additionFunction(a, b) {
return a + b;
}
let a = 10;
let b = 10;
let sum = additionFunction(a, b);
console.log("Sum of given numbers is :", sum);
//Output:
//Sum of given numbers is : 20
Using Arrow function
In this topic, Adding two numbers using an arrow function in JavaScript involves creating a concise function syntax that adds parameters and returns the sum.
Arrow function {()=>} means concise way of writing JavaScript functions in shorter way. Arrow functions were introduced in the ES6 version. They make our code more structured and readable.
Arrow functions are anonymous functions i.e. functions without a name but they are often assigned to any variable. They are also called Lambda Functions.
Syntax:
let addition = (a, b) => a + b
Example:
In this example, we are using arrow function to add two numbers.
let addition = (a, b) => a + b;
let a = 15;
let b = 25;
let sum = addition(a, b);
console.log("Sum of given numbers is :", sum);
//output:
//Sum of given number is:40
Using Addition Assignment (+=) Operator
In this approach we use Addition Assignment (+=) operator in which operator Sums up left and right operand values and then assigns the result to the left operand.
Syntax:
Y+=1 gives Y=Y+1
let a = 20;
let b = 10;
// Equivalent to a = a + b
a += b;
console.log("Sum of the given number is :", a);
//OUTPUT:
//Sum of given number is:30