Professional Documents
Culture Documents
programiz.com/javascript/variables-constants
JavaScript Variables
In programming, a variable is a container (storage area) to hold data. For example,
let num = 5;
In JavaScript, we use either var or let keyword to declare variables. For example,
var x;
let y;
Both var and let are used to declare variables. However, there are some differences
between them.
var let
var is used in the older versions of let is the new way of declaring variables
JavaScript starting ES6 (ES2015).
Note: It is recommended we use let instead of var. However, there are a few browsers
that do not support let. Visit JavaScript let browser support to learn more.
let x;
x = 5;
1/3
You can also initialize variables during its declaration.
let x = 5;
let y = 6;
let x = 5, y = 6, z = 7;
If you use a variable without initializing it, it will have an undefined value.
console.log(x); // undefined
Here x is the variable name and since it does not contain any value, it will be undefined.
You will learn about undefined and other data types in the next tutorial in detail.
It's possible to change the value stored in the variable. For example,
// 5 is assigned to variable x
let x = 5;
console.log(x); // 5
1. Variable names must start with either a letter, an underscore _, or the dollar sign $.
For example,
//valid
let a = 'hello';
let _a = 'hello';
let $a = 'hello';
//invalid
Let 1a = 'hello'; // this gives an error
2/3
3. JavaScript is case-sensitive. So y and Y are different variables. For example,
let y = "hi";
let Y = 5;
console.log(y); // hi
console.log(Y); // 5
//invalid
let new = 5; // Error! new is a keyword.
Notes:
Though you can name variables in any way you want, it's a good practice to give a
descriptive variable name. If you are using a variable to store the number of apples,
it better to use apples or numberOfApples rather than x or n.
In JavaScript, the variable names are generally written in camelCase if it has
multiple words. For example, firstName, annualSalary, etc.
JavaScript Constants
The const keyword was also introduced in the ES6(ES2015) version to create constants.
For example,
const x = 5;
const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)
Also, you cannot declare a constant without initializing it. For example,
Note: If you are sure that the value of a variable won't change throughout the program,
it's recommended to use const. However, there are a few browsers that do not support
const. Visit JavaScript const browser support to learn more.
Now that you know about variables, you will learn about different types of data a variable
can store in the next tutorial.
3/3