Variables in JavaScript are a dedicated memory area for storing values.
We can use variables to store data types such as numbers, strings, objects, or arrays.
An important point of variables is that they allow us to store and change values during program execution.
Before using a variable, we need to declare it. In JS, we can declare variables using keywords such as var, let, or const.
var number = 10;
let name = "John";
const PI = 3.14;
In the example above, we declare three variables: number, name, and PI. The variables number and name can change their values during program execution, while PI is a constant that cannot be changed.
After declaring a variable, we can assign a value to that variable.
var x;
x = 5;
In the example above, we declare a variable x and assign the value 5 to it.
We can also declare and assign a value to a variable at the same time:
var y = 10;
After assigning a value to a variable, we can use that variable in the source code.
var a = 5;
var b = 3;
var sum = a + b;
console.log(sum); // Kết quả: 8
In the example above, we declare three variables a, b, and sum. The variable sum stores the sum of a and b, and then we print the result using the console.log() function.
Variables in JavaScript have their scope.
There are two common scopes in JavaScript:
var globalVariable = "I am a global variable";
function myFunction() {
var localVariable = "I am a local variable";
// Kết quả: "I am a global variable"
console.log(globalVariable);
// Kết quả: "I am a local variable"
console.log(localVariable);
}
myFunction();
// Kết quả: "I am a global variable"
console.log(globalVariable);
// Kết quả: Lỗi - localVariable không được định nghĩa
console.log(localVariable);
In the example above, we declare the variables globalVariable and localVariable. The globalVariable has a global scope and can be accessed from anywhere in the program. The localVariable has a local scope and can only be accessed from within the myFunction function.