Checkout this video:
In other words, a variable is simply a box that you can store stuff in. You can use variables to store numbers, strings, objects, and even functions.
What is a Variable?
In programming, a variable is a value that can be changed, depending on conditions or on user input. In other words, a variable is like a container that can hold a value that can be changed.
For example, in the following code, the variable x is assigned the value 5. But later in the code, the value of x is changed to 10. So when the code is run, first x will have the value 5, and then it will have the value 10.
var x = 5;
x = 10;
This concept might be confusing at first, but you’ll get used to it with practice. Just remember that a variable is like a container that can hold a value which can be changed.
Why Do We Need Variables?
A variable is a “named storage” for data. We can use variables to store data like numbers or strings. Later, we can retrieve the data stored in the variable and use it in our program.
var myName = “John”;
This line creates a new variable called myName and stores the string value “John” in it. From now on, we can use the myName variable anywhere in our program to refer to the string “John”.
We can also create variables that store numbers like this:
var myAge = 20;
This line creates a new variable called myAge and stores the number value 20 in it.
Declaring a Variable
var answer = 42;
This statement creates a variable called answer and assigns it the value 42. You can call your variables anything you like, as long as they conform to the rules described below.
You can declare several variables in one go by comma-separating them:
var a = 1, b = 2, c = 3;
This will create three variables with the values 1, 2 and 3.
Assigning a Value to a Variable
Whenever you want to use a value in your program, you have to first declare a variable and then assign a value to that variable. The value can be of any data type like a number, string, or an array. You can also declare multiple variables of the same type in one statement by using commas to separate the variable names.
var variablename = value;
var x = 42;
var y = “Hello”;
Rules for Naming Variables
1. Variable names can be made up of letters, numbers, dollar signs, and underscores.
2. Variable names cannot start with a number.
3. Variable names are case sensitive, so myVariable is different from MyVariable.
Here are some examples of valid variable names:
var firstName; // use camel case when naming variables made up of multiple words
var $money; // dollars signs are often used in front of variables that hold money values
var _secret; // underscore can be used to indicate a “private” variable