Home >Web Front-end >JS Tutorial >The difference between var and let in JavaScript (code example)
Var and let are both used for function declarations in JavaScript. The difference between them is that var is function scope and let is block scope.
It can be said that compared with let, variables declared with var are defined throughout the program.
An example will illustrate this difference more clearly, as follows:
var example:
输入: console.log(x); var x=5; console.log(x); 输出: undefined 5
let example:
输入: console.log(x); let x=5; console.log(x); 输出: Error
Let’s take a look at the JavaScript code:
Code Example 1:
<html> <body> <script> // 定义后调用x var x = 5; document.write(x, "\n"); // 定义后调用y let y = 10; document.write(y, "\n"); // 在定义之前调用var z将返回undefined document.write(z, "\n"); var z = 2; // 在定义前调用let a会产生错误 document.write(a); let a = 3; </script> </body> </html>
Output:
Code Example 2:
In the code below, click start A function will be called that changes the color of both headers every 0.5 seconds. The color of the first title is stored in a var and the second title is declared using let.
Then access them outside the function block. Var will work, but variables declared using let will show an error because let is block scope.
<!DOCTYPE html> <html> <head> <title>js教程</title> <meta charset="UTF-8"> </head> <body> <h1 id="var" style="color:black;">javascript教程</h1> <h1 id="let" style="color:black;">javascript教程</h1> <button id="btn" onclick="colour()">Start</button> <script type="text/javascript"> function colour() { setInterval(function() { if (document.getElementById('var').style.color == 'black') var col1 = 'blue'; else col1 = 'black'; // 通过var设置color 1的值 if (document.getElementById('let').style.color == 'black') { let col2 = 'red'; } else { col2 = 'black'; } // 通过let设置color 2的值 document.getElementById('var').style.color = col1; document.getElementById('let').style.color = col2; // 在html中改变h1的颜色 }, 500); } </script> </body> </html>
Output:
##Related recommendations: "javascript tutorial"
This article is about JavaScript The difference between var and let is introduced, I hope it will be helpful to friends in need!The above is the detailed content of The difference between var and let in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!