Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion Validation and Handling Errors

Mark Warren
Mark Warren
19,252 Points

'let' instead of 'const'

In this particular instance why are we using 'let' instead of 'const'? Will 'const' not match scope if the variable is declared outside of a try... catch statement?

3 Answers

const are constants, they can not be changed once declared. let are variables, and can be changed once declared.

Noah Nordqvist
Noah Nordqvist
10,246 Points

Like Zimri states, const can not be changed once declared, while let can. In the case of the sections after "New Article Validation Errors" of the instructions, which I assume you are referring to here:

Before the changes in these sections, we merely declared article as a const, like so:

   const article = await Article.create(req.body);
   res.redirect("/articles/" + article.id);

... and that was fine. Since no further assignments where needed, we could keep article as a const. But, now, we're also opening up the possibility of a second assignment in the updated catch method:

/* POST create article. */
router.post('/', asyncHandler(async (req, res) => {
  let article;
  try {
    article = await Article.create(req.body);
    res.redirect("/articles/" + article.id);
  } catch (error) {
    if(error.name === "SequelizeValidationError") { // checking the error
      article = await Article.build(req.body);
      res.render("articles/new", { article, errors: error.errors, title: "New Article" })
    } else {

    }  
  }
}));

Since article first gets assigned in try, we can't then assign to it in catch when things inevitably go wrong. We'd get an error as we tried to assign to a constant. So, const is out. Unfortunately, we can't just declare a let variable in the try method:

  try {
    let article = await Article.create(req.body);
    res.redirect("/articles/" + article.id);
  }

... because let (and const) are both block-scoped. Meaning it wouldn't carry over to the catch block. Which is why we're now declaring let article above the try-catch block and then assigning as we go through.