-1

I am struggling with understanding the following.

I have the following code:

const myFunction = function (error) {
  console.error(error)
  callSomething();
}

As you see I am using a function called callSomething() and it works but as soon as I use arrow function then callSomething() :

const myFunction = error => console.error(error);callSomething();

Then callSomething() is not called.

3Dos
  • 3,210
  • 3
  • 24
  • 37
Hamed Minaee
  • 2,480
  • 4
  • 35
  • 63
  • 1
    How/where do you define `ElasticSearchCallError`? – TimoStaudinger Nov 15 '17 at 15:10
  • Please post your exact code, not some pseudo "do sth". – Bergi Nov 15 '17 at 15:11
  • Why do you want to use arrow functions if they don't work? [They are different](https://stackoverflow.com/q/34361379/1048572), and there are cases where only either of them fits. – Bergi Nov 15 '17 at 15:12
  • Remove the `;` in your arrow expression (Here: `(error);`). A proper editor would've thrown an syntax error on there. – Cerbrus Nov 15 '17 at 15:13
  • 1
    This sample should first and foremost throw syntax errors. Please show something that at least *could* work, and then give us the exact error message you get. – deceze Nov 15 '17 at 15:13

1 Answers1

0

From the docs

Omitting the curly braces implies using an expression as the MDN documentations says

Basic Syntax

(param1, param2, …, paramN) => { statements } (param1, param2, …,
paramN) => expression // equivalent to: (param1, param2, …, paramN) =>
{ return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements } singleParam => { statements }
singleParam => expression

// The parameter list for a function with no parameters should be
written with a pair of parentheses. () => { statements }

Expressions versus statements in Javascript

Explanations

So basically the following should work as callSomething() is an expression

const myFunction = error => callSomething(error)

With statements not being expressions (such as multiple expressions for exemple) the curly braces are mandatory

Example 1

const myFunction = error => {
  // other statements such as
  console.error(error);
  callSomehting(error);
});

Example 2

throw error is a statement but not an expression!

const myFunction = error => {
  throw error;
});
3Dos
  • 3,210
  • 3
  • 24
  • 37
  • Not that "an expression" would necessarily fail here… – deceze Nov 15 '17 at 15:14
  • This doesn't explain why the OP's code doesn't work. not does this explain what the significance of "expressions" is. – Cerbrus Nov 15 '17 at 15:14
  • My bad, `ElasticSearchCallError(error);` is an expression indeed – 3Dos Nov 15 '17 at 15:21
  • As OP tagged this as accepted answer, I suspect, he used more than a single function call resulting in multiple statements requiring the curly braces... – 3Dos Nov 15 '17 at 15:25