var x = 10;
The variable x is now declared and assigned the value 10. If we were to declare the same variable again using var, it would not throw any errors:
var x = 20;
This can lead to potential bugs and is considered bad practice. In addition, the scope of a variable declared using var is the entire function in which it is declared. If it is declared outside of any function, its scope is the global object.
let x = 10;
If we were to declare the same variable again using let, it would throw a SyntaxError:
let x = 20; // throws SyntaxError
This is because redeclaration of a variable with let is not allowed within the same block scope.
The const keyword is also introduced in ES6 and is used to declare constants. Constants are like variables, but their values cannot be re-assigned. Here is an example of how to use the const keyword:
const PI = 3.14;
If we were to try to re-assign the value of PI, it would throw a TypeError:
const PI = 3.14; PI = 4.13; // throws TypeError
This makes const useful for values that should not change, like mathematical constants or configuration settings. Similar to let, const also has a block scope.