Table of contents
No headings in the article.
1) In JavaScript, there are three keywords used for variable declaration: var, let, and const.
2) Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function. It becomes the property of the window object.
function example() {
x = 10;
}
example();
console.log(window.x); // 10
console.log(x) // 10
3) It's a good programming practice to declare all variables at the beginning of a script.
4) Objects (including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.
const employee = { job:'Web Developer'};
employee.job = 'Data Scientist';
employee.name = 'Amey'
console.log(employee.job); // Data Scientist
console.log(employee); // { job: 'Data Scientist', name: 'Amey' }
const a = [1,2,3,4]
a[1]=7
a.push(100)
console.log(a) // [ 1, 7, 3, 4, 100 ]
5) Initialize const with declaration only otherwise it will give an error.
const x;
// Uncaught SyntaxError: Missing initializer in const declaration
const y = 10;
6) It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).
const NAME = 'Jack';
let age = 30;
7) Limitations of Var keyword
- Hoisting: Variables declared with var are hoisted, which means they are moved to the top of their scope, even before the code is executed. This can lead to unexpected behavior.
console.log(x);
var x = 10;
// Output: undefined
- Function scope: In JavaScript, var variables are scoped to the nearest function, not block.
function myFunction() {
var x = 10;
if (true) {
var x = 20;
}
console.log(x);
}
myFunction();
// Output: 20
In this example, the var x inside the if block is not a new variable, but rather it's the same variable as the var x declared at the beginning of the function. Therefore, when you assign x the value of 20 inside the if block, it also changes the value of x in the entire function. The output of this code will be 20.
That's why use of let and const keywords is preferred over var.