Sign in Registration
ArticlesDownloadServicesAudioContacts
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

Communication

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

Share this

Subscribe to