If you are new to programming or want to learn more about JavaScript, you need to understand the concept of variables. Variables are used to store data and can be used to create dynamic webpages and applications. In this tutorial, we will discuss the basics of JavaScript variables, how to declare them, assign values to them and use them in your code.
Variables are an essential part of programming. They are used to store data and information in a program. In JavaScript, variables can be declared using the var
, let
, and const
keywords.
Each of these keywords have different properties and uses. The var
keyword is used to declare a variable that can be accessed throughout the program. The let
keyword is used to declare a variable that can only be accessed within the scope of the block it is declared in. The const
keyword is used to declare a constant variable that cannot be changed.
Keyword | Scope | Mutable |
---|---|---|
var | Global | Yes |
let | Block | Yes |
const | Block | No |
Let's look at an example of how each of these keywords can be used.
var x = 10;
let y = 20;
const z = 30;
if (x < y) {
console.log(y); // 20
}
x = 20; // valid
y = 30; // valid
z = 40; // invalid
In this example, we declared a var
variable x
with the value 10
. We then declared a let
variable y
with the value 20
. We also declared a const
variable z
with the value 30
.
We can access the x
variable outside of the if
block because it was declared with the var
keyword. We can also access the y
variable inside the if
block because it was declared with the let
keyword. We cannot change the value of the z
variable because it was declared with the const
keyword.