skip to Main Content
// snippet for syntax error
console.log("hello stackoverflow!");
const test3;
test3='❌'
console.log(test3)

var name="me"
console.log(name)

I understand that JS is synchronous and execute code line by line, but why over here hello stackoverflow! is not getting printed, as the error is in the next line.

Also, Consider another snippet below

// snippet for typeError
console.log('hello stackoverflow!')
const test3 = '✅'
test3='❌'
console.log(test3)

var name="me"
console.log(name)

This snippet prints the `hello stackoverflow`. Which is different behavior from the first snippet.

Can Anyone help me why it’s happening and who identifies these errors in JS and does that happen before memory allocation in JavaScript?

I was expecting console.log() to get printed in both scenarios which is not happening in the first snippet.

2

Answers


  1. The order things happen in JS is not strictly linear.

    Syntax errors are scanned for before execution begins.

    Login or Signup to reply.
  2. Interpreted language doesn’t mean that it is executed line by line like a shell script. Many things happen before the first line is getting executed like variable space allocation.
    If you define a variable in one way but use it another way the code execution won’t start at all.
    Please read about the code lifecycle: https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search