Variables are used by the program to store temporary data, this data can change its values during the process.
The var and let statements are used to create variables.
Let’s create variables for the example:
var username; let userage;
username and userage are variable names.
By declaring a variable, we can also write a value to it:
var username = 'Alex'; let userage = '25';
Now we can use the recorded value of the variable in our program, for example we will display “Alex” in the console
website:
console.log(username);
await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, yield
When naming variables, keep in mind that JavaScript is a case-sensitive language
, that is, in the following code two different variables are declared:
var username; var userName;
You can define multiple variables separated by commas:
var username, age, height; let a, b, c;
We can change variable value:
var username = 'Alex'; var username = "Bob"; console.log(username);//return Bob
Constants in JavaScript
Using the “const” keyword, you can define a constant, which, like a variable, stores a value, but this the value cannot be changed.
Create a constant:
const username = "Alex";
If we try to change its value, we will get an error.
Constants should be used if you are sure that the constant will remain unchanged during further execution of the program.
let and var in JS what is the difference
In JavaScript, the let and var keywords are used to declare variables, but there are some differences in their behavior and scope.
var
var was the main way to declare variables in JavaScript before the advent of let and const. A variable declared with var has global or function scope, which means it is accessible within the entire function in which it is declared, or globally if declared outside the function.
Variables declared with var are also subject to hoisting, which means they can be used before they are actually declared.
let
let introduced in the ECMAScript 6 (ES6) standard and provides block scope for variables. A variable declared with let is visible only within the block in which it is declared (for example, inside curly braces {} ).
Variables declared with let are not hoisted and cannot be used before they are declared.
Example
Here is an example illustrating the difference between let and var:
function example() { var x = 10; if (true) { var x = 20; console.log(x); // Return 20 } console.log(x); // Return 20 } function example2() { let y = 10; if (true) { let y = 20; console.log(y); // Return 20 } console.log(y); // Return 10 } example(); example2();