JavaScript variables are containers for storing data values.
In the below example, a, b, and c, are variables:
Example
var a = 4;
var b = 7;
var c = a + b;
JavaScript Data Types
JavaScript variables can hold numbers like 50 and text values like “Pawan Negi”. In a programming language, text values are called text strings. JavaScript can handle many types of data, but for now, just think of numbers and strings. In JavaScript, Strings are written inside double or single quotes. Numbers are written without quotes. If you put a number in quotes, it will be treated as a text string.
Example
var pi = 60.2;
var person = “Pawan Negi”;
var answer = ‘Yes I am!’;
Declaring (Creating) JavaScript Variables
Creating a variable or declaring a variable is same in JavaScript.
We create a JavaScript variable with the var keyword:
var myName;
After the declaration, the variable doesn’t have any value. (Technically it has the value of undefined)
To assign a value to the variable, use the equal sign:
myName = “Rahul”;
You can also assign a value to the variable when you declare it:
var myName = “Rahul”;
In the example below, we create a variable called myName and assign the value “Rahul” to it.
Then we “output” the value inside an HTML paragraph with id=”demo”:
Test Yourself With Exercise: 1
Create a variable called age, assign the value 21 to it, and display it.
Test Yourself With Exercise: 2
Display the sum of 2 + 8, using two variables a and b.
Test Yourself With Exercise: 3
Create a third variable called c, assign a + b to it, and display it.