Blog

  • JavaScript Events

    Understanding Events and Event Handlers

    An event is something that happens when user interact with the web page, such as when he clicked a link or button, entered text into an input box or textarea, made selection in a select box, pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some cases, the Browser itself can trigger the events, such as the page load and unload events.

    When an event occur, you can use a JavaScript event handler (or an event listener) to detect them and perform specific task or set of tasks. By convention, the names for event handlers always begin with the word “on”, so an event handler for the click event is called onclick, similarly an event handler for the load event is called onload, event handler for the blur event is called onblur, and so on.

    There are several ways to assign an event handler. The simplest way is to add them directly to the start tag of the HTML elements using the special event-handler attributes. For example, to assign a click handler for a button element, we can use onclick attribute, like this:

    Example

    <button type="button" onclick="alert('Hello World!')">Click Me</button>

    However, to keep the JavaScript seperate from HTML, you can set up the event handler in an external JavaScript file or within the <script> and </script> tags, like this:

    Example

    <button type="button" id="myBtn">Click Me</button>
    <script>
    
    function sayHello() {
        alert('Hello World!');
    }
    document.getElementById("myBtn").onclick = sayHello;
    </script>

    Note: Since HTML attributes are case-insensitive so onclick may also be written as onClickOnClick or ONCLICK. But its value is case-sensitive.

    In general, the events can be categorized into four main groups — mouse eventskeyboard eventsform events and document/window events. There are many other events, we will learn about them in later chapters. The following section will give you a brief overview of the most useful events one by one along with the real life practice examples.

    Mouse Events

    A mouse event is triggered when the user click some element, move the mouse pointer over an element, etc. Here’re some most important mouse events and their event handler.

    The Click Event (onclick)

    The click event occurs when a user clicks on an element on a web page. Often, these are form elements and links. You can handle a click event with an onclick event handler.

    The following example will show you an alert message when you click on the elements.

    Example

    <button type="button" onclick="alert('You have clicked a button!');">Click Me</button>
    <a href="#" onclick="alert('You have clicked a link!');">Click Me</a>

    The Contextmenu Event (oncontextmenu)

    The contextmenu event occurs when a user clicks the right mouse button on an element to open a context menu. You can handle a contextmenu event with an oncontextmenu event handler.

    The following example will show an alert message when you right-click on the elements.

    Example

    <button type="button" oncontextmenu="alert('You have right-clicked a button!');">Right Click on Me</button>
    <a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right Click on Me</a>

    The Mouseover Event (onmouseover)

    The mouseover event occurs when a user moves the mouse pointer over an element.

    You can handle the mouseover event with the onmouseover event handler. The following example will show you an alert message when you place mouse over the elements.

    Example

    <button type="button" onmouseover="alert('You have placed mouse pointer over a button!');">Place Mouse Over Me</button>
    <a href="#" onmouseover="alert('You have placed mouse pointer over a link!');">Place Mouse Over Me</a>

    The Mouseout Event (onmouseout)

    The mouseout event occurs when a user moves the mouse pointer outside of an element.

    You can handle the mouseout event with the onmouseout event handler. The following example will show you an alert message when the mouseout event occurs.

    Example

    <button type="button" onmouseout="alert('You have moved out of the button!');">Place Mouse Inside Me and Move Out</button>
    <a href="#" onmouseout="alert('You have moved out of the link!');">Place Mouse Inside Me and Move Out</a>

    Keyboard Events

    A keyboard event is fired when the user press or release a key on the keyboard. Here’re some most important keyboard events and their event handler.

    The Keydown Event (onkeydown)

    The keydown event occurs when the user presses down a key on the keyboard.

    You can handle the keydown event with the onkeydown event handler. The following example will show you an alert message when the keydown event occurs.

    Example

    <input type="text" onkeydown="alert('You have pressed a key inside text input!')">
    <textarea onkeydown="alert('You have pressed a key inside textarea!')"></textarea>

    The Keyup Event (onkeyup)

    The keyup event occurs when the user releases a key on the keyboard.

    You can handle the keyup event with the onkeyup event handler. The following example will show you an alert message when the keyup event occurs.

    Example

    <input type="text" onkeyup="alert('You have released a key inside text input!')">
    <textarea onkeyup="alert('You have released a key inside textarea!')"></textarea>

    The Keypress Event (onkeypress)

    The keypress event occurs when a user presses down a key on the keyboard that has a character value associated with it. For example, keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc. will not generate a keypress event, but will generate a keydown and keyup event.

    You can handle the keypress event with the onkeypress event handler. The following example will show you an alert message when the keypress event occurs.

    Example

    <input type="text" onkeypress="alert('You have pressed a key inside text input!')">
    <textarea onkeypress="alert('You have pressed a key inside textarea!')"></textarea>

    Form Events

    A form event is fired when a form control receive or loses focus or when the user modify a form control value such as by typing text in a text input, select any option in a select box etc. Here’re some most important form events and their event handler.

    The Focus Event (onfocus)

    The focus event occurs when the user gives focus to an element on a web page.

    You can handle the focus event with the onfocus event handler. The following example will highlight the background of text input in yellow color when it receives the focus.

    Example

    <script>
    
    function highlightInput(elm){
        elm.style.background = "yellow";
    }    
    </script> <input type="text" onfocus="highlightInput(this)"> <button type="button">Button</button>

    Note: The value of this keyword inside an event handler refers to the element which has the handler on it (i.e. where the event is currently being delivered).

    The Blur Event (onblur)

    The blur event occurs when the user takes the focus away from a form element or a window.

    You can handle the blur event with the onblur event handler. The following example will show you an alert message when the text input element loses focus.

    Example

    <input type="text" onblur="alert('Text input loses focus!')">
    <button type="button">Submit</button>

    To take the focus away from a form element first click inside of it then press the tab key on the keyboard, give focus on something else, or click outside of it.

    The Change Event (onchange)

    The change event occurs when a user changes the value of a form element.

    You can handle the change event with the onchange event handler. The following example will show you an alert message when you change the option in the select box.

    Example

    <select onchange="alert('You have changed the selection!');">
    
    &lt;option&gt;Select&lt;/option&gt;
    &lt;option&gt;Male&lt;/option&gt;
    &lt;option&gt;Female&lt;/option&gt;
    </select>

    The Submit Event (onsubmit)

    The submit event only occurs when the user submits a form on a web page.

    You can handle the submit event with the onsubmit event handler. The following example will show you an alert message while submitting the form to the server.

    Example

    <form action="action.php" method="post" onsubmit="alert('Form data will be submitted to the server!');">
    
    &lt;label&gt;First Name:&lt;/label&gt;
    &lt;input type="text" name="first-name" required&gt;
    &lt;input type="submit" value="Submit"&gt;
    </form>

    Document/Window Events

    Events are also triggered in situations when the page has loaded or when user resize the browser window, etc. Here’re some most important document/window events and their event handler.

    The Load Event (onload)

    The load event occurs when a web page has finished loading in the web browser.

    You can handle the load event with the onload event handler. The following example will show you an alert message as soon as the page finishes loading.

    Example

    <body onload="window.alert('Page is loaded successfully!');">
    
    &lt;h1&gt;This is a heading&lt;/h1&gt;
    &lt;p&gt;This is paragraph of text.&lt;/p&gt;
    </body>

    The Unload Event (onunload)

    The unload event occurs when a user leaves the current web page.

    You can handle the unload event with the onunload event handler. The following example will show you an alert message when you try to leave the page.

    Example

    <body onunload="alert('Are you sure you want to leave this page?');">
    
    &lt;h1&gt;This is a heading&lt;/h1&gt;
    &lt;p&gt;This is paragraph of text.&lt;/p&gt;
    </body>

    The Resize Event (onresize)

    The resize event occurs when a user resizes the browser window. The resize event also occurs in situations when the browser window is minimized or maximized.

    You can handle the resize event with the onresize event handler. The following example will show you an alert message when you resize the browser window to a new width and height.

    Example

    <p id="result"></p>
    <script>
    
    function displayWindowSize() {
        let w = window.outerWidth;
        let h = window.outerHeight;
        let txt = "Window size: width=" + w + ", height=" + h;
        document.getElementById("result").innerHTML = txt;
    }
    window.onresize = displayWindowSize;
    </script>
  • JavaScript Operators

    What are Operators in JavaScript

    Operators are symbols or keywords that tell the JavaScript engine to perform some sort of actions. For example, the addition (+) symbol is an operator that tells JavaScript engine to add two variables or values, while the equal-to (==), greater-than (>) or less-than (<) symbols are the operators that tells JavaScript engine to compare two variables or values, and so on.

    The following sections describe the different operators used in JavaScript.

    JavaScript Arithmetic Operators

    The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Here’s a complete list of JavaScript’s arithmetic operators:

    OperatorDescriptionExampleResult
    +Additionx + ySum of x and y
    -Subtractionx - yDifference of x and y.
    *Multiplicationx * yProduct of x and y.
    /Divisionx / yQuotient of x and y
    %Modulusx % yRemainder of x divided by y

    The following example will show you these arithmetic operators in action:

    Example

    let x = 10;
    let y = 4;
    alert(x + y); // 0utputs: 14
    alert(x - y); // 0utputs: 6
    alert(x * y); // 0utputs: 40
    alert(x / y); // 0utputs: 2.5
    alert(x % y); // 0utputs: 2

    JavaScript Assignment Operators

    The assignment operators are used to assign values to variables.

    OperatorDescriptionExampleIs The Same As
    =Assignx = yx = y
    +=Add and assignx += yx = x + y
    -=Subtract and assignx -= yx = x - y
    *=Multiply and assignx *= yx = x * y
    /=Divide and assign quotientx /= yx = x / y
    %=Divide and assign modulusx %= yx = x % y

    The following example will show you these assignment operators in action:

    Example

    let x;    // Declaring Variable
     
    x = 10;
    alert(x); // Outputs: 10
     
    x = 20;
    x += 30;
    alert(x); // Outputs: 50
     
    x = 50;
    x -= 20;
    alert(x); // Outputs: 30
     
    x = 5;
    x *= 25;
    alert(x); // Outputs: 125
     
    x = 50;
    x /= 10;
    alert(x); // Outputs: 5
     
    x = 100;
    x %= 15;
    alert(x); // Outputs: 10

    JavaScript String Operators

    There are two operators which can also used be for strings.

    OperatorDescriptionExampleResult
    +Concatenationstr1 + str2Concatenation of str1 and str2
    +=Concatenation assignmentstr1 += str2Appends the str2 to the str1

    The following example will show you these string operators in action:

    Example

    Try this code »

    let str1 = "Hello";
    let str2 = " World!";
     
    alert(str1 + str2); // Outputs: Hello World!
     
    str1 += str2;
    alert(str1); // Outputs: Hello World!

    JavaScript Incrementing and Decrementing Operators

    The increment/decrement operators are used to increment/decrement a variable’s value.

    OperatorNameEffect
    ++xPre-incrementIncrements x by one, then returns x
    x++Post-incrementReturns x, then increments x by one
    --xPre-decrementDecrements x by one, then returns x
    x--Post-decrementReturns x, then decrements x by one

    The following example will show you how increment and decrement operators actually work:

    Example

    let x; // Declaring Variable
     
    x = 10;
    alert(++x); // Outputs: 11
    alert(x);   // Outputs: 11
     
    x = 10;
    alert(x++); // Outputs: 10
    alert(x);   // Outputs: 11
     
    x = 10;
    alert(--x); // Outputs: 9
    alert(x);   // Outputs: 9
     
    x = 10;
    alert(x--); // Outputs: 10
    alert(x);   // Outputs: 9

    JavaScript Logical Operators

    The logical operators are typically used to combine conditional statements.

    OperatorNameExampleResult
    &&Andx && yTrue if both x and y are true
    ||Orx || yTrue if either x or y is true
    !Not!xTrue if x is not true

    The following example will show you how these logical operators actually work:

    Example

    let year = 2018;
     
    // Leap years are divisible by 400 or by 4 but not 100
    if((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))){
    
    alert(year + " is a leap year.");
    } else{
    alert(year + " is not a leap year.");
    }

    You will learn about conditional statements in JavaScript if/else chapter.


    JavaScript Comparison Operators

    The comparison operators are used to compare two values in a Boolean fashion.

    OperatorNameExampleResult
    ==Equalx == yTrue if x is equal to y
    ===Identicalx === yTrue if x is equal to y, and they are of the same type
    !=Not equalx != yTrue if x is not equal to y
    !==Not identicalx !== yTrue if x is not equal to y, or they are not of the same type
    <Less thanx < yTrue if x is less than y
    >Greater thanx > yTrue if x is greater than y
    >=Greater than or equal tox >= yTrue if x is greater than or equal to y
    <=Less than or equal tox <= yTrue if x is less than or equal to y

    The following example will show you these comparison operators in action:

    Example

    let x = 25;
    let y = 35;
    let z = "25";
     
    alert(x == z);  // Outputs: true
    alert(x === z); // Outputs: false
    alert(x != y);  // Outputs: true
    alert(x !== z); // Outputs: true
    alert(x < y);   // Outputs: true
    alert(x > y);   // Outputs: false
    alert(x <= y);  // Outputs: true
    alert(x >= y);  // Outputs: false
  • JavaScript Data Types

    Data Types in JavaScript

    Data types basically specify what kind of data can be stored and manipulated within a program.

    There are six basic data types in JavaScript which can be divided into three main categories: primitive (or primary), composite (or reference), and special data types. String, Number, and Boolean are primitive data types. Object, Array, and Function (which are all types of objects) are composite data types. Whereas Undefined and Null are special data types.

    Primitive data types can hold only one value at a time, whereas composite data types can hold collections of values and more complex entities. Let’s discuss each one of them in detail.

    The String Data Type

    The string data type is used to represent textual data (i.e. sequences of characters). Strings are created using single or double quotes surrounding one or more characters, as shown below:

    Example

    let a = 'Hi there!';  // using single quotes
    let b = "Hi there!";  // using double quotes

    You can include quotes inside the string as long as they don’t match the enclosing quotes.

    Example

    let a = "Let's have a cup of coffee."; // single quote inside double quotes
    let b = 'He said "Hello" and left.';  // double quotes inside single quotes
    let c = 'We\'ll never give up.';     // escaping single quote with backslash

    You will learn more about the strings in JavaScript strings chapter.


    The Number Data Type

    The number data type is used to represent positive or negative numbers with or without decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to 1.5×10-4).

    Example

    let a = 25;         // integer
    let b = 80.5;       // floating-point number
    let c = 4.25e+6;    // exponential notation, same as 4.25e6 or 4250000
    let d = 4.25e-6;    // exponential notation, same as 0.00000425

    The Number data type also includes some special values which are: Infinity-Infinity and NaN. Infinity represents the mathematical Infinity , which is greater than any number. Infinity is the result of dividing a nonzero number by 0, as demonstrated below:

    Example

    alert(16 / 0);  // Output: Infinity
    alert(-16 / 0); // Output: -Infinity
    alert(16 / -0); // Output: -Infinity

    While NaN represents a special Not-a-Number value. It is a result of an invalid or an undefined mathematical operation, like taking the square root of -1 or dividing 0 by 0, etc.

    Example

    alert("Some text" / 2);       // Output: NaN
    alert("Some text" / 2 + 10);  // Output: NaN
    alert(Math.sqrt(-1));         // Output: NaN

    You will learn more about the numbers in JavaScript numbers chapter.


    The Boolean Data Type

    The Boolean data type can hold only two values: true or false. It is typically used to store values like yes (true) or no (false), on (true) or off (false), etc. as demonstrated below:

    Example

    let isReading = true;   // yes, I'm reading
    let isSleeping = false; // no, I'm not sleeping

    Boolean values also come as a result of comparisons in a program. The following example compares two variables and shows the result in an alert dialog box:

    Example

    let a = 2, b = 5, c = 10;
     
    alert(b > a) // Output: true
    alert(b > c) // Output: false

    You will learn more about the comparisons in JavaScript if/else chapter.


    The Undefined Data Type

    The undefined data type can only have one value-the special value undefined. If a variable has been declared, but has not been assigned a value, has the value undefined.

    Example

    let a;
    let b = "Hello World!";
     
    alert(a) // Output: undefined
    alert(b) // Output: Hello World!

    The Null Data Type

    This is another special data type that can have only one value-the null value. A null value means that there is no value. It is not equivalent to an empty string ("") or 0, it is simply nothing.

    A variable can be explicitly emptied of its current contents by assigning it the null value.

    Example

    let a = null;
    alert(a); // Output: null
     
    let b = "Hello World!";
    alert(b); // Output: Hello World!
     
    b = null;
    alert(b) // Output: null

    The Object Data Type

    The object is a complex data type that allows you to store collections of data.

    An object contains properties, defined as a key-value pair. A property key (name) is always a string, but the value can be any data type, like strings, numbers, booleans, or complex data types like arrays, function and other objects. You’ll learn more about objects in upcoming chapters.

    The following example will show you the simplest way to create an object in JavaScript.

    Example

    let emptyObject = {};
    let person = {"name": "Clark", "surname": "Kent", "age": "36"};
     
    // For better reading
    let car = {
    
    "modal": "BMW X3",
    "color": "white",
    "doors": 5
    }

    You can omit the quotes around property name if the name is a valid JavaScript name. That means quotes are required around "first-name" but are optional around firstname. So the car object in the above example can also be written as:

    Example

    let car = {
    
    modal: "BMW X3",
    color: "white",
    doors: 5
    }

    You will learn more about the objects in JavaScript objects chapter.


    The Array Data Type

    An array is a type of object used for storing multiple values in single variable. Each value (also called an element) in an array has a numeric position, known as its index, and it may contain data of any data type-numbers, strings, booleans, functions, objects, and even other arrays. The array index starts from 0, so that the first array element is arr[0] not arr[1].

    The simplest way to create an array is by specifying the array elements as a comma-separated list enclosed by square brackets, as shown in the example below:

    Example

    let colors = ["Red", "Yellow", "Green", "Orange"];
    let cities = ["London", "Paris", "New York"];
     
    alert(colors[0]);   // Output: Red
    alert(cities[2]);   // Output: New York

    You will learn more about the arrays in JavaScript arrays chapter.


    The Function Data Type

    The function is callable object that executes a block of code. Since functions are objects, so it is possible to assign them to variables, as shown in the example below:

    Example

    let greeting = function(){ 
    
    return "Hello World!"; 
    } // Check the type of greeting variable alert(typeof greeting) // Output: function alert(greeting()); // Output: Hello World!

    In fact, functions can be used at any place any other value can be used. Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to other functions, and functions can be returned from functions. Consider the following function:

    Example

    function createGreeting(name){
    
    return "Hello, " + name;
    } function displayGreeting(greetingFunction, userName){
    return greetingFunction(userName);
    } let result = displayGreeting(createGreeting, "Peter"); alert(result); // Output: Hello, Peter

    You will learn more about the functions in JavaScript functions chapter.


    The typeof Operator

    The typeof operator can be used to find out what type of data a variable or operand contains. It can be used with or without parentheses (typeof(x) or typeof x).

    The typeof operator is particularly useful in the situations when you need to process the values of different types differently, but you need to be very careful, because it may produce unexpected result in some cases, as demonstrated in the following example:

    Example

    // Numbers
    typeof 15;  // Returns: "number"
    typeof 42.7;  // Returns: "number"
    typeof 2.5e-4;  // Returns: "number"
    typeof Infinity;  // Returns: "number"
    typeof NaN;  // Returns: "number". Despite being "Not-A-Number"
     
    // Strings
    typeof '';  // Returns: "string"
    typeof 'hello';  // Returns: "string"
    typeof '12';  // Returns: "string". Number within quotes is typeof string
     
    // Booleans
    typeof true;  // Returns: "boolean"
    typeof false;  // Returns: "boolean"
     
    // Undefined
    typeof undefined;  // Returns: "undefined"
    typeof undeclaredVariable; // Returns: "undefined"
     
    // Null
    typeof Null;  // Returns: "object"
     
    // Objects
    typeof {name: "John", age: 18};  // Returns: "object"
     
    // Arrays
    typeof [1, 2, 4];  // Returns: "object"
     
    // Functions
    typeof function(){};  // Returns: "function"

    As you can clearly see in the above example when we test the null value using the typeof operator (line no-22), it returned “object” instead of “null”.

    This is a long-standing bug in JavaScript, but since lots of codes on the web written around this behavior, and thus fixing it would create a lot more problem, so idea of fixing this issue was rejected by the committee that design and maintains JavaScript.

  • JavaScript Generating Output

    Generating Output in JavaScript

    There are certain situations in which you may need to generate output from your JavaScript code. For example, you might want to see the value of variable, or write a message to browser console to help you debug an issue in your running JavaScript code, and so on.

    In JavaScript there are several different ways of generating output including writing output to the browser window or browser console, displaying output in dialog boxes, writing output into an HTML element, etc. We’ll take a closer look at each of these in the following sections.

    Writing Output to Browser Console

    You can easily outputs a message or writes data to the browser console using the console.log() method. This is a simple, but very powerful method for generating detailed output. Here’s an example:

    Example

    // Printing a simple text message
    console.log("Hello World!"); // Prints: Hello World!
    
    // Printing a variable value 
    let x = 10;
    let y = 20;
    let sum = x + y;
    console.log(sum); // Prints: 30

    Tip: To access your web browser’s console, first press F12 key on the keyboard to open the developer tools then click on the console tab. It looks something like the screenshot here.


    Displaying Output in Alert Dialog Boxes

    You can also use alert dialog boxes to display the message or output data to the user. An alert dialog box is created using the alert() method. Here’s is an example:

    Example

    // Displaying a simple text message
    alert("Hello World!"); // Outputs: Hello World!
    
    // Displaying a variable value 
    let x = 10;
    let y = 20;
    let sum = x + y;
    alert(sum); // Outputs: 30

    Writing Output to the Browser Window

    You can use the document.write() method to write the content to the current document only while that document is being parsed. Here’s an example:

    Example

    // Printing a simple text message
    document.write("Hello World!"); // Prints: Hello World!
    
    // Printing a variable value 
    let x = 10;
    let y = 20;
    let sum = x + y;
    document.write(sum); // Prints: 30

    If you use the document.write() method method after the page has been loaded, it will overwrite all the existing content in that document. Check out the following example:

    Example

    <h1>This is a heading</h1>
    <p>This is a paragraph of text.</p>
    
    <button type="button" onclick="document.write('Hello World!')">Click Me</button>

    Inserting Output Inside an HTML Element

    You can also write or insert output inside an HTML element using the element’s innerHTML property. However, before writing the output first we need to select the element using a method such as getElementById(), as demonstrated in the following example:

    Example

    <p id="greet"></p>
    <p id="result"></p>
    
    <script>
    // Writing text string inside an element
    document.getElementById("greet").innerHTML = "Hello World!";
    
    // Writing a variable value inside an element
    let x = 10;
    let y = 20;
    let sum = x + y;
    document.getElementById("result").innerHTML = sum;
    </script>

    You will learn about manipulating HTML element in detail in JavaScript DOM manipulation chapter.

  • JavaScript Variables

    What is Variable?

    Variables are fundamental to all programming languages. Variables are used to store data, like string of text, numbers, etc. The data or value stored in the variables can be set, updated, and retrieved whenever needed. In general, variables are symbolic names for values.

    There are three ways to declare variables in JavaScript: varlet and const.

    The var keyword is the older way of declaring variables, whereas the let and const keywords are introduced in JavaScript ES6. The main difference between them is the variables declared with the let and const keywords are block scoped ({}), that means they will only be available inside the code blocks (functionsloops and conditions) where they are declared and it sub-blocks, whereas the variables declared with the var keyword are function scoped or globally scoped, depending on whether they are declared within a function or outside of any function.

    We’ll learn more about them in upcoming chapters. Now let’s take a look at the following example where we’ve created some variables with the let keyword, and simply used the assignment operator (=) to assign values to them, like this: let varName = value;

    Example

    let name = "Peter Parker";
    let age = 21;
    let isMarried = false;

    Tip: Always give meaningful names to your variables. Additionally, for naming the variables that contain multiple words, camelCase is commonly used. In this convention all words after the first should have uppercase first letters, e.g. myLongVariableName.

    In the above example we have created three variables, first one has assigned with a string value, the second one has assigned with a number, whereas the last one assigned with a boolean value. Variables can hold different types of data, we’ll learn about them in later chapter.

    In JavaScript, variables can also be declared without having any initial values assigned to them. This is useful for variables which are supposed to hold values like user inputs.

    Example

    // Declaring Variable
    let userName;
     
    // Assigning value
    userName = "Clark Kent";

    Note: In JavaScript, if a variable has been declared, but has not been assigned a value explicitly, is automatically assigned the value undefined.

    The const keyword works exactly the same as let, except that variables declared using const keyword cannot be reassigned later in the code. Here’s an example:

    Example

    // Declaring constant
    const PI = 3.14;
    console.log(PI); // 3.14
    
    // Trying to reassign
    PI = 10; // error

    Note: The let and const keywords are not supported in older browsers like IE10. IE11 support them partially. See the JS ES6 features chapter to know how to start using ES6 today.


    Declaring Multiple Variables at Once

    In addition, you can also declare multiple variables and set their initial values in a single statement. Each variable are separated by commas, as demonstrated in the following example:

    Example

    // Declaring multiple Variables
    let name = "Peter Parker", age = 21, isMarried = false;
     
    /* Longer declarations can be written to span
    multiple lines to improve the readability */
    let name = "Peter Parker",
    age = 21,
    isMarried = false;
    

    Naming Conventions for JavaScript Variables

    These are the following rules for naming a JavaScript variable:

    • A variable name must start with a letter, underscore (_), or dollar sign ($).
    • A variable name cannot start with a number.
    • A variable name can only contain alpha-numeric characters (A-z0-9) and underscores.
    • A variable name cannot contain spaces.
    • A variable name cannot be a JavaScript keyword or a JavaScript reserved word.
  • JavaScript Syntax

    Understanding the JavaScript Syntax

    The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

    A JavaScript consists of JavaScript statements that are placed within the <script></script> HTML tags in a web page, or within the external JavaScript file having .js extension.

    The following example shows how JavaScript statements look like:

    Example

    let x = 5;
    let y = 10;
    let sum = x + y;
    document.write(sum); // Prints variable value

    You will learn what each of these statements means in upcoming chapters.


    Case Sensitivity in JavaScript

    JavaScript is case-sensitive. This means that variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters.

    For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly, the method name getElementById() must be typed with the exact case not as getElementByID().

    Example

    let myVar = "Hello World!";
    console.log(myVar);
    console.log(MyVar);
    console.log(myvar);

    If you checkout the browser console by pressing the f12 key on the keyboard, you’ll see a line something like this: “Uncaught ReferenceError: MyVar is not defined”.


    JavaScript Comments

    A comment is simply a line of text that is completely ignored by the JavaScript interpreter. Comments are usually added with the purpose of providing extra information pertaining to source code. It will not only help you understand your code when you look after a period of time but also others who are working with you on the same project.

    JavaScript support single-line as well as multi-line comments. Single-line comments begin with a double forward slash (//), followed by the comment text. Here’s an example:

    Example

    // This is my first JavaScript program
    document.write("Hello World!");

    Whereas, a multi-line comment begins with a slash and an asterisk (/*) and ends with an asterisk and slash (*/). Here’s an example of a multi-line comment.

    Example

    /* This is my first program 
    in JavaScript */
    document.write("Hello World!");
  • JavaScript Getting Started

    Getting Started with JavaScript

    Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge of HTML and CSS.

    If you’re just starting out in the world of web development, start learning from here »

    Well, let’s get started with the most popular client-side scripting language.

    Adding JavaScript to Your Web Pages

    There are typically three ways to add JavaScript to a web page:

    • Embedding the JavaScript code between a pair of <script> and </script> tag.
    • Creating an external JavaScript file with the .js extension and then load it within the page through the src attribute of the <script> tag.
    • Placing the JavaScript code directly inside an HTML tag using the special tag attributes such as onclickonmouseoveronkeypressonload, etc.

    The following sections will describe each of these procedures in detail:

    Embedding the JavaScript Code

    You can embed the JavaScript code directly within your web pages by placing it between the <script> and </script> tags. The <script> tag indicates the browser that the contained statements are to be interpreted as executable script and not HTML. Here’s an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Embedding JavaScript&lt;/title&gt;
    </head> <body>
    &lt;script&gt;
    let greet = "Hello World!";
    document.write(greet); // Prints: Hello World!
    &lt;/script&gt;
    </body> </html>

    The JavaScript code in the above example will simply prints a text message on the web page. You will learn what each of these JavaScript statements means in upcoming chapters.

    Note: The type attribute for <script> tag (i.e. <script type="text/javascript">) is no longer required since HTML5. JavaScript is the default scripting language for HTML5.


    Calling an External JavaScript File

    You can also place your JavaScript code into a separate file with a .js extension, and then call that file in your document through the src attribute of the <script> tag, like this:

    <script src=”js/hello.js”></script>

    This is useful if you want the same scripts available to multiple documents. It saves you from repeating the same task over and over again, and makes your website much easier to maintain.

    Well, let’s create a JavaScript file named “hello.js” and place the following code in it:

    Example

    // A function to display a message
    function sayHello() {
    
    alert("Hello World!");
    } // Call function on click of the button document.getElementById("myBtn").onclick = sayHello;

    Now, you can call this external JavaScript file within a web page using the <script> tag, like this:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Including External JavaScript File&lt;/title&gt;        
    </head> <body>
    &lt;button type="button" id="myBtn"&gt;Click Me&lt;/button&gt;
    &lt;script src="js/hello.js"&gt;&lt;/script&gt;
    </body> </html>

    Note: Usually when an external JavaScript file is downloaded for first time, it is stored in the browser’s cache (just like images and style sheets), so it won’t need to be downloaded multiple times from the web server that makes the web pages load more quickly.


    Placing the JavaScript Code Inline

    You can also place JavaScript code inline by inserting it directly inside the HTML tag using the special tag attributes such as onclickonmouseoveronkeypressonload, etc.

    However, you should avoid placing large amount of JavaScript code inline as it clutters up your HTML with JavaScript and makes your JavaScript code difficult to maintain. Here’s an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Inlining JavaScript&lt;/title&gt;        
    </head> <body>
    &lt;button onclick="alert('Hello World!')"&gt;Click Me&lt;/button&gt;
    </body> </html>

    The above example will show you an alert message on click of the button element.

    Tip: You should always keep the content and structure of your web page (i.e. HTML) separate out from presentation (CSS), and behavior (JavaScript).


    Positioning of Script inside HTML Document

    The <script> element can be placed in the <head>, or <body> section of an HTML document. But ideally, scripts should be placed at the end of the body section, just before the closing </body> tag, it will make your web pages load faster, since it prevents obstruction of initial page rendering.

    Each <script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code, so placing them in the head section (i.e. <head> element) of the document without any valid reason will significantly impact your website performance.

    Tip: You can place any number of <script> element in a single document. However, they are processed in the order in which they appear in the document, from top to bottom.


    Difference Between Client-side and Server-side Scripting

    Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browser, while server-side scripting languages such as PHP, ASP, Java, Python, Ruby, etc. runs on the web server and the output sent back to the web browser in HTML format.

    Client-side scripting has many advantages over traditional server-side scripting approach. For example, you can use JavaScript to check if the user has entered invalid data in form fields and show notifications for input errors accordingly in real-time before submitting the form to the web-server for final data validation and further processing in order to prevent unnecessary network bandwidth usages and the exploitation of server system resources.

    Also, response from a server-side script is slower as compared to a client-side script, because server-side scripts are processed on the remote computer not on the user’s local computer.

    You can learn more about server-side scripting in PHP tutorial section.

  • JavaScript Tutorial

    JavaScript is the most popular and widely used client-side scripting language. Client-side scripting refers to scripts that run within your web browser. JavaScript is designed to add interactivity and dynamic effects to the web pages by manipulating the content returned from a web server.

    JavaScript was originally developed as LiveScript by Netscape in the mid 1990s. It was later renamed to JavaScript in 1995, and became an ECMA standard in 1997. Now JavaScript is the standard client-side scripting language for web-based applications, and it is supported by virtually all web browsers available today, such as Google Chrome, Mozilla Firefox, Apple Safari, etc.

    JavaScript is an object-oriented language, and it also has some similarities in syntax to Java programming language. But, JavaScript is not related to Java in any way.

    JavaScript is officially maintained by ECMA (European Computer Manufacturers Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of the ECMAScript standard.

    Tip: Our JavaScript tutorial will help you to learn the fundamentals of JavaScript scripting language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basics and gradually move forward by learning a little bit every day.


    What You Can Do with JavaScript

    There are lot more things you can do with JavaScript.

    • You can modify the content of a web page by adding or removing elements.
    • You can change the style and position of the elements on a web page.
    • You can monitor events like mouse click, hover, etc. and react to it.
    • You can perform and control transitions and animations.
    • You can create alert pop-ups to display info or warning messages to the user.
    • You can perform operations based on user inputs and display the results.
    • You can validate user inputs before submitting it to the server.

    The list does not end here, there are many other interesting things that you can do with JavaScript. You will learn about all of them in detail in upcoming chapters.


    What This Tutorial Covers

    This JavaScript tutorial series covers all the fundamental programming concepts, including data types, operators, creating and using variables, generating outputs, structuring your code to make decisions in your programs or to loop over the same block of code multiple times, creating and manipulating strings and arrays, defining and calling functions, and so on.

    Once you’re comfortable with the basics, you’ll move on to next level that explains the idea of objects, the Document Object Model (DOM) and Browser Object Model (BOM), as well as how to make use of the native JavaScript objects like Date, Math, etc., and perform type conversions.

    Finally, you’ll explore some advanced concepts like event listeners, event propagation, borrowing methods from other objects, hoisting behavior of JavaScript, encoding and decoding JSON data, as well as detailed overview of new features introduced in ECMAScript 6 (or ES6).

  • Tabs and Pills

    Bootstrap Nav Components

    Bootstrap provides an easy and quick way to create basic navigation as well as components like tabs and pills which are very flexible and elegant. All the Bootstrap’s nav components, including tabs and pills, share the same base markup and styles through the base .nav class.

    Creating Basic Nav with Bootstrap

    You can use the Bootstrap .nav class to create a basic navigation menu, like this:

    Example

    <nav class="nav">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Navigation Menu

    Note: You can use the class .disabled to make a link look like disabled. But, the .disabled class only changes the visual appearance of the link by making it gray and removing the hover effect, however the link will remain clickable unless you remove the "href" attribute.


    Alignment of Nav Items

    By default, navs are left-aligned, but you can easily align them to center or right using flexbox utilities.

    The following example uses the class .justify-content-center to align nav items to center.

    Example

    <nav class="nav justify-content-center">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Nav Center Alignment

    Similarly, you can align nav items to right using the class .justify-content-end, like this:

    Example

    <nav class="nav justify-content-end">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Nav Right Alignment

    Moreover, you can even vertically stack your nav items by changing the flex item direction with the class .flex-column. Also, if you want to stack your nav vertically on smaller viewports but not on others, use it with responsive breakpoint (e.g., .flex-sm-column).

    Example

    <nav class="nav flex-column">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Vertically Stacked Nav

    Creating the Basic Tabs

    Simply, add the class .nav-tabs to the basic nav to generate a tabbed navigation, like this:

    Example

    <nav class="nav nav-tabs">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Tabbed Navigation

    See the tutorial on Bootstrap tabs to learn how to create dynamic tab to toggle between content.

    You can also add icons to your tab items to make it more attractive, as shown here:

    Example

    <nav class="nav nav-tabs">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;
        &lt;i class="bi-house-door"&gt;&lt;/i&gt; Home
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-person"&gt;&lt;/i&gt; Profile
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-envelope"&gt;&lt;/i&gt; Messages
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;
        &lt;i class="bi-bar-chart"&gt;&lt;/i&gt; Reports
    &lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Tabs with Icons

    See the tutorial on Bootstrap icons to learn how to use icons in Bootstrap. Also, check out Bootstrap icons classes to explore the icons provided by Bootstrap.


    Creating the Pills Nav

    Similarly, you can create pill based navigation by adding the class .nav-pills on the basic nav instead of class .nav-tabs, as shown in the following example:

    Example

    <nav class="nav nav-pills">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Messages&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Pills Nav

    Similarly, like nav tabs you can also add icons to your pills nav to make it more attractive:

    Example

    <nav class="nav nav-pills">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;
        &lt;i class="bi-house-door"&gt;&lt;/i&gt; Home
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-person"&gt;&lt;/i&gt; Profile
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-envelope"&gt;&lt;/i&gt; Messages
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;
        &lt;i class="bi-bar-chart"&gt;&lt;/i&gt; Reports
    &lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Pills Nav with Icons

    Additionally, you can apply the class .flex-column on the .nav element to make the pills nav appear vertically stacked. You can alternatively use responsive versions (e.g., .flex-sm-column) if you need to stack them on specific viewports but not on others.

    Example

    <nav class="nav nav-pills flex-column">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;
        &lt;i class="bi-house-door"&gt;&lt;/i&gt; Home
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-person"&gt;&lt;/i&gt; Profile
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;
        &lt;i class="bi-envelope"&gt;&lt;/i&gt; Messages
    &lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;
        &lt;i class="bi-bar-chart"&gt;&lt;/i&gt; Reports
    &lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Vertically Stacked Pills Nav

    Bootstrap Nav with Dropdown Menus

    You can add dropdown menus to a link inside tabs and pills nav with a little extra markup.

    The four CSS classes .dropdown.dropdown-toggle.dropdown-menu and .dropdown-item are required in addition to the .nav.nav-tabs or .nav-pills classes to create a simple dropdown menu inside tabs and pills nav without using any JavaScript code.

    Creating Tabs with Dropdowns

    The following example will show you how to add simple dropdown menu to a tab.

    Example

    <nav class="nav nav-tabs">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;div class="nav-item dropdown"&gt;
        &lt;a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown"&gt;Messages&lt;/a&gt;
        &lt;div class="dropdown-menu"&gt;
            &lt;a href="#" class="dropdown-item"&gt;Inbox&lt;/a&gt;
            &lt;a href="#" class="dropdown-item"&gt;Sent&lt;/a&gt;
            &lt;a href="#" class="dropdown-item"&gt;Drafts&lt;/a&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Tabs with Dropdown Menus

    Creating Pills with Dropdowns

    The following example will show you how to add simple dropdown menu to a pill nav.

    Example

    <nav class="nav nav-pills">
    
    &lt;a href="#" class="nav-item nav-link active"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Profile&lt;/a&gt;
    &lt;div class="nav-item dropdown"&gt;
        &lt;a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown"&gt;Messages&lt;/a&gt;
        &lt;div class="dropdown-menu"&gt;
            &lt;a href="#" class="dropdown-item"&gt;Inbox&lt;/a&gt;
            &lt;a href="#" class="dropdown-item"&gt;Sent&lt;/a&gt;
            &lt;a href="#" class="dropdown-item"&gt;Drafts&lt;/a&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;a href="#" class="nav-item nav-link disabled" tabindex="-1"&gt;Reports&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Pills with Dropdown Menus

    You will learn more about dropdown menus later in Bootstrap dropdowns chapter.


    Fill and Justify Nav Component

    You can force your .nav-items to extend and proportionately fill all available width using the class .nav-fill on the .nav element. In the following example all horizontal space is occupied by the nav items, but every nav item doesn’t have the same width.

    Example

    <nav class="nav nav-pills nav-fill">
    
    &lt;a href="#" class="nav-item nav-link"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;About&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link active"&gt;Explore Products&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Contact Us&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Nav Fill

    Alternatively, you can use the class .nav-justified instead of.nav-fill, if you want nav that fills all horizontal space as well as every nav item has the same width.

    Example

    <nav class="nav nav-pills nav-justified">
    
    &lt;a href="#" class="nav-item nav-link"&gt;Home&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;About&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link active"&gt;Explore Products&lt;/a&gt;
    &lt;a href="#" class="nav-item nav-link"&gt;Contact Us&lt;/a&gt;
    </nav>

    — The output of the above example will look something like this:

    Bootstrap Nav Justified
  • Bootstrap Icons

    Using Icons in Bootstrap 5

    Bootstrap now includes over 1,300 high quality icons, which are available in SVGs, SVG sprite, or web fonts format. You can use them with or without Bootstrap in any project.

    The advantage of using font icons is, you can create icons of any color just through applying the CSS color property. Also, to change the size of icons you can simply use the CSS font-size property.

    Now, let’s see how to include and use Bootstrap icons on a web page.

    Including Bootstrap Icons in a Web Page

    The simplest way to include Bootstrap icons in a web page is using the CDN link. This CDN link basically points to a remote CSS file that includes all the necessary classes to generate font icons.

    You can include Bootstrap icons in a Bootstrap template as well as in a simple web page without using the Bootstrap framework. Let’s take a look at the following example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="utf-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
    &lt;title&gt;Including Bootstrap Icons in HTML&lt;/title&gt;
    &lt;!-- Bootstrap CSS --&gt;
    &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"&gt;
    &lt;!-- Bootstrap Font Icon CSS --&gt;
    &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"&gt;
    </head> <body>
    &lt;h1&gt;&lt;i class="bi-globe"&gt;&lt;/i&gt; Hello, world!&lt;/h1&gt;
    
    &lt;!-- Bootstrap JS Bundle with Popper --&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt;
    </body> </html>

    How to Use Bootstrap Icons in Your Code

    To use Bootstrap icons in your code you’ll require an <i> tag with an individual icon class .bi-* applied on it. The general syntax for using Bootstrap icons is:

    <i class=”bi-class-name“></i>

    Where class-name is the name of the particular icon class, e.g. searchpersoncalendarstarglobefacebooktwitter, and so on. See the list of all Bootstrap icons classes.

    For example, to place search icon inside a button you could do something like this:

    Example

    <button type="submit" class="btn btn-primary"><span class="bi-search"></span> Search</button>
    <button type="submit" class="btn btn-secondary"><span class="bi-search"></span> Search</button>

    — The output of the above example will look something like this:

    Bootstrap Icons Inside Buttons

    Similarly, you can place icons inside the navs, forms, tables, paragraphs or anywhere you want. In the next chapter you will see how to use these icons in Bootstrap nav components.

    Note: Remember to leave a space after the closing tag of icon element (i.e. after </i> tag), when using the icons along with the strings of text such as inside buttons or navigation links, to ensure that there is proper spacing between the icon and text.


    Using Font Awesome Icons in Bootstrap

    You can also use external icon libraries in Bootstrap. One of the most popular and highly compatible external icon library for Bootstrap is Font Awesome. It provides over 675 icons which are available in SVG, PNG, as well as in web font format for better usability and scalability.

    You can simply use the freely available font-awesome CDN link to include it in your project. Let’s take a look at the following example to understand how it basically works:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="utf-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
    &lt;title&gt;Including Font Awesome Icons in Bootstrap&lt;/title&gt;
    &lt;!-- Bootstrap CSS --&gt;
    &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"&gt;
    &lt;!-- Font Awesome CSS --&gt;
    &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"&gt;
    </head> <body>
    &lt;h1&gt;&lt;i class="fa fa-globe"&gt;&lt;/i&gt; Hello, world!&lt;/h1&gt;
    
    &lt;!-- Bootstrap JS Bundle with Popper --&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt;
    </body> </html>

    How to Use Font Awesome Icons in Your Code

    To use Font Awesome icons in your code you’ll require an <i> tag along with a base class .fa and an individual icon class .fa-*. The general syntax for using font-awesome icons is:

    <i class=”fa fa-class-name“></i>

    Where class-name is the name of the particular icon class, e.g. searchusercalendarstarglobefacebooktwitter, and so on. See the list of all Font Awesome icons classes.

    For example, you can place font-awesome search icon inside a button like this:

    Example

    <button type="submit" class="btn btn-primary"><span class="fa fa-search"></span> Search</button>
    <button type="submit" class="btn btn-secondary"><span class="fa fa-search"></span> Search</button>

    — The output of the above example will look something like this:

    Font Awesome Icons Inside Bootstrap Buttons

    Similarly, you can place Font Awesome icons inside the navs, forms, tables, paragraphs, and other components in the same way as you do with Bootstrap icons.