James Beaupry
James Beaupry

Reputation: 1

JavaScript :Multiple variables returned from a global function isn't able to be accessed by object

I'm trying to have the location properties of my 'BB' object be set by my setLoc() function, but when I check the values in the debug console they come up as undefined. Other than that there are no errors being thrown in the console. Where have I gone wrong?

I've tried adding the function as a method to BB, but that brought additional errors.

Here's the two code blocks:

var loc = function setLoc(){
  let x;
  let y;
    if(random(1,2) == 1){
      x = random(-1000, 0);
      y = random(-1000, 0);
    }
      else{
        x = random(0, 1000);
        y = random(0, 1000);
      }
    return [x, y];
}

var bb = {
  done : false,
  hp : 10,
  fuel : 10,
  location : {
    x : loc[0],
    y : loc[1]
  },
}

Upvotes: 0

Views: 28

Answers (1)

Nino Filiu
Nino Filiu

Reputation: 18523

You define loc as a function. It should be a value - to do so, use an IIFE instead:

var loc = (function setLoc() { ... })();

Upvotes: 1

Related Questions