Are function declarations non-static?

Viewed 30

I'm not sure if I phrased the question accurately, but up to this point I had always assumed a function declaration in javascript was 'set in stone'.

When I tried to better understand closures (mimicking a simplified version of React's useState), I became unsure of where the 'x' in the following code block was being stored in memory:

function useState () {
    let x = 0;
    return [function() { console.log(x) },function (y) { x = y}];
}

const [getX, setX] = useState(); 
getX()
setX(1)
getX()

So while the useState function returns a getter and a setter as variables "getX" and "setX", where exactly is "x" being stored? In the original declaration of useState? What am I missing here?

1 Answers

When a function (or any block) runs, a new Environment Record is created, which is essentially a mapping of variable names used inside that block to the values they contain. If the variable names can be referenced after the block has finished, this is what is generally called a "closure".

Every time a function runs, a new such record is created. This record closure is where your x gets stored. This is also why you can call your useState multiple times, and have the resulting be separate:

const [getX, setX] = useState(); // Function called; record created
const [getY, setY] = useState(); // Function called again; another record created

Above, since useState runs twice, you've created two environment records / closures, each with a separate binding of x So getX and setX close over the same x, and getY and setY together close over a different x.

If the useState function is never called, x is not stored anywhere, because the record for the useState function is never created.

Related