Before you say "The variable must be declared globally, and not inside the function", it already is .
In a Node/Express setup I retrieve the value of a the variable loggedIn
from the BE. This is 1 if the user is logged in, and 0 if the user is not. The value should determine which header is loaded.
This is the code, let's say user A is logged in:
let loggedIn = 0 // VALUE IS DECLARED OUTSIDE THE FUNCTION LIKE IT SHOULD BE
async function checkLoggedIn () { // THE FUNCTION TO CHECK IS USER IS LOGGED IN
const res = await fetch('users/authenticate')
const loggedInString = await res.json()
loggedIn = parseInt(loggedInString)
console.log(loggedIn) // THIS LOGS OUT '1' LIKE IT SHOULD BECAUSE USER A IS LOGGED IN
}
checkLoggedIn() // WE RUN THE FUNCTION
console.log(loggedIn) // THIS LOGS OUT '0' EVEN THOUGH USER A IS LOGGED IN
For the life of me, I can't figure out why the value of loggedIn
is 0 outside the function.
One thing to note is that the log first logs out the value of loggedIn
outside the function (i.e. the second instance in the code). Why is that? The function is being called before the console.log(loggedIn)
outside the function is run.
This is what the browser logs out when the code is run:
0 (index):12 // VALUE OUTSIDE THE FUNCTION
1 (index):7 // VALUE INSIDE THE FUNCTION
Line 12 is logged out before line 7, which I don't understand.
I am sure there is a simple explanation, but I just don't get it.