I'll try to make this concise...
With all the ES6 hype, I feel like using the var
keyword is becoming more and more frowned upon by the JS community at large. Due to this (perceived) general consensus, I've been getting in the habit of avoiding using var
in lieu of the newer const
and let
keywords for creating variables.
Below is an example of a block of code I wrote where I couldn't use const
because I wanted to redefine a variable. I was also using async / await
so all the code was in the same block-level scope
, which apparently prevents you from redefining let
variables either. So my only option was to use var
(or create yet another let
variable).
Here's the code. Saving a new user account to a MongoDB via Mongoose...
router.post('/signup', async (req, res, next) => {
const { email, password } = req.body;
const user = await userModel.findOne({ email });
if (user) { res.send('Email already in use.'); return; }
// here is where the issue occurs - use var instead?
let newUser = new userModel({ email, password });
let newUser = await newUser.save();
console.log(newUser); // just checking everything works
res.send({ message: 'New user account created!' });
});
MDN mentions this behavior... with just ONE SENTENCE! That's not helpful. :( And then they go on to discuss hoisting behavior, which isn't my issue, or at least I don't see how that's related. MDN Source Here.
So in conclusion...
Is this an example of an instance when
var
would be the most appropriate keyword to use?If this isn't a time for using
var
, is there any instance whenvar
is the most appropriate keyword to use, even in the age of ES6 (7, 8, etc)?
Disclaimer: I know I don't absolutely need to save those variables, but in my opinion, it's worth the trade off to write slightly more verbose code that's also more readable and understandable. I'm fine with using var
, I just though this was an interesting case.