In a YouTube video (https://www.youtube.com/watch?v=iLWTnMzWtj4&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=3), it was said that when we run the JS code, a global execution context is created. Execution context is created in two phases: Memory Creation and Code Execution phase.
In the memory creation phase var are assigned undefined and whole function body is assigned to the function name something like this:
a: undefined
foo: {whole function body}
A new Execution Context is created for each function WHEN THEY ARE INVOKED. Then the memory is assigned to its local variables.
The question is if memory is not assigned to a function local variables until it is invoked, then why do they throw SyntaxError if we make a syntax mistake in a function and the whole code doesn't run at all?
for e.g. the below code throws SyntaxError and doesn't run at all whereas the memory is allocated to foo after it is invoked which is after the first line
console.log("hello");
function foo() {
vard world = "world";
console.log(world);
}
foo();
Can anyone please explain when does the JS engine knows that there is actually a SyntaxError? Obviously it is not after the function is invoked because even if we don't invoke the function at all, the SyntaxError will still be thrown
Does the Global Execution Context gets created if there is a syntax error in the code? What is the sequence? Which happens first and later means the Global Execution Context gets created first or the parsing the code to machine language is done first?