JavaScript Variables

JavaScript variables are containers for storing data values.

In 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.

 

Working hours

 

Day Timing
Monday To Friday 8:00 Am To 8:00Pm
Saturday & Sunday 8:00 Am To 5:00Pm
 
 

Contact Information
ADDRESS: 263, First Floor
Pocket H-17, Sector 7
Rohini, Delhi - 110085
Near Rohini West Metro Station
Opposite Metro Pillar No. 425

Email: contactbapugraphics@gmail.com
            bapugraphicsindia@gmail.com

Mobile: 9891222738

Copyright © 2014 Bapu Graphics, All Right Reserved.