For further actions, you may consider blocking this person and/or reporting abuse
Read next
Cutting-Edge Features Every IPTV Solution Should Have
Hiredeveloper -
How Lotto Software is Revolutionizing the Online Lottery Industry
Hiredeveloper -
Discover the Best Asian Supermarket in the UK for Authentic Groceries
thomaserick -
Shop Authentic Asian Groceries Without Leaving Your City
martinwalt -
Top comments (3)
You can and should use
var
in many situations! If you're writing code that will need to run on older browsers (i.e. any code that isn't being transformed by a tool like Babel),var
is the only available keyword for variable declaration. You should declare your variables. Although JavaScript doesn't require you to do so, declaring your variables helps you avoid mistakes like accidentally overwriting a variable from an outer scope, or creating a variable at a higher scope than you intended.In newer versions of JavaScript you have access to
let
andconst
. These are nicer thanvar
for a few reasons. For one, they're block-scoped instead of function-scoped, so it's easier to see where you're allowed to use the variable; in most cases just look for the nearest curly braces{
before and after the declaration}
. For another, they help you tell everyone what your plans are for the variable. If you don't want the variable to change, useconst
(remember that if the variable points to an object, you can still update the object's properties, add and remove properties, etc.--and if it points to an array, you can add, remove and change items in the array as well--just so long as you don't try to point it to a different object or array). In most cases, you'll useconst
. If you plan to overwrite the variable, uselet
.There's absolutely nothing wrong with
var
, and we used it just fine for years. So if your project usesvar
, don't sweat it. But if you have the option to uselet
andconst
instead, that's a great way to make your intentions a little more clear. And making your intentions clear is the secret to good code.Great answer!
As Isaac touched on, it can be easier to understand and reason through code that uses
let
and notvar
, which I consider to be one of the most important aspects of writing code. JavaScript's Hoisting is very unintuitive to many people!There can also be specific circumstances where let and var have performance differences in some Browsers and maybe even some versions of NodeJS. However, this level of min/maxing your coding is not something you should worrying about unless you are writing a complex library that needs to a lot of heavy, repetitive tasks like processing large quantities of images or handling a high bitrate datastream from a stock exchange. Some early browser implementations of
let
andconst
were signficantly slower thanvar
, but those were bugs that got fixed.