Melvin Idema
Melvin Idema

Reputation: 56

Try / Catch won't catch Declared constant error

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?

Upvotes: 0

Views: 332

Answers (1)

Richard Millen
Richard Millen

Reputation: 209

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.

Upvotes: 1

Related Questions