Data

Variable

JavaScript

 

Defining Variable

ECMAScript 5
var age;

var name = "Sam";

Here we are defining two variables name and age.

You can optionally initialize a variable with a value in its declaration.

Variable names are:

  • Case sensitive
  • Can contain letters, digits, $ or _
  • Cannot start with a digit
  • Cannot be any of the reserved keywords
 

Defining Variable

ECMAScript 2015
let age;

let name = "Sam";

let can be used to defined a variable, just like var.

Here we are defining 2 variables age and name which name is initialized with value Sam.

let keyword is introduced in JavaScript ES6, and it declares a block scope local variables. This means that variables defined with let in a block, are not accessible from outside of the block.

 

Variable Types

ECMAScript 5
// Primitive Data Types
var booleanVar = true;
var numberVar = 12;
var stringVar = "Hello";
var nullVar = null;
var undefinedVar = undefined;

// Object
var arrayVar = [1, 2, 3];
var regexVar = /sam(uel)?/g;
var objectVar = { name: "Sam", age: 21 };

Data Types in JavaScript are devided into two groups:

  • Primitive Data Types:
    These are the most basic datatypes, which are boolean, number, string, null and undefined.

  • Object:
    Any data type that is not Primitive is an Object, for example: Array, Regex, etc.

 

Type Safety

ECMAScript 5
var status = 0;

status = "success";

JavaScript unlike C and Java, is not a Type-Safe Language.

It automatically converts the variable to the correct data type, depending on its value.

 

Defining Variables in one line

ECMAScript 5
var x, y=7, z=12;

You can define multiple variables in one statement.

Here, we are creating variables x, y, and z, and initialize y to 7 and z to 12.

 

Setting Variable value

ECMAScript 5
var age;

age = 21;

Here, we are defining a variable age first and assign a value 21 to it.

Assigning a value to a variable that is not defined yet, implicitely defines that variable and assign that value to it. (Check Strict mode)

 

Getting Variable value

ECMAScript 5
var age = 21;

var samAge = age + 3;   // samAge -> 24

To get the value of a variable, you can simply use its name.