Javascript, let, varAnd const is a keyword used to declare variables. However, there is a significant difference between the three, especially in terms of scope (scope) and variable mutability. Here are the main differences:
We
Coverage: Variable declared with var has a scope (scope) function. This means that variables can only be accessed in the function where it is declared.
Lift: Variable declared with var will be “Hoist” to the top of its function. This means you can access the variables before it is physically declared in the code.
Reassignment: Variable value declared with var can be changed again (reassign).
function example() {
var x = 10;
if (true) {
var x = 20; // Variabel x di sini sebenarnya adalah variabel yang sama dengan x di atas
}
console.log(x); // Output: 20
}
let
Coverage: Variable declared with let Has the scope of blocks. This means that variables can only be accessed in the block where he is declared.
Lift: Like var, let also “Hoist,” but the variables cannot be accessed before being declared in the code.
Reassignment: Variable value declared with let can be changed again (reassign).
function example() {
let x = 10;
if (true) {
let x = 20; // Variabel x di sini adalah variabel yang berbeda dengan x di atas
}
console.log(x); // Output: 10
}
Const
Coverage: Variable declared with const also has a block scope. Like letVariables can only be accessed in the block where he is declared.
Lift: Same as let, const “Hoist” and above, but cannot be accessed before being declared in the code.
Reassignment: Variable declared with const cannot be changed again after the initial value is determined. However, note that for objects and arrays declared with constThe contents of the object or array can still be changed.
Election between var, letor const Depending on the needs and scenarios of your code development. Generally, it is recommended to use const When possible, because this helps produce a code that is safer and easier to understand. Use let If you need a variable whose value can change, and avoid use var unless you work on an old code that might use var.
Game Center
Game News
Review Film
Rumus Matematika
Anime Batch
Berita Terkini
Berita Terkini
Berita Terkini
Berita Terkini
review anime
Comments are closed, but trackbacks and pingbacks are open.