JavaScript Boolean Object

JavaScript Boolean object is a member of global objects and a wrapper class. It is used to create a boolean object which holds true or false value, depending upon the value used while creating the Boolean object.

The Boolean object’s true and false values are different from the primitive boolean type’s true and false values.

As already mentioned, it has two values, true and false. The Boolean object returns false when it is passed with values such as 0, -0, an empty string(""), false, nullundefined, or Not a Number(NaN) while creating the Boolean object. Apart from all these values which set the initial value as false for the Boolean object, all other values, even an empty array([]), empty object({}) or the string “false“, will set the initial value for the Boolean object as true.

Creating JavaScript Boolean Object

To create an instance of the Boolean object, we use the new keyword with the Boolean object constructor function, providing a value at the time of creation.

Following is the syntax for it:

let bool = new Boolean(SOME_VALUE);

Depending upon the value passed, the initial value is set as true or false.

Let’s take an example,

// Creating Boolean Object
let boolObj = new Boolean(true);  
document.write(boolObj);

boolObj = new Boolean(false);  
document.write("<br>"+boolObj);

true false

JavaScript Boolean Object False

JavaScript Boolean Object will have the initial value as false if the value provided at the time of object creation is 0-0NaNnullundefined, false, empty string or even if no value is provided because the default value is also false.

let obj1 = new Boolean();
let obj2 = new Boolean(0);
let obj3 = new Boolean(null);
let obj4 = new Boolean('');
let obj5 = new Boolean(false);

document.write(obj1+" "+obj2+" "+obj3+" "+obj4+" "+obj5)

false false false false false

JavaScript Boolean Object True

Apart from the values specified above, for which the initial value of the Boolean object is false, all other values will set the value as true. Let’s take a few examples,

let obj1 = new Boolean(true);
let obj2 = new Boolean('true');
let obj3 = new Boolean('false');
let obj4 = new Boolean('hello');
let obj5 = new Boolean([]);
let obj6 = new Boolean({});

document.write(obj1+" "+obj2+" "+obj3+" "+obj4+" "+obj5+" "+obj6)

true true true true true true

JavaScript Boolean Object vs. Primitive Boolean type

As we have already mentioned that the boolean object and primitive boolean types are different. The Boolean object is a JavaScript object and not a primitive type, but an object type, which can have true or false as its value.

Let’s take an example, where we will see how the Boolean object and the primitive boolean type behave when used in a JavaScript conditional statement expression.

// Boolean object
let obj = new Boolean(false);

// using in if condition 
if(obj)
{
	document.write("It is boolean object"); // executes
}

// Primitive value
let bool = false;
if(bool)
{
	document.write("It is primitive boolean"); // does not execute
}

It is boolean object

In spite of the false value of the Boolean object, the first if statement executes, that is because when we provide an object in the if condition, it is always evaluated as true.

We can get the value of the Boolean objects by using the valueOf() method of the Boolean object and then it will be treated as a norma primitive type true or false value.

Converting Boolean Object to Primitive

We can use the valueOf() method of the Boolean object for accessing its value,

// Boolean object
let obj = new Boolean(false);

// using the value of Boolean object in condition 
if(obj.valueOf()){
	document.write("It is boolean object");   // does not execute
}
else{ 
	document.write("boolean value is false");   // executes
}

boolean value is false

Methods of Boolean Object

The following are some of the commonly used methods of the Boolean object.

  1. toString(): converts the boolean value into a string and returns the string.
  2. valueOf(): returns the primitive value of a Boolean object.

JavaScript Boolean Object Example

Let’s see another code example for the Boolean object:

<html>
    <head>
        <title>
            Using Boolean Object
        </title>
    </head>
    <body>
        <script type="text/javaScript">
            let bool1 = new Boolean(0);
            let bool2 = new Boolean(8);
            let bool3 = new Boolean(2);
            let bool4 = new Boolean("");
            let bool5 = new Boolean("Hello");
            let bool6 = new Boolean('false');
            let bool7 = new Boolean(null);
            let bool8 = new Boolean(NaN);
            document.write("0 value is boolean :" + bool1+"<br>");
            document.write("8 value is boolean :" + bool2+"<br>");
            document.write("1 value is boolean :" + bool3+"<br>");
            document.write("An empty string is boolean :" + bool4+"<br>");
            document.write("String 'Hello' is   boolean :" + bool5+"<br>");
            document.write("String 'false' is boolean :" + bool6+"<br>");
            document.write("null is boolean :" + bool7+"<br>");
            document.write("NaN is boolean :" + bool8+"<br>");
        </script>
    </body>
</html>

JavaScript Data Types

JavaScript Data types are used to identify the type of data that is stored inside a variable during the script execution. As we have already specified about the Dynamic Typed JavaScript feature so we do not have to specify the data type of the variable while declaring it.

So JavaScript data types are basically for identification purposes to know what is being stored in the variable, when it’s stored, not before that.

Dynamically typed language is a language that infers data types at runtime. It allows storing different types of values to a variable during programming.

Below we have a basic example, where we have defined a variable with a numeric value and then updated it to store a string value. So JavaScript allows this.

var x = 5;    // x is a number
x = "studytonight";    // x is string here.

JavaScript broadly supports three types of Data types, they are:

  • Primitive Type
  • Reference Type
  • Special Data Type

Let’s cover each one of this one by one while seeing which category has all data types.

JavaScript Primitive Data Type

JavaScript Primitive data types can be classified further into the following types:

  1. String Data Type
  2. Boolean Data Type
  3. Number Data Type

These are the most common data types, used for storing sequences of characters, true/false and numeric values respectively. Let’s cover them one by one with examples.

1. JavaScript String Data type

Whenever we write a character or sequence of characters inside single or double quotes then it becomes String. For example “StudyTonight“.

We can use both single or double-quotes to create string type values.

var str = "Ferari F60";  // string using double quotes

var str1 = 'Volvo S60';  // string using single quotes.

To have a single quote as part of the string we should use the double quote to enclose the string value and vice versa. And if you want to include a single quote in the string which is defined by enclosing it within single quotes only, in that case, we must use a backslash \ to escape the single quote, and similarly, we can escape the double quote too in a string value.

Let’s see an example of this:

var str1 = "Ferari's F60";    // Output: Ferari's F60

var str2 = 'Volvo "S60"';   // Output: Volvo "S60"

var str3 = 'Ferari\'s F60';    // Output: Ferari's F60

We have covered JavaScript String in details and also covered various String methods in JavaScript.

2. JavaScript Boolean Data type

JavaScript Boolean Data type is used in conditional based programming. It can have two values, either true or false.

var isOn = true;  // bulb is on

var isOn = false;  // bulb is off

We get Boolean values while comparing two numbers, for example:

doument.write(4 < 2)  // false
doument.write(4 > 2)  // true

We will see this in the JavaScript If else Flow Control tutorial.

3. JavaScript Number Data type

JavaScript Number Data type can be with or without decimal points and can have negative and positive values.

var x = 45; // Number without decimal point

var y = 45.90; // Number with decimal point - floating point

var z = -10; // Number with negative value

The JavaScript Number data type also represents some special values like Infinity-Infinity and Nan. When a positive number is divided by zero (it’s a popular case of runtime error), in JavaScript it’s represented as Infinity. Similarly, when a negative number is divided by zero we will get -Infinity.

var a = 100;
var b = -100;
var c = 0;

alert(a/c);  // Infinity 
alert(b/c);  // -Infinity

And Nan means Not a number, if we try to perform any operation between a numeric value and a non-numeric value like a string we will get this as output.

var a = "Studytonight";
var b = 7;

alert(a/b);    // Nan

JavaScript Composite Data types

These data types can hold collections of values and more complex entities. It is further divided into Object, Array and Function.

  1. Object data type
  2. Array data type
  3. Function data type

1. JavaScript Object Data Type

In JavaScript, an object data type is used to store the collection of data. Object’s properties are written as key:value pairs, which are separated by commas and enclosed within curly braces {}.

The key (name) must always be a string, but the value can be of any data type. This is pretty similar to a map data structure in many programming languages which also stores key-value pairs like this.

var name = { };   // It will create an empty object.

var emp = {firstname="ram", lastname="singh", salary=20000};

2. JavaScript Array Type

JavaScript Array data type is written inside a pair of square brackets [] and is used to store multiple values of the same datatype be it strings, numbers etc. The items in a JavaScript array are also written in a comma-separated manner.

Each element in the array gets a numeric position, known as its index. The array index starts from 0 or we can say that array indexes are zero-based, so that the first array element is arr[0] and not arr[1].

Let’s take an example for JavaScript array:

// Creating an Array
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

3. JavaScript Function Type

You must be thinking, how a function can be a datatype. But in JavaScript functions act as a data type which can be assigned to a variable. JavaScript Function is nothing but a set of statement inside a code block which is used to perform a specific operation and this datatype is of callable in nature. So, you can call it anywhere in the program whenever needed.

Since functions are objects, so it is possible to assign them to a variable.

Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to other functions too and can be returned from other functions as well.

var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

JavaScript Special Data types

JavaScript also has some special data types, although seeing function called as a data type would have already been special for you. But there are two more.

  1. Undefined Data type
  2. Null Data type

Let’s cover each of them one by one.

1. JavaScript Undefined Data Type

When a variable is just declared and is not assigned any value, it has undefined as its value. Yes, undefined is a valid data type in JavaScript and it can have only one value which is undefined.

We can even use this value while doing some comparison. Let’s take an example:

var a;   // Undefined

alert(a == undefined);   // returns true

2. JavaScript Null Data Type

JavaScript Null data type is used to represent no value. It is not similar to undefined, and neither it is similar to empty value or zero value. The Null datatype means, the variable has been defined but it contains no value.

The Null data type can have only one value, which is null. Let’s take an example for this:

var a = null;

alert(a);    // Output will be null

JavaScript typeOf Operator

The typeOf operator in JavaScript can be used to check the data type of any variable. Although its an operator but we are mentioning it here, because it’s oftenly used to check the data type of any variable.

Let’s take a few examples to see how this works:

// Function datatype
var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

typeOf welcome;    // function

var a = null;

typeOf a;   // null

// Array datatype
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

typeOf cars;    // array

You can try this with other data types too.

JavaScript Literals and Keywords

JavaScript Literals are the fixed value that cannot be changed, you do not need to specify any type of keyword to write literals. Literals are often used to initialize variables in programming, names of variables are string literals.

A JavaScript Literal can be a numeric, string, floating-point value, a boolean value or even an object. In simple words, any value is literal, if you write a string “Studytonight” is a literal, any number like 7007 is a literal, etc.

JavaScript supports various types of literals which are listed below:

  • Numeric Literal
  • Floating-Point Literal
  • Boolean Literal
  • String Literal
  • Array Literal
  • Regular Expression Literal
  • Object Literal

JavaScript Numeric Literal

  • It can be expressed in the decimal(base 10), hexadecimal(base 16) or octal(base 8) format.
  • Decimal numeric literals consist of a sequence of digits (0-9) without a leading 0(zero).
  • Hexadecimal numeric literals include digits(0-9), letters (a-f) or (A-F).
  • Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric literal indicates octal format.

JavaScript Numeric Literals Example

120 // decimal literal

021434 // octal literal

0x4567 // hexadecimal literal

JavaScript Floating-Point Literal

  • It contains a decimal point(.)
  • A fraction is a floating-point literal
  • It may contain an Exponent.

JavaScript Floating-Point Literal Example

6.99689 // floating-point literal

-167.39894 // negative floating-point literal

JavaScript Boolean Literal

Boolean literal supports two values only either true or false.

JavaScript Boolean Literal Example

true // Boolean literal

false // Boolean literal

JavaScript String Literal

A string literal is a combination of zero or more characters enclosed within a single(') or double quotation marks (").

JavaScript String Literal Example

"Study" // String literal

'tonight' // String literal 

String literals can have some special characters too which are tabled below.

String Special Characters:

CharacterDescription
\bIt represents a backspace.
\fIt represents a Form Feed.
\nIt represents a new line.
\rIt represents a carriage return.
\tIt represents a tab.
\vIt represents a vertical tab.
\'It represents an apostrophe or single quote.
\"It represents a double quote.
\\It represents a backslash character.
\uXXXXIt represents a Unicode character specified by a four-digit hexadecimal number.

JavaScript Array Literal

  • An array literal is a list of zero or more expressions representing array elements that are enclosed in a square bracket([]).
  • Whenever you create an array using an array literal, it is initialized with the elements specified in the square bracket.

JavaScript Array Literal Example

var emp = ["aman","anu","charita"];  // Array literal

JavaScript Regular Expression Literal

Regular Expression is a pattern, used to match a character or string in some text. It is created by enclosing the regular expression string between forward slashes.

JavaScript Regular Expression Example

var myregexp = /ab+c/; // Regular Expression literal

var myregexp = new RegExp("abc"); // Regular Expression literal

JavaScript Object Literal

It is a collection of key-value pairs enclosed in curly braces({}). The key-value pair is separated by a comma.

JavaScript Object Literal Example

var games = {cricket :11, chess :2, carom: 4}  // Object literal

JavaScript Keywords

Every programming language has its own keywords and reserved words. Every keyword is created to perform a specific task and the compiler or interpreter already knows about the built-in keywords and reserved words. JavaScript supports a rich set of keywords that are listed in the below table.

KeywordDescription
forThe for keyword is used to create a for-loop.
do/whileThe do and while both keywords are used to create loops in JavaScript.
if/elseThe if and else keywords are used to create conditional statements.
continueThe continue keyword is used to resume the loop.
breakIt is used to break the loop.
functionThe function keyword is used to declare a function.
debuggerIt is used to call the debugger function
classThe class keyword is used to declare the class.
returnReturn keyword is used to return function from the function.
floatIt is used to declare float type variable.
intIt is used to declare int type variable.
privateIt is an access modifier.
publicPublic is an access modifier that gives the class public access.
varVar is used to declare a variable.
switchThe switch creates various statement blocks and executes only on block depending on the condition or the case.
try/catchIt creates a block for error handling of the statements.

NOTE: While defining name of any function or variable, you should not use any keyword or reserved words.

In this tutorial, we learned about JavaScript literals, different types of literals along with examples. We also covered the JavaScript keywords and reserved words.