0% completed
In programming, variables are used to store information that can be used later in your code. Think of a variable as a container that holds data. You can name this container anything you like, and then use that name to access the data stored in it.
In JavaScript, there are three ways to declare a variable:
var
let
const
For now, we'll focus on var
to keep things simple.
To create a variable, you need to declare it. Declaring a variable means telling the program that this container exists and giving it a name. Here's how you declare a variable using var
:
var myVariable;
This line of code creates a variable named myVariable. Right now, myVariable doesn't contain any data. Let's give it some data!
You can assign a value to a variable when you declare it, or you can do it later. Here's how you do it:
var myVariable = 10;
You can also do it in two steps:
var myVariable; myVariable = 10;
Once you've created a variable and assigned it a value, you can use it in your code. For example, you can print the value of myVariable to the console. When you run this code, it will print 10 to the console.
One of the powerful features of variables is that you can change their value. Here's an example:
In this example, myVariable
starts with the value 10
. Then, we change its value to 20
. When we print it again, it shows the new value.
Variables can store numbers as well as strings (and other types that we will discuss later). Here is an example using variables with strings stored in them.
In this program, we create two variables: greeting
and theName
. We assign the values "Hello" and "World" to them. Then, we use the + operator to combine these values and print "Hello World" to the console.
.....
.....
.....