To return the sum of two numbers in JavaScript, you can use the following approach:
Step 1: First, define a function that takes two arguments, `a`
and `b`
. These arguments will be the numbers that you want to add together.
function add(a, b) {
// code to add a and b and return the result
}
Step 2: Inside the function, use the `+`
operator to add `a`
and `b`
and assign the result to a variable `sum`
.
function add(a, b) {
var sum = a + b;
// return the sum
}
Step 3: Finally, use the `return`
statement to return the `sum`
variable.
function add(a, b) {
var sum = a + b;
return sum;
}
Here is the complete code:
function add(a, b) {
var sum = a + b;
return sum;
}
var result = add(2, 3);
console.log(result); // Output: 5
You can also use the following shortened version of the function:
function add(a, b) {
return a + b;
}
var result = add(2, 3);
console.log(result); // Output: 5
Comments (0)