Ask coding questions

← Back to all posts
[JS] Why variable no global!!!1!!1!!1!!!!
MrVoo

I have no idea how any of this code works, I just stole it from stackoverflow. Anyway, I'm trying to set k to data but it says k isn't defined, send help?

Answered by SixBeeps [earned 5 cycles]
View Answer
Voters
sobakarooted
MrVoo
Comments
hotnewtop
TheDNAHero

You need to define the variable outside of the function, so I would recommend doing
var k;
function makeLevel(name) {
fetch('levels/'+name+'.json').then(response => {
return response.json();
}).then(data => {
console.log(data);
var k = data;
}).catch(err => {
return undefined;
});
};

makeLevel('levelName');
console.log(k);

MrVoo

@TheDNAHero Its just always equal to undefined if I do that, the console.log(data) shows the correct thing though...

TheDNAHero

@MrVoo you have the console.log statement before you declare the var

MrVoo

@TheDNAHero That doesn't matter though?

TheDNAHero

@MrVoo Just try it

MrVoo

@TheDNAHero Doesn't do anything, no reason to.

SixBeeps

@TheDNAHero This answer is halfway there.

@MrVoo The reason why you might be seeing those undefineds is likely because you're accessing it before the fetch completes. Not only do you need to declare the variable globally, but you also need to make sure the fetch has completed before accessing it. Something like this?

MrVoo

@SixBeeps It still sets k to undefined :(

SixBeeps

@MrVoo What's the value of ready? If it's false, then either your fetch failed or it hasn't finished yet.

MrVoo

@SixBeeps I found something that worked :} You could've been right too though, and I wasted your time, so you're c o r r e c t now