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;
}
2
  • 2
    You never call the inner function. Commented Jul 9, 2017 at 22:10
  • 1
    The anonymous function is never called. But why would you use one at all instead of simply return 4? Please post your actual code. Commented Jul 9, 2017 at 22:11

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

The last set of parenthesis ()` should be on the outside otherwise you'll get an error.
Thanks, updated. This was never the case before fat arrow syntax ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.