Variables and Data Types in JavaScript

Variables in JavaScript

Variables are the containers that are used to store some value. Those values can be changed. Variables are actually the name of a memory location.

Variables in JavaScript are loosely typed which means you do not have to mention data type while declaring variable.

How to create variables in JavaScript?

Variables in JavaScript are created using var keyword. Few naming conventions are to be followed while defining variable names.
Example: var myVariable;
You can define more than one variable in one line.
Example: var first, second;

Naming Conventions while declaring variables in JavaScript

  • JavaScript variable name may comprise letters, numbers and underscore.
  • It should not contain space.
  • It should not begin with a number.
  • Variable names are case sensitive.

Example: var myVariable, var myvariable, var my_variable and var myvariable1 are all legal and are all different variables.

Variables can be declared first and then it can be initialized with a value.
var myNumber;
myNumber = 10;

Also variables can be declared and initialized in a single line.
var myNumber = 10;

Data Types in JavaScript

Data type defines what type of data should be stored in variable. Since JavaScript is loosely typed language, JavaScript parser decides that data type at the execution time of JavaScript code.

Following data types are there in JavaScript:

Data Type Description Example
boolean Possible values are true(1) or false(0). true
number it can be an integer or floating point number. 8 or 12.4 or 3.14
string it can be a single character or a group of characters including space and is always enclosed in single quotes or double quotes. 'a' or "JavaScript"
function it can be a predefined or user defined function. write() method
object it can be a predefined or user defined object. document

Contatenation Operation in JavaScript

Contatenation operation means joining two or more strings. It can be performed using plus(+) sign.


var str = "a" + "b"; //output: ab
var x = "Hello ";
var y = "World";
x = x + y; //output: Hello World

x = x + y can also be written as x += y.

<!DOCTYPE html>
<title>Variables and Data Types</title>
<div id="content"></div>
var bool = true;
var num1 = 10;
var num2 = 12.4;
var str;
str = "this is my text";
document.getElementById('content').innerHTML = "<h2>Varibales and Data Types</h2>";
document.getElementById('content').innerHTML += "Boolean" + bool;
document.getElementById('content').innerHTML += "<br />Integer" + num1;
document.getElementById('content').innerHTML += "<br />Real Number" + num2;
<< Displaying Output Functions >>