A JavaScript Boolean represents one of two values: true or false.
Very often, in programming, you will need a data type that can only have one of two values, like
For this, JavaScript has a Boolean data type. It can only take the values true or false.
You can use the Boolean() function to find out if an expression (or a variable) is true:
Boolean(10 > 9) // returns true
Or even easier:
(10 > 9) // also returns true
10 > 9 // also returns true
The chapter JS comparisons gives a full overview of comparison operators.
The chapter JS conditions gives a full overview of conditional statements.
Here are some examples:
Operator |
Description |
Example |
== |
equal to |
if (day == "Monday") |
> |
greater than |
if (salary > 9000) |
< |
less than |
if (age < 18) |
The Boolean value of an expression is the fundament for JavaScript comparisons and conditions. |
100
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
5 < 6
The Boolean value of 0 (zero) is false:
var x = 0;
Boolean(x); // returns false
The Boolean value of -0 (minus zero) is false:
var x = -0;
Boolean(x); // returns false
The Boolean value of "" (empty string) is false:
var x = "";
Boolean(x); // returns false
The Boolean value of undefined is false:
var x;
Boolean(x); // returns false
The Boolean value of null is false:
var x = null;
Boolean(x); // returns false
The Boolean value of false is (you guessed it) false:
var x = false;
Boolean(x); // returns false
The Boolean value of NaN is false:
var x = 10 / "H";
Boolean(x); // returns false
A regular expression is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations.
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.
/pattern/modifiers;
var patt = /w3schools/i
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);
The result in n will be:
6
The search method will also accept a string as search argument. The string argument will be converted to a regular expression:
Use a string to do a search for "W3schools" in a string:
var str = "Visit W3Schools!";
var n = str.search("W3Schools");
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");
The result in res will be:
Visit W3Schools!
The replace() method will also accept a string as search argument:
var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");
Regular expression arguments (instead of string arguments) can be used in the methods above. |
Modifiers can be used to perform case-insensitive more global searches:
Modifier |
Description |
i |
Perform case-insensitive matching |
g |
Perform a global match (find all matches rather than stopping after the first match) |
m |
Perform multiline matching |
Brackets are used to find a range of characters:
Expression |
Description |
[abc] |
Find any of the characters between the brackets |
[0-9] |
Find any of the digits between the brackets |
(x|y) |
Find any of the alternatives separated with | |
Metacharacters are characters with a special meaning:
Metacharacter |
Description |
\d |
Find a digit |
\s |
Find a whitespace character |
\b |
Find a match at the beginning or at the end of a word |
\uxxxx |
Find the Unicode character specified by the hexadecimal number xxxx |
Quantifiers define quantities:
Quantifier |
Description |
n+ |
Matches any string that contains at least one n |
n* |
Matches any string that contains zero or more occurrences of n |
n? |
Matches any string that contains zero or one occurrences of n |
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
var patt = /e/;
patt.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:
/e/.test("The best things in life are free!")
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
e
Number() converts to a Number, String() converts to a String, Boolean() converts to a Boolean.
In JavaScript there are 5 different data types that can contain values:
There are 3 types of objects:
And 2 data types that cannot contain values:
You can use the typeof operator to find the data type of a JavaScript variable.
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
typeof new Date() // Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not declared)
typeof null // Returns object
Please observe:
You cannot use typeof to define if an object is an JavaScript Array or a JavaScript Date.
The constructor property returns the constructor function for all JavaScript variables.
"John".constructor // Returns function String() { [native code] }
(3.14).constructor // Returns function Number() { [native code] }
false.constructor // Returns function Boolean() { [native code] }
[1,2,3,4].constructor // Returns function Array() { [native code] }
{name:'John', age:34}.constructor // Returns function Object() { [native code] }
new Date().constructor // Returns function Date() { [native code] }
function () {}.constructor // Returns function Function(){ [native code] }
You can check the constructor property to find out if an object is an Array (contains the word "Array"):
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
You can check the constructor property to find out if an object is a Date (contains the word "Date"):
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
JavaScript variables can be converted to a new variable and another data type:
The global method String() can convert numbers to strings.
It can be used on any type of numbers, literals, variables, or expressions:
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression
The Number method toString() does the same.
x.toString()
(123).toString()
(100 + 23).toString()
In the chapter Number Methods, you will find more methods that can be used to convert numbers to strings:
Method |
Description |
toExponential() |
Returns a string, with a number rounded and written using exponential notation. |
toFixed() |
Returns a string, with a number rounded and written with a specified number of decimals. |
toPrecision() |
Returns a string, with a number written with a specified length |
The global method String() can convert booleans to strings.
String(false) // returns "false"
String(true) // returns "true"
The Boolean method toString() does the same.
false.toString() // returns "false"
true.toString() // returns "true"
The global method String() can convert dates to strings.
String(Date()) // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
The Date method toString() does the same.
Date().toString() // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
In the chapter Date Methods, you will find more methods that can be used to convert dates to strings:
Method |
Description |
getDate() |
Get the day as a number (1-31) |
getDay() |
Get the weekday a number (0-6) |
getFullYear() |
Get the four digit year (yyyy) |
getHours() |
Get the hour (0-23) |
getMilliseconds() |
Get the milliseconds (0-999) |
getMinutes() |
Get the minutes (0-59) |
getMonth() |
Get the month (0-11) |
getSeconds() |
Get the seconds (0-59) |
getTime() |
Get the time (milliseconds since January 1, 1970) |
The global method Number() can convert strings to numbers.
Strings containing numbers (like "3.14") convert to numbers (like 3.14).
Empty strings convert to 0.
Anything else converts to NaN (Not a number).
Number("3.14") // returns 3.14
Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN
In the chapter Number Methods, you will find more methods that can be used to convert strings to numbers:
Method |
Description |
parseFloat() |
Parses a string and returns a floating point number |
parseInt() |
Parses a string and returns an integer |
The global method Number() can also convert booleans to numbers.
Number(false) // returns 0
Number(true) // returns 1
The global method Number() can be used to convert dates to numbers.
d = new Date();
Number(d) // returns 1404568027739
The date method getTime() does the same.
d = new Date();
d.getTime() // returns 1404568027739
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
The result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 1 // returns "51" because 1 is converted to "1"
"5" - 1 // returns 4 because "5" is converted to 5
JavaScript automatically calls the variable's toString() function when you try to "output" an object or a variable:
document.getElementById("demo").innerHTML = myVar;
// if myVar = {name:"Fjohn"} // toString converts to "[object Object]"
// if myVar = [1,2,3,4] // toString converts to "1,2,3,4"
// if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
Numbers and booleans are also converted, but this is not very visible:
// if myVar = 123 // toString converts to "123"
// if myVar = true // toString converts to "true"
// if myVar = false // toString converts to "false"
Comparison and Logical operators are used to test for true or false.
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator |
Description |
Comparing |
Returns |
Try it |
== |
equal to |
x == 8 |
false |
|
x == 5 |
true |
|||
=== |
equal value and equal type |
x === "5" |
false |
|
x === 5 |
true |
|||
!= |
not equal |
x != 8 |
true |
|
!== |
not equal value or not equal type |
x !== "5" |
true |
|
x !== 5 |
false |
|||
> |
greater than |
x > 8 |
false |
|
< |
less than |
x < 8 |
true |
|
>= |
greater than or equal to |
x >= 8 |
false |
|
<= |
less than or equal to |
x <= 8 |
true |
Comparison operators can be used in conditional statements to compare values and take action depending on the result:
if (age < 18) text = "Too young";
You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator |
Description |
Example |
&& |
and |
(x < 10 && y > 1) is true |
|| |
or |
(x == 5 || y == 5) is false |
! |
not |
!(x == y) is true |
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
variablename = (condition) ? value1:value2
voteable = (age < 18) ? "Too young":"Old enough";
If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough".
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
if (condition) {
block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. |
Make a "Good day" greeting if the time is less than 20:00:
if (time < 20) {
greeting = "Good day";
}
The result of greeting will be:
Good day
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
If the time is less than 20:00, create a "Good day" greeting, otherwise "Good evening":
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The result of greeting will be:
Good day
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The result of greeting will be:
Good day
The switch statement is used to perform different action based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
Use today's weekday number to calculate weekday name: (Sunday=0, Monday=1, Tuesday=2, ...)
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
The result of day will be:
Monday
When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more execution of code and/or case testing inside the block.
When a match is found, and the job is done, it's time for a break. |
The default keyword specifies the code to run if there is no case match:
If today is neither Saturday nor Sunday, write a default message:
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
The result of text will be:
Looking forward to the Weekend
Sometimes, in a switch block, you will want different cases to use the same code, or fall-through to a common default.
Note from the next example, that cases can share the same code block, and that the default case does not have to be the last case in a switch block:
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
Loops can execute a block of code a number of times.
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
JavaScript supports different kinds of loops:
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Normally you will use statement 1 to initiate the variable used in the loop (var i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
And you can omit statement 1 (like when your values are set before the loop starts):
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial. |
Often statement 3 increases the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), or larger increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
The JavaScript for/in statement loops through the properties of an object:
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
Loops can execute a block of code as long as a specified condition is true.
The while loop loops through a block of code as long as a specified condition is true.
while (condition) {
code block to be executed
}
In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:
while (i < 10) {
text += "The number is " + i;
i++;
}
If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser. |
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
If you have read the previous chapter, about the&nb