JavaScript: Literals
This JavaScript tutorial explains how to use literals (string, number, boolean and null) in JavaScript with examples.
Description
We'll cover four types of literals - string literals, number literals, boolean literals and null literals.
String Literals
String literals are always surrounded by single quotes (') or double quotes (").
For example:
'ABC'
'TechOnTheNet'
"ABC"
"TechOnTheNet"
In JavaScript, you can declare a variable named h and give it the string value of 'TechOnTheNet'.
var h = 'TechOnTheNet';
or
var h = "TechOnTheNet";
Number Literals
Number literals can be written with or without decimal places. Number literals can be either positive numbers or negative numbers. If you do not specify a sign, then a positive number is assumed. Here are some examples of valid number literals:
15
3.14
-23
In JavaScript, you can declare a variable named counter and give it the numeric value of 15.
var counter = 15;
Boolean Literals
Boolean literals can either be true or false. These values are special keywords in JavaScript and don't need quotes. Here are the two types of Boolean literals:
true
false
In JavaScript, you can declare a variable named found and give it the Boolean value of false.
var found = false;
Null Literals
Null literals are a special literal value in JavaScript. A null represents the absence of a value. Here is a null literal:
null
In JavaScript, you can declare a variable named h and give it a value of null.
var h = null;
Advertisements