I should start by noting I am extremely inexperienced with Javascript.
I have a program in javascript that declares a variable right at the start, in global scope, as follows
var psycho_pairs
Later I write to this variable with the following
async function experimentInit() {
psycho_pairs = [];
let num_samples = 10;
let num_repeats = 4;
let increment = (high_bound - low_bound)/(num_samples);
for (let i = low_bound increment/2; i < high_bound; i = increment){
let f2_low = Math.max(i - 1,low_bound);
let f2_high = Math.min(i 1,high_bound);
let f2_incr = (f2_high - f2_low)/(num_samples);
for (let j = f2_low; j < f2_high - f2_incr/2; j = f2_incr){
for (let n = 0; n < num_repeats; n ){
psycho_pairs.push([i,j]);
}
}
}
console.log(psycho_pairs);
}
That final line prints what I expect it to, so thats good. Later on in the program I have the following lines of code
function routine_2afc_stimRoutineBegin(snapshot) {
return async function () {
console.log(psycho_pairs);
let rand_ind = Math.floor(Math.random() * psycho_pairs.length)
var cur_pair = psycho_pairs[rand_ind];
var psycho_pairs = psycho_pairs.splice(rand_ind,1);
console.log(cur_pair);
}
}
In this case the first console.log
just prints undefined
and the program throws the following error
TypeError: Cannot read properties of undefined (reading 'length')
It seems to me that the variable psycho_pairs
is being updated locally within the first function, but that isn't being reflected in the global workspace, so in the second function the variable is still just undefined. However, I thought the var
keyword explicitly creates global variables that are mutable inside of functions? What mistake have I made with the initialisation/creation of this variable?
CodePudding user response:
In Javascript var
variables have a strange property where they are initialized at the top of the block, and then set wherever you set them. In your second function, you are re-declaring psycho_pairs
, bringing a local variable called psycho_pairs
into scope, even though the declaration is below your console.log.
You can read more about it here: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting