Pyram
Pyram

Reputation: 87

Set variables out of anonymous functions in Javascript

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

Upvotes: 0

Views: 104

Answers (3)

Alex McMillan
Alex McMillan

Reputation: 17952

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

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

Upvotes: 1

Khauri
Khauri

Reputation: 3863

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

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65845

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

Upvotes: 5

Related Questions