0

I am trying to get a value outside of an anonymous function in Javascript. Basically, I want this function to return 4. I feel like there is an easy fix but I am unsure. Thanks!

function a(){
  var x = 1;
  ()=>{
    x = 4;
  }
  return x;
}
Pyram
  • 45
  • 5

3 Answers3

5

You have to invoke the inner function, but since it's anonymous, it has to become an immediately invoked function expression. And, since there is only one statement in the anonymous function, you can omit the curly braces if you like.

function a(){
  var x = 1;
  (() => x = 4)();
  return x;
}

console.log(a());
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
1

Your example defines a function, but nothing is running it. Perhaps try using an IIFE:

function a(){
  var x = 1;
  (()=>{
    x = 4;
  })();
  return x;
}
Alex McMillan
  • 13,847
  • 6
  • 47
  • 76
1

Pretty weird that you'd want to do this, but just make sure you call the inner function. This can be done using the Immediately-invoked function expression syntax.

function a(){
  var x = 1;
  (()=>{
    x = 4;
  })()
  return x;
}

console.log(a());
Khauri
  • 3,329
  • 1
  • 6
  • 17