Variables
A variable in JavaScript is an entity that is used to store data of various types, such as integers, strings, booleans, etc. While writing code, you need to declare variables in which you'll store the data, these variables can be named as abc, ab1, ABC, or a1b, with the only condition being that the variable shouldn't start with a number. The data stored in variables is manipulated in the program to get the desired result.
To declare a variable, you can use the var, let, and consts keywords. The very first keyword introduced to declare a variable is var, followed by the let and const keywords in ES6.
Let's dive deeper into the keywords used while declaring a variable.
Var
The var keyword was initially used in ES6 to declare a variable in a function scope. Function scope is declaring a variable that can only be accessed inside the function. If you want to access it globally, you need to declare it globally.
var variable_name = value/data;
The scope of a variable can be of two types -
- Local variables - The variable that can be accessed anywhere in the program, has to be declared outside the scope.
- Global variables - The variable which has to be declared inside a function to restrict its accessibility outside the main function. Its main objective is to take care of privacy.
ES6 - let and const
It has introduced let and const, which provide block scope in Javascript. Let's read about them. You can also know about ES6 in the upcoming modules.
Let
To improve the functionality of the var keyword, let has come into existence. To create a block-scoped variable, the variable can be accessed anywhere in the program. Using let can avoid the errors that may occur in the var keyword while dealing with variables' accessibility.
Using the let keyword in a block will not affect the variables outside the block, even if both variables have the same name.
Syntax :
let variable_name = value/data;
For example:
Let z = "New";
Const
The const keyword is used to declare variables that have a constant value. Also, const is block-scoped, similar to let. Because the value of const is constant, it cannot be redefined or updated. It has to be initialized at the time of declaration in the program.
Syntax :
const variable_name = constant_value/data;
For example:
const pi = 3.14;
Conclusion
In this article, we have talked about the variables in JavaScript with some well-explained examples. Later, in the upcoming articles, you'll be introduced to more basic features of JavaScript like data types in JavaScript.