Sure, here are some examples of using let, var, and const in JavaScript:
- Using
var:
javascriptfunction exampleFunction() {
var x = 5;
if (true) {
var x = 10;
console.log(x); // Output: 10
}
console.log(x); // Output: 10
}
In this example, the var keyword is used to declare a variable x inside a function. When the function is called, x is first assigned a value of 5. Then, inside an if statement, x is reassigned a value of 10 using the var keyword. This reassignment affects the value of x outside the if statement as well, because var has function scope.
- Using
let:
javascriptfunction exampleFunction() {
let x = 5;
if (true) {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // Output: 5
}
In this example, the let keyword is used to declare a variable x inside a function. When the function is called, x is first assigned a value of 5. Then, inside an if statement, a new variable x is declared and assigned a value of 10. This new variable only exists inside the if statement, because let has block scope.
- Using
const:
arduinoconst PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable.
In this example, the const keyword is used to declare a constant variable PI with a value of 3.14159. The value of PI cannot be changed later, as it is a constant. If an attempt is made to reassign PI, an error will be thrown.
No comments:
Post a Comment