JavaScript Booleans

 

A JavaScript Boolean represents one of two values: true or false.

 

Boolean Values

Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the values true or false.

 

The Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true:

Example

Boolean(10 > 9)        // returns true 


Try it Yourself » 

Or even easier:

Example

(10 > 9)              // also returns true
10 > 9                // also returns true 


Try it Yourself » 

 

 

Comparisons and Conditions

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.

 

Everything With a Real Value is True

Examples

100

3.14

-15

"Hello"

"false"

7 + 1 + 3.14

5 < 6 


Try it Yourself » 

 

 

Everything Without a Real Value is False

The Boolean value of 0 (zero) is false:

var x = 0;
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of -0 (minus zero) is false:

var x = -0;
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of "" (empty string) is false:

var x = "";
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of undefined is false:

var x;
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of null is false:

var x = null;
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of false is (you guessed it) false:

var x = false;
Boolean(x);       // returns false 


Try it Yourself » 

 

The Boolean value of NaN is false:

var x = 10 / "H";
Boolean(x);       // returns false 

 

 

 

JavaScript Regular Expressions

« Previous

Next Chapter »

 

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. 

 

What Is a Regular Expression?

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.

Syntax

/pattern/modifiers; 

 

Example:

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).

 

Using String Methods

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.

 

Using String search() With a Regular Expression

Example

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:


Try it Yourself »

 

 

Using String search() With String

The search method will also accept a string as search argument. The string argument will be converted to a regular expression: 

Example

Use a string to do a search for "W3schools" in a string:

var str = "Visit W3Schools!";
var n = str.search("W3Schools"); 


Try it Yourself » 

 

 

Use String replace() With a Regular Expression

Example

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!


Try it Yourself » 

 

Using String replace() With a String

The replace() method will also accept a string as search argument: 

var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools"); 


Try it Yourself » 

 

 

Did You Notice?

 

 

Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example). 

 

 

Regular Expression Modifiers

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

 

 

Regular Expression Patterns

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

 

 

Using the RegExp Object

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

 

Using test()

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":

Example

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 


Try it Yourself » 

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!") 

 

 

Using exec()

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":

Example 1

/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

 

 

 

JavaScript Type Conversion

« Previous

Next Chapter »

 

Number() converts to a Number, String() converts to a String, Boolean() converts to a Boolean. 

 

JavaScript Data Types

In JavaScript there are 5 different data types that can contain values:

  • string
  • number
  • boolean
  • object
  • function

There are 3 types of objects:

  • Object
  • Date
  • Array

And 2 data types that cannot contain values:

  • null
  • undefined

 

The typeof Operator

You can use the typeof operator to find the data type of a JavaScript variable.

Example

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 


Try it yourself » 

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined

You cannot use typeof to define if an object is an JavaScript Array or a JavaScript Date.

 

The constructor Property

The constructor property returns the constructor function for all JavaScript variables.

Example

"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] } 


Try it yourself » 

You can check the constructor property to find out if an object is an Array (contains the word "Array"):

Example

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;


Try it yourself » 

You can check the constructor property to find out if an object is a Date (contains the word "Date"):

Example

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;


Try it yourself » 

 

 

JavaScript Type Conversion

JavaScript variables can be converted to a new variable and another data type:

  • By the use of a JavaScript function
  • Automatically by JavaScript itself

 

Converting Numbers to Strings

The global method String() can convert numbers to strings.

It can be used on any type of numbers, literals, variables, or expressions:

Example

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


Try it yourself » 

The Number method toString() does the same.

Example

x.toString()
(123).toString()
(100 + 23).toString()


Try it yourself » 

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

 

 

Converting Booleans to Strings

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" 

 

 

Converting Dates to Strings

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.

Example

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)

 

 

Converting Strings to Numbers

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

 

 

Converting Booleans to Numbers

The global method Number() can also convert booleans to numbers.

Number(false)     // returns 0
Number(true)      // returns 1 

 

 

Converting Dates to Numbers

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 

 

 

Automatic Type Conversion

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

 

 

Automatic String Conversion

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" 

 

 

 

JavaScript Comparison and Logical Operators

« Previous

Next Chapter »

 

Comparison and Logical operators are used to test for true or false.

 

Comparison Operators

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

Try it »

x == 5

true

Try it »

===

equal value and equal type

x === "5"

false

Try it »

x === 5

true

Try it »

!=

not equal

x != 8

true

Try it »

!==

not equal value or not equal type

x !== "5"

true

Try it »

x !== 5

false

Try it »

>

 greater than

x > 8

false

Try it »

<

 less than

x < 8

true

Try it »

>=

 greater than or equal to

x >= 8

false

Try it »

<=

 less than or equal to

x <= 8

true

Try it »

 

 

How Can it be Used

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

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

 

 

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename = (condition) ? value1:value2 

Example

voteable = (age < 18) ? "Too young":"Old enough";


Try it Yourself » 

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".

 

 

 

JavaScript If...Else Statements

« Previous

Next Chapter »

 

Conditional statements are used to perform different actions based on different conditions.

 

Conditional Statements

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 if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

 

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

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. 

 

Example

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 


Try it Yourself » 

 

 

The else Statement

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
}

 

Example

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 


Try it Yourself » 

 

 

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

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
}

 

Example

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 

 

 

 

JavaScript Switch Statement

« Previous

Next Chapter »

 

The switch statement is used to perform different action based on different conditions.

 

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.

 

Example

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 


Try it Yourself » 

 

 

The break Keyword

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.
There is no need for more testing. 

 

 

The default Keyword

The default keyword specifies the code to run if there is no case match:

Example

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 


Try it Yourself » 

 

 

Common Code and Fall-Through

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:

Example

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";

 

 

 

JavaScript For Loop

« Previous

Next Chapter »

 

Loops can execute a block of code a number of times.

 

JavaScript Loops

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:

Instead of writing:

text += cars[0] + "<br>"; 
text += cars[1] + "<br>"; 
text += cars[2] + "<br>"; 
text += cars[3] + "<br>"; 
text += cars[4] + "<br>"; 
text += cars[5] + "<br>"; 

 

You can write:

for (i = 0; i < cars.length; i++) { 
    text += cars[i] + "<br>";
}


Try it Yourself » 

 

 

Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

 

The For Loop

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.

Example

for (i = 0; i < 5; i++) {
    text += "The number is " + i + "<br>";
}


Try it Yourself » 

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.

 

Statement 1

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):

Example:

for (i = 0, len = cars.length, text = ""; i < len; i++) { 
    text += cars[i] + "<br>";
}


Try it Yourself » 

And you can omit statement 1 (like when your values are set before the loop starts):

Example:

var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) { 
    text += cars[i] + "<br>";
}


Try it Yourself » 

 

 

Statement 2

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.  

 

 

Statement 3

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): 

Example:

var i = 0;
var len = cars.length;
for (; i < len; ) { 
    text += cars[i] + "<br>";
    i++;
}


Try it Yourself » 

 

 

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

Example

var person = {fname:"John", lname:"Doe", age:25}; 

var text = "";
var x;
for (x in person) {
    text += person[x];
}

 

 

 

JavaScript While Loop

« Previous

Next Chapter »

 

Loops can execute a block of code as long as a specified condition is true.

 

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition) {
    code block to be executed
}

Example

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:

Example

while (i < 10) {
    text += "The number is " + i;
    i++;
}


Try it Yourself » 

 

 

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

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.

Syntax

do {
    code block to be executed
}
while (condition);

Example

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:

Example

do {
    text += "The number is " + i;
    i++;
}
while (i < 10);


Try it Yourself » 

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

 

Comparing For and While

If you have read the previous chapter, about the&nb