JavaScript Booleans

TUTORIAL HOME
JavaScript Booleans
❮ Previous Next ❯
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
»
Or even easier:

Example
(10 > 9)              // also returns true
10 > 9                // also returns true
»
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
»
Everything Without a “Real” is False
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
»
Booleans Can be Objects
Normally JavaScript booleans are primitive values created from literals: var x = false

But booleans can also be defined as objects with the keyword new: var y = new Boolean(false)

Example
var x = false;
var y = new Boolean(false);

// typeof x returns boolean
// typeof y returns object
Try it yourself »
Do not create Boolean objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == operator, equal booleans are equal:

Example
var x = false;            
var y = new Boolean(false);

// (x == y) is true because x and y have equal values
»
When using the === operator, equal booleans are not equal, because the === operator expects equality in both type and value.

Example
var x = false;            
var y = new Boolean(false);

// (x === y) is false because x and y have different types
»
Or even worse. Objects cannot be compared:

Example
var x = new Boolean(false);            
var y = new Boolean(false);

// (x == y) is false because objects cannot be compared
»
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always return false.

Complete Boolean Reference
For a complete reference, go to our Complete JavaScript Boolean Reference.

The reference contains descriptions and examples of all Boolean properties and methods.

❮ Previous Next ❯

JavaScript Comparison and Logical Operators

Toggle navigation
TUTORIAL HOME
JavaScript Comparison  and Logical Operators
❮ Previous Next ❯
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 »
x == “5” true Try it »
=== equal value and equal type x === 5 true Try it »
x === “5” false Try it »
!= not equal x != 8 true Try it »
!== not equal value or not equal type x !== 5 false Try it »
x !== “5” true Try it »
x !== 8 true 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 Try it
&& and (x 1) is true Try it »
|| or (x == 5 || y == 5) is false Try it »
! not !(x == y) is true Try it »
Conditional (Ternary) Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax
variablename = (condition) ?  value1:value2
Example
var 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”.

Comparing Different Types
Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false.

Case Value Try
2 < 12 true Try it »
2 < "12" true Try it »
2 < "John" false Try it »
2 > “John” false Try it »
2 == “John” false Try it »
“2” < "12" false Try it »
“2” > “12” true Try it »
“2” == “12” false Try it »
When comparing two strings, “2” will be greater than “12”, because (alphabetically) 1 is less than 2.

To secure a proper result, variables should be converted to the proper type before comparison:

age = Number(age);
if (isNaN(age)) {
    voteable = “Error in input”;
} else {
    voteable = (age < 18) ? "Too young" : "Old enough";
}
»
Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »  Exercise 6 »

❮ Previous Next ❯

JavaScript Numbers

Toggle navigation
TUTORIAL HOME
JavaScript Numbers
❮ Previous Next ❯
JavaScript has only one type of number.

Numbers can be written with, or without, decimals.

JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example
var x = 34.00;    // A number with decimals
var y = 34;       // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:

Example
var x = 123e5;    // 12300000
var y = 123e-5;   // 0.00123
JavaScript Numbers are Always 64-bit Floating Point
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 – 51) 11 bits (52 – 62) 1 bit (63)
Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

Example
var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000
»
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Example
var x = 0.2 + 0.1;         // x will be 0.30000000000000004
Try it yourself »
To solve the problem above, it helps to multiply and divide:

Example
var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3
»
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.

Example
var x = 0xFF;             // x will be 255
»
Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

By default, JavaScript displays numbers as base 10 decimals.

But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).

Example
var myNumber = 128;
myNumber.toString(16);     // returns 80
myNumber.toString(8);      // returns 200
myNumber.toString(2);      // returns 10000000
»
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Example
var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity
    myNumber = myNumber * myNumber;
}
Try it yourself »
Division by 0 (zero) also generates Infinity:

Example
var x =  2 / 0;          // x will be Infinity
var y = -2 / 0;          // y will be -Infinity
»
Infinity is a number: typeof Infinity returns number.

Example
typeof Infinity;        // returns “number”
»
NaN – Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

Example
var x = 100 / “Apple”;  // x will be NaN (Not a Number)
»
However, if the string contains a numeric value , the result will be a number:

Example
var x = 100 / “10”;     // x will be 10
»
You can use the global JavaScript function isNaN() to find out if a value is a number.

Example
var x = 100 / “Apple”;
isNaN(x);               // returns true because x is Not a Number
»
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

Example
var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN
»
Or the result might be a concatenation:

Example
var x = NaN;
var y = “5”;
var z = x + y;         // z will be NaN5
»
NaN is a number, and typeof NaN returns number:

Example
typeof NaN;             // returns “number”
»
Numbers Can be Objects
Normally JavaScript numbers are primitive values created from literals: var x = 123

But numbers can also be defined as objects with the keyword new: var y = new Number(123)

Example
var x = 123;
var y = new Number(123);

// typeof x returns number
// typeof y returns object
Try it yourself »
Do not create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == operator, equal numbers are equal:

Example
var x = 500;            
var y = new Number(500);

// (x == y) is true because x and y have equal values
»
When using the === operator, equal numbers are not equal, because the === operator expects equality in both type and value.

Example
var x = 500;            
var y = new Number(500);

// (x === y) is false because x and y have different types
»
Or even worse. Objects cannot be compared:

Example
var x = new Number(500);            
var y = new Number(500);

// (x == y) is false because objects cannot be compared
»
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always return false.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »

❮ Previous Next ❯

JavaScript If…Else Statements

Toggle navigation
TUTORIAL HOME
JavaScript If…Else  Statements
❮ Previous Next ❯
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 hour is less than 18:00:

if (hour < 18) {
    greeting = “Good day”;
}
The result of greeting will be:

Good day
»
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 hour is less than 18, create a “Good day” greeting, otherwise “Good evening”:

if (hour < 18) {
    greeting = “Good day”;
} else {
    greeting = “Good evening”;
}
The result of greeting will be:

Good day
»
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
»
More Examples
Random link
This example will write a link to either Omegas or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »  Exercise 6 »

❮ Previous Next ❯

TUTORIAL HOME JavaScript Switch Statement

Toggle navigation
TUTORIAL HOME
JavaScript Switch  Statement
❮ Previous Next ❯
The switch statement is used to perform different actions 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:
        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
The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:

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”;
}
The result of day will be:

Monday
»
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and 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.

A break can save a lot of execution time because it “ignores” the execution of all the rest of the code in the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

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

Example
The getDay() method returns the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), 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
»
The default case does not have to be the last case in a switch block:

Example
switch (new Date().getDay()) {
    default:
        text = “Looking forward to the Weekend”;
        break;
    case 6:
        text = “Today is Saturday”;
        break;
    case 0:
        text = “Today is Sunday”;
}
»
If default is not the last case in the switch block, remember to end the default case with a break.

Common Code Blocks
Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:

Example
switch (new Date().getDay()) {
    case 4:
    case 5:
        text = “Soon it is Weekend”;
        break;
    case 0:
    case 6:
        text = “It is Weekend”;
        break;
    default:
        text = “Looking forward to the Weekend”;
}
»
Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »

❮ Previous Next ❯

JavaScript For Loop

Toggle navigation
TUTORIAL HOME
JavaScript For Loop
❮ Previous Next ❯
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] + “
“;
text += cars[1] + “
“;
text += cars[2] + “
“;
text += cars[3] + “
“;
text += cars[4] + “
“;
text += cars[5] + “
“;

You can write:
for (i = 0; i < cars.length; i++) {
    text += cars[i] + “
“;
}
»
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 + “
“;
}
»
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 initialize the variable used in the loop (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] + “
“;
}
»
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] + “
“;
}
»
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 increments the value of 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–), positive 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] + “
“;
    i++;
}
»
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];
}
»
The While Loop
The while loop and the do/while loop will be explained in the next chapter.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »  Exercise 6 »

❮ Previous Next ❯

JavaScript While Loop

Toggle navigation
TUTORIAL HOME
JavaScript While Loop
❮ Previous Next ❯
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++;
}
»
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);
»
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 for loop, you will discover that a while loop is much the same as a for loop, with statement 1 and statement 3 omitted.

The loop in this example uses a for loop  to collect the car names from the cars array:

Example
var cars = [“BMW”, “Volvo”, “Saab”, “Ford”];
var i = 0;
var text = “”;

for (;cars[i];) {
    text += cars[i] + “
“;
    i++;
}
»
The loop in this example uses a while loop to collect the car names from the cars array:

Example
var cars = [“BMW”, “Volvo”, “Saab”, “Ford”];
var i = 0;
var text = “”;

while (cars[i]) {
    text += cars[i] + “
“;
    i++;
}
»
Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »

❮ Previous Next ❯

JavaScript Break and Continue

TUTORIAL HOME
JavaScript Break and Continue
❮ Previous Next ❯
The break statement “jumps out” of a loop.

The continue statement “jumps over” one iteration in the loop.

The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch() statement.

The break statement can also be used to jump out of a loop. 

The break statement breaks the loop and continues executing the code after the loop (if any):

Example
for (i = 0; i < 10; i++) {
    if (i === 3) { break; }
    text += “The number is ” + i + “
“;
}
»
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 3:

Example
for (i = 0; i < 10; i++) {
    if (i === 3) { continue; }
    text += “The number is ” + i + “
“;
}
»
JavaScript Labels
To label JavaScript statements you precede the statements with a label name and a colon:

label:
statements
The break and the continue statements are the only JavaScript statements that can “jump out of” a code block.

Syntax:

break labelname;

continue labelname;
The continue statement (with or without a label reference) can only be used to skip one loop iteration.

The break statement, without a label reference, can only be used to jump out of a loop or a switch.

With a label reference, the break statement can be used to jump out of any code block:

Example
var cars = [“BMW”, “Volvo”, “Saab”, “Ford”];
list: {
    text += cars[0] + “
“;
    text += cars[1] + “
“;
    text += cars[2] + “
“;
    break list;
    text += cars[3] + “
“;
    text += cars[4] + “
“;
    text += cars[5] + “
“;
}
»
A code block is a block of code between { and }.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »

❮ Previous Next ❯

JavaScript Type Conversion

Toggle navigation
TUTORIAL HOME
JavaScript Type Conversion
❮ Previous Next ❯
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” *
typeof null                   // Returns “object”
»
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 *
The data type of a variable that has not been assigned a value is also undefined *
You cannot use typeof to determine if a JavaScript object is an array (or a date).

The Data Type of typeof
The typeof operator is not a variable. It is an operator. Operators ( + – * / ) do not have any data type.

But, the typeof operator always returns a string (containing the type of the operand).

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] }”
»
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;
}
»

Or even simpler, you can check if the object is an Array function:

Example
function isArray(myArray) {
    return myArray.constructor === Array;
}
»

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;
}
»

Or even simpler, you can check if the object is a Date function:

Example
function isDate(myDate) {
    return myDate.constructor === Date;
}
»

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
»
The Number method toString() does the same.

Example
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
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
The Unary + Operator
The unary + operator can be used to convert a variable to a number:

Example
var y = “5”;      // y is a string
var x = + y;      // x is a number
»
If the variable cannot be converted, it will still become a number, but with the value NaN (Not a number):

Example
var y = “John”;   // y is a string
var x = + y;      // x is a number (NaN)
»
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” + 2     // returns 52        because 2 is converted to “2”
“5” – 2     // returns 3         because “5” is converted to 5
“5” * “2”   // returns 10        because “5” and “2” are converted to 5 and 2
»
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 Type Conversion Table
This table shows the result of converting different JavaScript values to Number, String, and Boolean:

Original
Value Converted
to Number Converted
to String Converted
to Boolean Try it
false 0 “false” false Try it »
true 1 “true” true Try it »
0 0 “0” false Try it »
1 1 “1” true Try it »
“0” 0 “0” true Try it »
“000” 0 “000” true Try it »
“1” 1 “1” true Try it »
NaN NaN “NaN” false Try it »
Infinity Infinity “Infinity” true Try it »
-Infinity -Infinity “-Infinity” true Try it »
“” 0 “” false Try it »
“20” 20 “20” true Try it »
“twenty” NaN “twenty” true Try it »
[ ] 0 “” true Try it »
[20] 20 “20” true Try it »
[10,20] NaN “10,20” true Try it »
[“twenty”] NaN “twenty” true Try it »
[“ten”,”twenty”] NaN “ten,twenty” true Try it »
function(){} NaN “function(){}” true Try it »
{ } NaN “[object Object]” true Try it »
null 0 “null” false Try it »
undefined NaN “undefined” false Try it »
Values in quotes indicate string values.

Red values indicate values (some) programmers might not expect.

❮ Previous Next ❯

JavaScript Bitwise Operations

Toggle navigation
TUTORIAL HOME
JavaScript Bitwise Operations
❮ Previous Next ❯
JavaScript Bitwise Operators
Operator Description Example Same as Result Same as
& AND 5 & 1 0101 & 0001 1 0001
| OR 5 | 1 0101 | 0001 5 0101
~ NOT ~ 5 ~0101 10 1010
^ XOR 5 ^ 1 0101 ^ 0001 4 0100
<< Zero fill left shift 5 << 1 0101 << 1 10 1010
>> Signed right shift 5 >> 1 0101 >> 1   2 0010
>>> Zero fill right shift 5 >>> 1 0101 >>> 1   2 0010
The examples above uses 4 bits unsigned examples. But JavaScript uses 64 bits signed numbers.

Because of this (in JavaScript) ~ 5 will not return 10. It will return -6.

0000000000000000000000000000000000000000000000000000000000000101

will return:

1111111111111111111111111111111111111111111111111111111111111010

Bitwise AND
When a bitwise AND is performed on a pair of bits, it returns 1 if both bits are 1.

One bit example:
Operation Result
0 & 0 0
0 & 1 0
1 & 0 0
1 & 1 1
4 bits example:
Operation Result
1111 & 0000 0000
1111 & 0001 0001
1111 & 0010 0010
1111 & 0100 0100
Bitwise OR
When a bitwise OR is performed on a pair of bits, it returns 1 if one of the bits are 1:

One bit example:
Operation Result
0 | 0 0
0 | 1 1
1 | 0 1
1 | 1 1
4 bits example:
Operation Result
1111 | 0000 1111
1111 | 0001 1111
1111 | 0010 1111
1111 | 0100 1111
Bitwise XOR
When a bitwise XOR is performed on a pair of bits, it returns 1 if the bits are different:

One bit example:
Operation Result
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
4 bits example:
Operation Result
1111 ^ 0000 1111
1111 ^ 0001 1110
1111 ^ 0010 1101
1111 ^ 0100 1011
JavaScript Bitwise Operations
JavaScript bitwise operations works on 32 bits signed integers.

Any number in a bitwise operation is converted into a 32 bit signed integer.

The result of a bitwise operation is converted back into a JavaScript number.

JavaScript Bitwise AND (&)
Bitwise AND returns 1 only if both bits are 1:

Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
5 & 1 00000000000000000000000000000001 (1)
Example
var x = 5 & 1;
»
JavaScript Bitwise OR (|)
Bitwise or returns 1 if one of the bits are 1:

Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
5 | 1 00000000000000000000000000000101 (5)
Example
var x = 5 | 1;
»
JavaScript Bitwise XOR (^)
Bitwise XOR returns 1 if the bits are different:

Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
5 ^ 1 00000000000000000000000000000100 (4)
Example
var x = 5 ^ 1;
»
JavaScript Bitwise NOT (~)
Decimal Binary
5 00000000000000000000000000000101
~5 11111111111111111111111111111010 (-6)
Example
var x = ~5;
»
JavaScript (Zero Fill) Bitwise Left Shift (<<)
This is a zero fill left shift. One or more zero bits are pushed in from the right, and the leftmost bits fall off:

Decimal Binary
5 00000000000000000000000000000101
5 << 1 00000000000000000000000000001010 (10)
Example
var x = 5 << 1;
»
JavaScript (Sign Preserving) Bitwise Right Shift (>>)
This is a sign preserving right shift. Copies of the leftmost bit are pushed in from the left, and the rightmost bits fall off:

Decimal Binary
-5 11111111111111111111111111111011
-5 >> 1 11111111111111111111111111111101 (-3)
Example
var x = -5 >> 1;
»
JavaScript (Zero Fill) Right Shift (>>>)
This is a zero fill right shift. One or more zero bits are pushed in from the left, and the rightmost bits fall off:

Decimal Binary
5 00000000000000000000000000000101
5 >>> 1 00000000000000000000000000000010 (2)
Example
var x = 5 >>> 1;
»
Signed Numbers
Signed numbers with only one bit set is easy to understand:

Binary Representation Decimal value
00000000000000000000000000000001 1
00000000000000000000000000000010 2
00000000000000000000000000000100 4
00000000000000000000000000001000 8
00000000000000000000000000010000 16
00000000000000000000000000100000 32
00000000000000000000000001000000 64
Setting a few more bits reveals the binary pattern:

Binary Representation Decimal value
00000000000000000000000000000101 5 (4 + 1)
00000000000000000000000000001101 13 (8 + 4 + 1)
00000000000000000000000000101101 45 (32 + 8 + 4 + 1)
JavaScript numbers are stored in two’s complement format.

This means that a negative number is the bitwise NOT of the number plus 1:

Binary Representation Decimal value
00000000000000000000000000000101 5
11111111111111111111111111111011 -6
00000000000000000000000000101000 40
11111111111111111111111111011000 -41
Converting Decimal to Binary
Example
function dec2bin(dec){
    return (dec >>> 0).toString(2);
}
»
Converting Binary to Decimal
Example
function bin2dec(bin){
    return parseInt(bin, 2).toString(10);
}
»

❮ Previous Next ❯