-3

I wrote a very simple addition function. The first code was written with the traditional function. But I want to write the same code with arrow function, but a red error appears under the arrow sign and when I want to see the result with console.log, I get a meaningless error. Why? and How do I write this function in its simplest form with the arrow function? Thanks!!

My code

    // First way

function total(a, b) {
  return a + b;
}

console.log(total(5,2)); // Will print total "7"


// Second way

total(a, b) => {
  return  a + b;      // **Will I get an error when I print console.log(total(5,2))! Why?**
}
Mirza
  • 17
  • 4
  • 3
    `let total = (a, b) => ...` - the main issue was the missing `=`, but you should always explicitly declare your variables with `let`/`const`. Voting to close as a typo. More info at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#examples) – Rory McCrossan Sep 18 '22 at 12:06
  • 1
    Hey Rory, Thank you so much! My conclusions from what you said: When I write with the traditional method, I don't need to assign const or let to the total variable. But since I'm writing with arrow, I need to assign const or let. Well, when I want to write with arrow function, the simplest version is "const total = (a, b) => a + b;" is this, is it correct? – Mirza Sep 18 '22 at 12:23
  • Yes that's correct. – Rory McCrossan Sep 18 '22 at 12:25

3 Answers3

1

you are having the syntax error, for an arrow function you need to provide the variable which stores the value for the function here(total), then the parameters that needs to be passed a,b and then your function body.

const total = (a, b) => {
  return  a + b;      
}
console.log(total(5,2));
Tanish Gupta
  • 400
  • 2
  • 8
  • 20
0
total(a, b) => {
  return  a + b;   
} 

this is error because you have not declared any variable.arrow function takes a variable then parameter and then the logics that you want to put .

so make your arrow function like :-

let total = (a,b) =>{
return a+b;
}
Rahul Mohanty
  • 342
  • 3
  • 9
0

There is a syntax error.

This is the correct way:

const total = (a, b) => {
  return a + b;
}

or

const total = (a, b) => a + b;