Dalam JavaScript, pembolehubah ialah blok binaan asas yang membolehkan anda menyimpan dan memanipulasi data sepanjang kod anda. Sama ada anda menjejak input pengguna, mengurus keadaan atau hanya memegang nilai untuk digunakan kemudian, pembolehubah adalah amat diperlukan dalam mana-mana aplikasi JavaScript. Memandangkan JavaScript telah berkembang, begitu juga dengan cara kami mentakrifkan pembolehubah ini.
Hari ini, terdapat tiga cara utama untuk mengisytiharkan pembolehubah dalam JavaScript: var, let dan const. Setiap kata kunci ini menawarkan gelagat yang berbeza dan memahami masa untuk menggunakan setiap kata kunci adalah penting untuk menulis kod yang bersih, cekap dan bebas pepijat.
Dalam blog ini, kami akan meneroka perbezaan antara javascript var vs let vs const, membandingkan penggunaannya dan menyediakan contoh kod praktikal untuk menggambarkan amalan terbaik bagi setiap satu. Pada akhirnya, anda akan mempunyai pemahaman yang jelas tentang cara memilih pengisytiharan pembolehubah yang betul untuk keperluan anda, membantu anda menulis kod JavaScript yang lebih baik.
var ialah cara asal untuk mengisytiharkan pembolehubah dalam JavaScript dan menjadi bahan ruji selama bertahun-tahun. Walau bagaimanapun, apabila JavaScript berkembang, had dan isu dengan var membawa kepada pengenalan let dan const dalam ES6 (ECMAScript 2015).
Ciri utama var ialah ia berskop fungsi, bermakna ia hanya boleh diakses dalam fungsi di mana ia diisytiharkan. Jika diisytiharkan di luar fungsi, ia menjadi pembolehubah global. Skop fungsi ini berbeza daripada skop blok yang disediakan oleh let dan const.
Satu lagi ciri penting var ialah mengangkat, di mana pengisytiharan berubah-ubah dialihkan ke bahagian atas skopnya semasa pelaksanaan. Ini membolehkan anda merujuk pembolehubah var sebelum ia diisytiharkan, tetapi nilainya tidak akan ditentukan sehingga tugasan berlaku. Walaupun pengangkatan boleh menjadi mudah, ia sering membawa kepada kekeliruan dan pepijat halus, terutamanya dalam pangkalan kod yang lebih besar.
console.log(x); // Outputs: undefined var x = 5; console.log(x); // Outputs: 5
Dalam contoh ini, walaupun x dilog sebelum ia diisytiharkan, kod itu tidak menimbulkan ralat. Sebaliknya, ia mengeluarkan tidak ditentukan kerana pengangkatan. JavaScript melayan kod seolah-olah perisytiharan var x telah dialihkan ke bahagian atas skopnya.
Salah satu perangkap biasa dengan var ialah penciptaan pembolehubah global secara tidak sengaja. Jika anda terlupa menggunakan var dalam fungsi, JavaScript akan mencipta pembolehubah global, yang boleh membawa kepada tingkah laku yang tidak dijangka.
function setValue() { value = 10; // Accidentally creates a global variable } setValue(); console.log(value); // Outputs: 10 (global variable created unintentionally)
Isu lain ialah var membenarkan pengisytiharan semula dalam skop yang sama, yang boleh membawa kepada pepijat yang sukar dikesan:
var x = 10; var x = 20; console.log(x); // Outputs: 20
Di sini, pembolehubah x diisytiharkan semula dan diberikan nilai baharu, berpotensi menimpa nilai sebelumnya tanpa sebarang amaran.
Dalam JavaScript moden let vs var vs const , var biasanya tidak digalakkan memihak kepada let dan const, yang menawarkan skop yang lebih baik dan menghalang banyak isu biasa. Walau bagaimanapun, var mungkin masih boleh digunakan dalam pangkalan kod lama yang pemfaktoran semula bukan pilihan atau dalam senario tertentu di mana skop peringkat fungsi dikehendaki secara eksplisit.
let ialah pengisytiharan pembolehubah berskop blok yang diperkenalkan dalam ES6 (ECMAScript 2015). Tidak seperti var, yang berskop fungsi, biarkan terhad kepada blok di mana ia ditakrifkan, seperti dalam gelung atau pernyataan if. Skop blok ini membantu mencegah ralat dan menjadikan kod anda lebih mudah diramal dengan mengehadkan kebolehcapaian pembolehubah kepada blok tertentu di mana ia diperlukan.
Perbezaan utama antara skop fungsi dan skop blok ialah pembolehubah berskop fungsi (var) boleh diakses sepanjang keseluruhan fungsi di mana ia diisytiharkan, manakala pembolehubah berskop blok (biar) hanya boleh diakses dalam blok tertentu, seperti sebagai gelung atau pernyataan bersyarat, di mana ia ditakrifkan. Tingkah laku let ini boleh membantu mengelakkan isu yang timbul daripada pembolehubah yang boleh diakses secara tidak sengaja di luar skop yang dimaksudkan.
for (let i = 0; i < 3; i++) { console.log(i); // Outputs 0, 1, 2 } console.log(i); // ReferenceError: i is not defined
Dalam contoh ini, i hanya boleh diakses dalam gelung kerana skop sekatan.
if (true) { var x = 10; let y = 20; } console.log(x); // Outputs 10 (function-scoped) console.log(y); // ReferenceError: y is not defined (block-scoped)
Di sini, x boleh diakses di luar blok if disebabkan oleh skop fungsi var, manakala y tidak boleh diakses di luar blok kerana skop let's block.
const is another block-scoped variable declaration introduced in ES6, similar to let. However, const is used to declare variables that are intended to remain constant throughout the program. The key difference between const and let is immutability: once a const variable is assigned a value, it cannot be reassigned. This makes const ideal for values that should not change, ensuring that your code is more predictable and less prone to errors.
However, it’s important to understand that const enforces immutability on the variable binding, not the value itself. This means that while you cannot reassign a const variable, if the value is an object or array, the contents of that object or array can still be modified.
const myNumber = 10; myNumber = 20; // Error: Assignment to constant variable.
In this example, trying to reassign the value of myNumber results in an error because const does not allow reassignment.
const myArray = [1, 2, 3]; myArray.push(4); // Allowed console.log(myArray); // Output: [1, 2, 3, 4] const myObject = { name: "John" }; myObject.name = "Doe"; // Allowed console.log(myObject); // Output: { name: "Doe" }
Here, even though the myArray and myObject variables are declared with const, their contents can be modified. The const keyword only ensures that the variable itself cannot be reassigned, not that the data inside the object or array is immutable.
Best practices in modern JavaScript suggest using const by default for most variables. This approach helps prevent unintended variable reassignment and makes your code more reliable. You should only use let when you know that a variable's value will need to be reassigned. By adhering to this principle, you can reduce bugs and improve the overall quality of your code.
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Hoisted (initialized as undefined) | Hoisted (but not initialized) | Hoisted (but not initialized) |
Re-declaration | Allowed within the same scope | Not allowed in the same scope | Not allowed in the same scope |
Immutability | Mutable | Mutable | Immutable binding, but mutable contents for objects/arrays |
Example of Scope:
function scopeTest() { if (true) { var a = 1; let b = 2; const c = 3; } console.log(a); // Outputs 1 (function-scoped) console.log(b); // ReferenceError: b is not defined (block-scoped) console.log(c); // ReferenceError: c is not defined (block-scoped) } scopeTest();
In this example, var is function-scoped, so a is accessible outside the if block. However, let and const are block-scoped, so b and c are not accessible outside the block they were defined in.
Example of Hoisting:
console.log(varVar); // Outputs undefined console.log(letVar); // ReferenceError: Cannot access 'letVar' before initialization console.log(constVar); // ReferenceError: Cannot access 'constVar' before initialization var varVar = "var"; let letVar = "let"; const constVar = "const";
Here, var is hoisted and initialized as undefined, so it can be referenced before its declaration without causing an error. However, let and const are hoisted but not initialized, resulting in a ReferenceError if accessed before their declarations.
Example of Re-declaration
var x = 10; var x = 20; // No error, x is now 20 let y = 10; let y = 20; // Error: Identifier 'y' has already been declared const z = 10; const z = 20; // Error: Identifier 'z' has already been declared
With var, re-declaring the same variable is allowed, and the value is updated. However, let and const do not allow re-declaration within the same scope, leading to an error if you try to do so.
Example of Immutability:
const myArray = [1, 2, 3]; myArray.push(4); // Allowed console.log(myArray); // Output: [1, 2, 3, 4] myArray = [4, 5, 6]; // Error: Assignment to constant variable
In this case, const prevents reassignment of the variable myArray, which would result in an error. However, the contents of the array can still be modified, such as adding a new element.
In modern JavaScript, the consensus among developers is to use const and let in place of var to ensure code that is more predictable, maintainable, and less prone to bugs. Here are some best practices to follow:
Sample Refactor: Converting var to let and const
Here’s a simple example of refactoring older JavaScript code that uses var to a more modern approach with let and const.
Before Refactoring:
function calculateTotal(prices) { var total = 0; for (var i = 0; i < prices.length; i++) { var price = prices[i]; total += price; } var discount = 0.1; var finalTotal = total - (total * discount); return finalTotal; }
After Refactoring:
function calculateTotal(prices) { let total = 0; for (let i = 0; i < prices.length; i++) { const price = prices[i]; // price doesn't change within the loop total += price; } const discount = 0.1; // discount remains constant const finalTotal = total - (total * discount); // finalTotal doesn't change after calculation return finalTotal; }
In the refactored version, total is declared with let since its value changes throughout the function. price, discount, and finalTotal are declared with const because their values are not reassigned after their initial assignment. This refactoring makes the function more robust and easier to reason about, reducing the likelihood of accidental errors.
When working with var, let, and const, developers often encounter common pitfalls that can lead to bugs or unexpected behavior. Understanding these pitfalls and knowing how to avoid them is crucial for writing clean, reliable code.
One of the most common mistakes with var is accidentally creating global variables. This happens when a var declaration is omitted inside a function or block, causing the variable to be attached to the global object.
function calculate() { total = 100; // No var/let/const declaration, creates a global variable } calculate(); console.log(total); // Outputs 100, but total is now global!
How to Avoid:
Always use let or const to declare variables. This ensures that the variable is scoped to the block or function in which it is defined, preventing unintended global variables.
var is hoisted to the top of its scope, but only the declaration is hoisted, not the assignment. This can lead to confusing behavior if you try to use the variable before it is assigned.
console.log(name); // Outputs undefined var name = "Alice";
How to Avoid:
Use let or const, which are also hoisted but not initialized. This prevents variables from being accessed before they are defined, reducing the chance of errors.
var allows for re-declaration within the same scope, which can lead to unexpected overwrites and bugs, especially in larger functions.
var count = 10; var count = 20; // No error, but original value is lost
How to Avoid:
Avoid using var. Use let or const instead, which do not allow re-declaration within the same scope. This ensures that variable names are unique and helps prevent accidental overwrites.
Many developers assume that const makes the entire object or array immutable, but in reality, it only prevents reassignment of the variable. The contents of the object or array can still be modified.
const person = { name: "Alice" }; person.name = "Bob"; // Allowed, object properties can be modified person = { name: "Charlie" }; // Error: Assignment to constant variable
How to Avoid: Understand that const applies to the variable binding, not the value itself. If you need a truly immutable object or array, consider using methods like Object.freeze() or libraries that enforce immutability.
Developers may incorrectly assume that variables declared with let or const are accessible outside of the block they were defined in, similar to var.
if (true) { let x = 10; } console.log(x); // ReferenceError: x is not defined
Always be aware of the block scope when using let and const. If you need a variable to be accessible in a wider scope, declare it outside the block.
By understanding these common pitfalls and using var, let, and const appropriately, you can avoid many of the issues that commonly arise in JavaScript development. This leads to cleaner, more maintainable, and less error-prone code.
In this blog, we've explored the key differences between var, let, and const—the three primary ways to define variables in JavaScript. We've seen how var is function-scoped and hoisted, but its quirks can lead to unintended behavior. On the other hand, let and const, introduced in ES6, offer block-scoping and greater predictability, making them the preferred choices for modern JavaScript development.
For further reading and to deepen your understanding of JavaScript variables, check out the following resources:
MDN Web Docs: var
MDN Web Docs: let
MDN Web Docs: const
Understanding when and how to use var, let, and const is crucial for writing clean, efficient, and bug-free code. By defaulting to const, using let only when necessary, and avoiding var in new code, you can avoid many common pitfalls and improve the maintainability of your projects.
Atas ialah kandungan terperinci JavaScript Var vs Let vs Const: Perbezaan Utama & Penggunaan Terbaik. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!