parti
parti

Reputation: 215

Access object variables outside of a function

I am trying to get variable values that are returned as an object from within a js function. What am I doing wrong?

function myFunction() {
  vara = 1;
  varb = 2;
  var myobj = {'vara': vara, 'varb': varb};
  return myobj;
}
myFunction();
var getA = myobj.vara; // Console is saying can't find variable myobj

Upvotes: 1

Views: 621

Answers (2)

xdeepakv
xdeepakv

Reputation: 8125

When you create a variable inside a function, It has local scope inside a function. It can not be accessed outside. Once you return, you have to assign some variables to access those properties.

function myFunction() {
  vara = 1;
  varb = 2;
  // Local functaional scope
  var myobj = { vara: vara, varb: varb };
  return myobj; // return here
}
const obj = myFunction(); // capture return in obj variable

var getA = obj.vara; // access the value

console.log(getA)

Upvotes: 0

Luís Ramalho
Luís Ramalho

Reputation: 10208

You'll have to assign the returned object from the myFunction() to a variable, then you can access it, something like the following:

function myFunction() {
  vara = 1;
  varb = 2;
  var myobj = { vara: vara, varb: varb };
  return myobj;
}

var obj = myFunction(); // Assign the return of the function to a variable
var getA = obj.vara; // Then you can access it

console.log(getA)

Upvotes: 1

Related Questions