DEV Community

Arina Nasri
Arina Nasri

Posted on

Javascript Variables

Variables are named containers for data in Javascript. With variables, we are able to store values in memory and then enact specific actions on those values whenever necessary. Variables are able to hold simple and complex data types.

We create variables using declarative keywords. The declarative keywords include key, let, and const. You create the variable by first typing out one of the declarative keywords and then whatever you'd like to call your variable. To assign it, you then type an equal sign(=) and set it to whatever data type you'd like.
Image description

Each variable name is case sensitive meaning lastname and lastName would be different so when you refer to the variable later, make sure to refer to it properly. All variable names should be written in camelCase so lastName is proper notation whereas lastname is not.

Var, let, and const are the three declarative keywords. When Javascript was first created, the only way to create variables was by using var, however, var was error-prone, specifically when it came to hoisting and being scoped to specific blocks of code. Due to this, let and const were made.

Var and let are reassignable, but const is not.
Image description

Let and const can not be hoisted. Hoisting refers to the process where the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code (MDN Web Docs). With var, you can reference the value before it is declared, but you can't do that with let and const. Only the variable name is hoisted to the top and not their assignment. Variables only get hoisted inside their own scope.
Image description

Var is not scoped to if blocks or loop blocks, but let and const are scoped to both.
Image description

To summarize, variables are named containers for data in Javascript and an essential to master when coding. Variables can hold simple or complex data types and must be written in camelCase. The three declarative keywords for variables are var, let, and const. Var is reassignable, but is not scoped to if blocks or loop blocks. Let is reassignable and scoped to if blocks and loop blocks, but it is not hoisted. Const is not reassignable or hoisted, but it is scoped to if blocks and loop blocks.

References:
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Top comments (0)