JavaScript concept with a cup of coffee and a laptop

JavaScript Variables

Variable declaration

Variables in JavaScript can be declared in two ways. By using the keywords of “var” or “let”.

var syntax:

Let syntax:

Var is the older way to declare a variable, while let is a newer way. It is recommended to utilize let in modern JavaScript programming, but you will still run into var in various programs. It is important to understand what it does.

Why is let considered to be better than var? The answer is in scope and encapsulation. We will get into scope and how it is used in JavaScript later, but a rudimentary look is prudent here. When the var keyword is used, depending on how and where it is used, the variable and its contents could be available to parts of the program that should not be accessing it. If var is used to declare a variable inside a function, it is available to that function. If it is declared outside the function, it is global. Var is considered to be function-scoped.

By using let, the variable is scoped properly to protect any adverse effects occurring in your program. Let limits access to the variable within the block where it is defined. In JavaScript, a block is defined by curly braces {}. Let is block-scoped.

There is a third way to define a container in JavaScript…const. The const keyword stands for constant. Const is also block-scoped. The difference between const and let is that const variable values cannot be reassigned. Note that they can be mutated. NEED PAGE discussing mutability

Const syntax:

We will cover scoping (function and block) later. The bottom-line is that you should use “let” and “const” as much as possible.

Note: Multiple variables can be declared in a single statement. Instead of…

The following can be written…

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content