0

I'm trying to set an object value to a function call using another value (array) as its parameter, however, for some reason the value comes back as undefined, I'm then trying access that value right after that. It's inside an IIFE.

I am unsure why this is happening because to the best of my knowledge the scoping is okay and the value should be initialized and executed by that time?

Here's a simplified example:

(function(){
 var minefield = [1,2,3,'M',4,5,6];

function findMachine(minefieldMachine) {
  return minefieldMachine === 'M';
}

  var terrain = {

    start:{initialMachienLocation:minefield.findIndex(findMachine)}, 
    currentMutable:{mutableIndex:terrain.start.initialMachineLocation}//Error: "Uncaught type error cannot read property 'start' of undefined"
//Why isn't the above accessing the value declared in terrain.start.initialMachineLocation through the function call?

  }
}());

However, doing this works, out of context from above:

function findMachine(minefield){return minefield === 'M'}
[1,2,3,'M',4,5,6].findIndex(findMachine);
//above returns the proper index value, 3.
1
  • you cant access to any function or var inside, seems is private... Commented Nov 16, 2017 at 18:57

1 Answer 1

3

This has nothing to do with the function.

What you are attempting to do is, essentially, this:

var foo = {
    a: 1,
    b: foo.a
}

You need to consider the order of operations.

The object literal constructs an object which is then assigned to the variable foo.

… except that while the object is being constructed, you are trying to read the value of foo. It doesn't have one yet, so this fails.

You need to do this in two steps.

var foo = {
    a: 1,
}
foo.b = foo.a;
Sign up to request clarification or add additional context in comments.

Comments

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.