eval(string) thực thi chuỗi như code JS. Rất nguy hiểm: injection attack, hiệu năng kém, khó debug, phá vỡ scope. Tránh dùng hoàn toàn trong production. Thay bằng JSON.parse, Function constructor, hoặc logic trực tiếp.
Ví dụ (chỉ để hiểu hành vi)
Đánh giá biểu thức, gán biến, gọi hàm:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>eval() JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: green; }
</style>
</head>
<body>
<h1>eval() trong JavaScript - CHỈ DEMO, KHÔNG DÙNG TRONG PRODUCTION</h1>
<div class="result"></div>
<button class="Btn">CHẠY EVAL</button>
<h3>Nhấn để thấy eval thực thi chuỗi</h3>
<script>
const resEle = document.querySelector('.result');
const btn = document.querySelector('.Btn');
function multiply(a, b) { return a * b; }
btn.addEventListener('click', () => {
resEle.innerHTML = `eval('12+92') = ${eval('12+92')}<br>`;
eval('resEle.innerHTML += \"eval gán trực tiếp HTML<br>\";');
resEle.innerHTML += `eval('multiply(12,33)') = ${eval('multiply(12,33)')}`;
});
</script>
</body>
</html>
Kết quả
Hiển thị: 104, eval gán trực tiếp HTML, 396.
CẢNH BÁO: Không bao giờ eval(input_từ_user). Dùng new Function() nếu buộc phải dynamic code (vẫn rủi ro).