In this beginners guide, we’ll explore the different types of variables, and how to declare and assign values to them in JavaScript.
Variables can be declared using the var, let, or const keywords in JavaScript.
1// Variables in JavaScript
2var a = 10; // Declaring a variable using 'var'
3let b = 20; // Declaring a variable using 'let'
4const c = 30; // Declaring a constant using 'const'
When naming variables, follow these best practices to ensure your code is readable and maintainable:
1// Use camelCase for variable names
2const camelCase = 'camelCase';
3
4// Use PascalCase for class names
5class PascalCase {}
6
7// Boolean variables should start with 'is' or 'has'
8const isNumber = 10;
9const hasValue = true;
10
11// Constants should be in uppercase
12const PI = 3.14159;
13
14// Variables starting with '_' are considered private
15const _privateVariable = 'private'
1// Variables declared with 'var' can be redeclared
2var x = 10;
3var x = 20;
4
5console.log(x); // 20
6
7// Variables declared with 'var' can be reassigned
8x = 30;
9
10console.log(x); // 30
1// Variables declared with 'let' cannot be redeclared
2let x = 10;
3
4console.log(x); // 10
5
6// SyntaxError: Identifier 'x' has already been declared
7let x = 20;
8
9// Variables declared with 'let' can be reassigned
10x = 30;
11
12console.log(x); // 30
1// Variables declared with 'const' cannot be redeclared
2const x = 10;
3
4// SyntaxError: Identifier 'x' has already been declared
5const x = 20;
6
7// SyntaxError: Assignment to constant variable
8x = 30;
1// Variables declared with 'var' have function scope
2var x = 10;
3if (true) {
4 var x = 20; // Same variable
5}
6console.log(x); // 20
1var y = 10;
2function test() {
3 var y = 20; // Different variable
4}
5test();
6console.log(y); // 10
1// Variables declared with 'let' and 'const' have block scope
2let x = 10;
3if (true) {
4 let x = 20; // Different variable
5}
6console.log(x); // 10
1// Variables declared with 'var' are hoisted to the top of the function
2console.log(a); // undefined
3var a = 10;
1// Variables declared with 'let' and 'const' are not hoisted
2console.log(b); // ReferenceError: Cannot access 'b' before initialization
3let b = 20;