Literal Types

ECMAScript 5
var booleanVar = true;
var integerVar = 12;
var floatingPointVar = 1.618;
var stringVar = "Hello";
var arrayVar = [1, 2, 3];
var objectVar = { name: "Sam", age: 21 };
var regexVar = /sam(uel)?/g;
var nullVar = null;
var undefinedVar = undefined;

Literals represent values, like: true, 12 or "Hello".

Literals in JavaScript can be grouped into these categories:

  • Boolean
  • Integer
  • Floating-point
  • String
  • Array
  • Object
  • Regex
  • Null
  • Undefined

Boolean Literal

ECMAScript 5
var enable   = true;
var disable  = false;

There are 2 Boolean literals, true and false.


Integer Literal

ECMAScript 2015
var ans1 = 42;        // Base10
var ans2 = 0b101010;  // Binary
var ans3 = 0o52;      // Octal
var ans4 = 0x2A;      // Hexadecimal

There are 4 Integer Literal representations:

  • Base10
  • Binary (base 2)
  • Octal (base 8)
  • Hexadecimal (base 16)

Binary, Octal and Hexadecimal forms have been introduced in JavaScript ES6.

All the variables defined here are equal to value 42.


Floating-Point Literal

ECMAScript 5
var pi1 = 3.14159   // Normal
var pi2 = 314159E-5 // Scientific

There are 2 Floating-point Literal representations:

  • Normal
  • Scientific

Both variables defined here are equal.


String Literal

ECMAScript 2015
var name1 = 'sam';
var name2 = "sam";
var name3 = `sam`;

String is a sequence of characters.

There are 3 String Literal representations:

  • Single quote
  • Double quote
  • Template String

The differences between these Literals will be explained in the String topic.


Array Literal

ECMAScript 5
var groceries = ["Milk", "Egg", "Corn"];

Array is an ordered sequence of items.

Here, We are creating an array of 3 elements named groceries.

Arrays will be discussed in the Array topic.


Object Literal

ECMAScript 5
var sam = {name: "Sam", age: 21};

Object is a container for key/value pairs, in which keys are unique.

Here, We are creating an object with 2 properties name and age.

Objects and classes will be discussed in the Class topic.


Regex Literal

ECMAScript 5
var isSam = /sam(uel)?/;

Regular Expression or Regex is a sequence of characters that define a search pattern.

Here, We are creating a Regular Expression variable isSam. This is going to match strings sam and samuel.

You can read more about Regular Expressions here.


Null Literal

ECMAScript 5
var nextElement = null;

null is used to represent the absence of a value.

null is generally intentionally being set.


Undefined Literal

ECMAScript 5
var var1;   // undefined
var var2 = undefined;
var var3 = void 0;

undefined is a value assigned to variables which are just defined without setting initial value or variables that hasn't been defined yet.

void 0 returns an undefined value with better compatibility for older implementations of JavaScript.