DEV Community

Cover image for Variables in JavaScript
Sona Barseghyan
Sona Barseghyan

Posted on

Variables in JavaScript

Hello friends. In this post you can read about variables in JavaScript, find out what they are in general, how to declare them and how to use them. So, a little bit about JavaScript: JavaScript, often abbreviated as JS, is one of the most useful programming languages, one of the core technologies of the World Wide Web. With the help of JavaScript we can create rapidly updating content, control multimedia, animate images, and so on. So, back to our topic: variables. Variables are used to store data values. There are 4 ways to declare variables: var, let, const and nothing. We create variables by giving them relevant names, which are called identifiers.
Identifiers must begin with a letter, can contain underscores and digits, but note that they are case sensitive, so a variable with the same name with just the difference of upper and lower cases are not the same.
Let's see some examples of declared variables in JavaScript. By the way, we can see the output of the value that we gave to the the variable with using function console.log().

Image description

Image description

Actually, both var and let are used for declaring a value, but their difference is that var is function scoped and let is block scoped. What does that mean? A function scoped variable is the one defined within a function which is not accessible from outside the function. A block scoped variable is the one defined within a block which is not accessible from outside the block.
At the same time there are 2 types of scope:local and global. Global variables are those declared outside of a block. We can create such a variable with the help of let. Local variables are those declared inside of a block. We can create such a variable using var.

Image description
See the example above: as we want to print the value of age and gender in the block first, we see the values that are assigned in the block, and when we want to print the values outside the block, we get those outside it.

Nowadays, we are encouraged to use let. The difference between using let and const is that while using let, we realize that in the future the value of the variable declared by let may be changed(reassigned), meanwhile declaring a variable with const means assigning it a permanent value, which cannot be changed in any way.
See an example of a reassigned variable.

Image description

Now see how we get an error while trying to reassign a value stored in const variable.

Image description

We can store a lot of types of data in variables, including strings(text), numbers, boolean values(either true or false), arrays(lists), objects, symbols. Actually, we can find the type of data with the help of a function;

Image description

But let us be satisfied with variables, and further information about functions in my next blog post!:)

Top comments (0)