0

This is my first post on the forum so please be kind.

The following is my code:

var powerValue = 0;

  for(let l = 0; l < array.length; l++) {
    let path = pathfind.findPath(coordX, coordY, powerSourceIndex[l][0], powerSourceIndex[l][1], function(path) {
      if(path !== null) {
        powerValue = 1;
        console.log("set value = " + powerValue)
      }
    });
    pathfind.calculate();
    console.log("second read = " + powerValue)
  }

I know that powerValue is indeed being set to 1, because I see the "set value = 1" on my console. However, I also see "second read = 0"

I am aware that similar issues have already been asked, but alot of these seem to be regarding asynchronous functions. Similar to an async, this function seems to have some kind of separated scope, but it isn't exactly an async.

I have done the research, believe me, I tried! But due to my lack of understanding of this specific issue, I can't seem to find a solution the problem.

Any help would be appreciated!

TLDR: I know powerValue is being set to 1 due to my console logging, but it is 0 at "second read"

Wes
  • 1
  • I assume you saw first `second read = 0` and then `set value = 1` ? – Fullstack Guy Feb 02 '19 at 05:15
  • It does seem like it may be an asynchronous function. What is the output if you console.log path? (Not in the function passed as an argument but the one defined with let) – BMcV Feb 02 '19 at 05:17
  • @AmardeepBhowmick Ah my apologies... The unnamed function is called when `pathfind.calculate()` is called as per the library. So, `second read` appears after `set value` @BMcV it is not null, if that's what you're thinking. – Wes Feb 02 '19 at 05:27

2 Answers2

0

let pv = 0;
for (var i=0; i<5; i++) {
 let path = function() {
  pv = 1;
  console.log("set value = " + pv);
  };
 path();
  console.log("second read = " + pv);
}

Just trying to achieve without using your library. The value you'll get here correctly because running the path() sets the global variable value to 1.

Abhishek
  • 382
  • 1
  • 6
0

Variables declared in the self executing function are, by default, only available to code within the self executing function.

Read More

If you want your variable to be modified outside the function as well, do not use a self-executing function. Thus, you'd do, for example:

function is_path_null(path) {
  if(path !== null) {
    powerValue = 1;
    console.log("set value = " + powerValue)
  }
}
//...
let path = pathfind.findPath(coordX, coordY, powerSourceIndex[l][0], powerSourceIndex[l][1], is_path_null(path) {
  //...
}
pathfind.calculate();
is_path_null(path);
console.log("second read = " + powerValue)
Cedric Ipkiss
  • 5,662
  • 2
  • 43
  • 72