Sign in Registration
ruen

What is the difference between declaring variables in JavaScript, what to choose - window, var, let, const

JavaScript allows you to declare variables in a variety of ways. This language is being improved just like everything else in the IT field. The ability to declare variables in a new way has been added to the language specification.

chem-otlichaetsya-obyavlenie-peremennyh-v

Initially, there were two ways to declare JS variables :

- using the window prefix , then the variable is considered global in the window scope;

- using the var keyword , the variable is available in the current scope, for example, in a function.

But the new specification adds new ways:

- the let keyword , declares a variable with limited visibility, only in the current block (the block is usually curly braces {});

- const keyword , differs from let in that a variable cannot be changed.

Above we briefly discussed how var, let, const and window differ. What to use in practice depends on the specific needs of the project, but it is important to remember that only modern browsers have let and const support . These innovations were driven by security requirements and other standards.

Some guidelines what to choose - var, let, const or window in JavaScript :

- it is always recommended to declare a variable with the smallest scope ;

- it is not recommended to use window global variables with full window scope ;

- you should try to use const if changing the variable is not expected (better performance) ;

- use let when const is not possible ;

- use var otherwise, this might be useful in some scenarios .

Comments (0)
For commenting sign in or register.

Latest articles

Popular sections

Eqsash (Tools)

Android app - VK LAST USER ID, отучитель от зависимости и т.д.:
Available on Google Play

Amessage (Communication)

Login to the web version
Android app:
Available on Google Play

Share this

Subscribe to

YouTube

Books

IT notes - In simple language about the most necessary things (HTML, CSS, JavaScript, PHP, databases, Drupal, Bitrix, SEO, domains, security and more), PDF, 500 p.