Why do I get an error when I write a traditional function as an arrow function?

Viewed 41

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?**
}
3 Answers

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));
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;
}

There is a syntax error.

This is the correct way:

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

or

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