Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Từ khóa const trong JavaScript

Từ khóa const khai báo biến không thể gán lại giá trị khác hay khai báo lại. Được giới thiệu từ ES2015 (ES6).

Ví dụ

<!DOCTYPE html> <html> <head> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    } </style> </head> <body> <h1>Ví dụ const</h1> <button class="Btn">NHẤN VÀO ĐÂY</button> <p class="sample"></p> <h3>Nhấn nút để thử thay đổi giá trị const</h3> <script>    let sampleEle = document.querySelector(".sample");    const a = 33;    sampleEle.innerHTML = "a = " + a + "<br>";    document.querySelector(".Btn").addEventListener("click", () => {       try {          a = 44;       } catch (err) {          sampleEle.innerHTML += "Lỗi : " + err;       }    }); </script> </body> </html>

Kết quả

Khi nhấn nút, báo lỗi TypeError: Assignment to constant variable.