0

Some of you made some awesome javascript courses which I follow eagerly in the adventure to become a better developer.

One of these courses was about EcmaScript6 const and let variables and the Try and Catch statement. So as a curious junior developer I tried it myself by declaring an arrow function in a constant and trying to change the constant:

const userValidation = (userValid) => userValid == true ? "You may enter" : "You may not enter, sorry.";

try {
  var userValidation = function(userID) {
    //Execute some code which ofcourse will never execute
  }
}
catch(err) {
  console.log("Woops, something went wrong.");
}

console.log(userValidation(false));

The behaviour which I expected was the error message: "Woops, something went wrong." because I already declared the constant "UserValidation". But that was not what was happening, instead the console just gave the error and dies:

Console error

What am I doing wrong?

  • 1. You're trying to re-assign to the constant variable `userValidation` here 2. You're declaring the variable `userValidation` again – Ramya Oct 01 '18 at 12:17
  • Exactly. But because it's inside a try and catch statement the error it creates should be catched and the message: "Woops, something went wrong." should be logged to the console. Leaving the rest of the script running. But instead it spits out the error regarding wether or not it is inside the try and catch statement and killing the script. Am I not understanding the goal of the try and catch statement, or is there something wrong in my statement? – Melvin Idema Oct 01 '18 at 12:18
  • 1
    Remember you can catch programmer-generated or runtime errors only. This error you're trying to catch is a compile time error. Also why would you want to catch this type of error? – Ramya Oct 01 '18 at 12:24
  • 1
    Found this related post: https://stackoverflow.com/questions/5963045/can-syntax-errors-be-caught-in-javascript – Ramya Oct 01 '18 at 12:26

1 Answers1

1

try, catch statements are used to catch runtime errors, but this SyntaxError is detected while the Javascript is being parsed, before it is run. This is because you are not reassigning the (const) variable here but redefining it with a different identifier (var). If the code were

const userValidation = (userValid) => userValid == true ? "You may enter" : "You may not enter, sorry.";

try {
  userValidation = function(userID) {
    //Execute some code which ofcourse will never execute
  }
}
catch(err) {
  console.log("Woops, something went wrong.");
}

without the var identifier, then this would become a runtime error. The code would be attempting reassign the const variable and your catch statement would execute.

  • Aah oke. Thank you so much for the clear answer! Didn't knew the difference between runtime errors and parsing errors or was even aware of their existence. Thanks again! – Melvin Idema Oct 01 '18 at 13:12