let allows you to declare block-level variables. The declared variable is available from the function block it is enclosed in.
//myLetVariable is *not* visible out here
for( let myLetVariable = 0; myLetVariable < 5; myLetVariable++ ) {//myLetVariable is only visible in here
}
//myLetVariable is *not* visible out here
const allows you to declare variables whose values are never intended to change. The variable is available from the function block it is declared in.
const Pi = 3.14; // variable Pi is set
const Pi = 3.14; // variable Pi is set
Pi = 1; // will throw an error because you cannot change a constant variable.
var is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function block it is declared in.
//myVarVariable *is* visible out here
for( var myVarVariable = 0; myVarVariable < 5; myVarVariable++ ) {
//myVarVariable is visible to the whole function
}
//myVarVariable *is* visible out here
If you declare a variable without assigning any value to it, its type is undefined.
An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function.
However, starting with ECMAScript Edition 6, let and const declarations allow you to create block-scoped variables.
@reference_0_mozilla
No comments:
Post a Comment