Author: saqibkhan

  •  Installation

    To get started with developing using the Electron, you need to have Node and npm(node package manager) installed. If you do not already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.

    node --version
    npm --version
    

    The above command will generate the following output −

    v6.9.1
    3.10.8
    

    Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.

    • Fire up your terminal/cmd, create a new folder named hello-world and open that folder using the cd command.
    • Now to create the package.json file using npm, use the following command.
    npm init
    
    • It will ask you for the following information −
    Package.json creation

    Just keep pressing Enter, and enter your name at the “author name” field.

    Create a new folder and open it using the cd command. Now run the following command to install Electron globally.

    $ npm install -g electron-prebuilt
    

    Once it executes, you can check if Electron is installed the right way by running the following command −

    $ electron --version
    

    You should get the output −

    v1.4.13
    

    Now that we have set up Electron, let us move on to creating our first app using it.

  •  Overview

    Why Electron?

    Electron enables you to create desktop applications with pure JavaScript by providing a runtime with rich native (operating system) APIs.

    This does not mean Electron is a JavaScript binding to graphical user interface (GUI) libraries. Instead, Electron uses web pages as its GUI, so you can also see it as a minimal Chromium browser, controlled by JavaScript. So all the electron apps are technically web pages running in a browser that can leverage your OS APIs.

    Who Uses Electron?

    Github developed Electron for creating the text editor Atom. They were both open sourced in 2014. Electron is used by many companies like Microsoft, Github, Slack, etc.

    Electron has been used to create a number of apps. Following are a few notable apps −

    • Slack desktop
    • WordPress desktop app
    • Visual Studio Code
    • Caret Markdown Editor
    • Nylas Email App
    • GitKraken git client
  • Materialize CSS Collapsible

    Collapsible or accordion is used to get various predefined visuals and behavioral enhancements to display various types of accordions. Materialize CSS provides different CSS classes to apply these collapsible.

    IndexClass nameDescription
    collapsibleIt is used to identify an element as a materialize collapsible component. Required for ul element.
    collapsible-headerIt is used to set div as a section header.
    collapsible-bodyIt is used to set div as a section content container.
    popoutIt is used to create a popout collapsible.
    activeIt is used to open a section.
    expandableIt is used to mark a collapsible component as expandable.
    accordionIt is used to mark a collapsible component as accordion.

    Example

    Let’s take an example to demonstrate collapsible in Materialize CSS:

    <html>  
    
       <head>  
    
          <title>The Materialize Collapsible Example</title>  
    
          <meta name = "viewport" content = "width = device-width, initial-scale = 1">        
    
          <link rel = "stylesheet"  
    
             href = "https://fonts.googleapis.com/icon?family=Material+Icons">  
    
          <link rel = "stylesheet"  
    
             href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">  
    
          <script type = "text/javascript"  
    
             src = "https://code.jquery.com/jquery-2.1.1.min.js"></script>             
    
          <script src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js">  
    
          </script>  
    
       </head>  
    
         
    
       <body class = "container">   
    
          <h4>Simple Accordion</h4>  
    
          <ul class = "collapsible" data-collapsible = "accordion">  
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">filter_drama</i>First Section</div>  
    
                <div class = "collapsible-body"><p>This is first section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">place</i>Second Section</div>  
    
                <div class = "collapsible-body"><p>This is second section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">whatshot</i>Third Section</div>  
    
                <div class = "collapsible-body"><p>This is third section.</p></div>  
    
             </li>  
    
          </ul>  
    
            
    
          <h4>Popout Accordion</h4>  
    
          <ul class = "collapsible popout" data-collapsible = "accordion">  
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">filter_drama</i>First Section</div>  
    
                <div class = "collapsible-body"><p>This is first section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">place</i>Second Section</div>  
    
                <div class = "collapsible-body"><p>This is second section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">whatshot</i>Third Section</div>  
    
                <div class = "collapsible-body"><p>This is third section.</p></div>  
    
             </li>  
    
          </ul>  
    
            
    
          <h4>Accordion with Preselected Section</h4>  
    
          <ul class = "collapsible" data-collapsible = "accordion">  
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">filter_drama</i>First Section</div>  
    
                <div class = "collapsible-body"><p>This is first section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header active">  
    
                   <i class = "material-icons">place</i>Second Section</div>  
    
                <div class = "collapsible-body"><p>This is second section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">whatshot</i>Third Section</div>  
    
                <div class = "collapsible-body"><p>This is third section.</p></div>  
    
             </li>  
    
          </ul>  
    
            
    
          <h4>Expandables</h4>  
    
          <ul class = "collapsible" data-collapsible = "expandable">  
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">filter_drama</i>First Section</div>  
    
                <div class = "collapsible-body"><p>This is first section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">place</i>Second Section</div>  
    
                <div class = "collapsible-body"><p>This is second section.</p></div>  
    
             </li>  
    
               
    
             <li>  
    
                <div class = "collapsible-header">  
    
                   <i class = "material-icons">whatshot</i>Third Section</div>  
    
                <div class = "collapsible-body"><p>This is third section.</p></div>  
    
             </li>  
    
          </ul>               
    
       </body>    
    
    </html>

    Output:

    Materialize collapsible 1
  • JavaScript Objects

    What is an Object?

    JavaScript is an object-based language and in JavaScript almost everything is an object or acts like an object. So, to work with JavaScript effectively and efficiently we need to understand how objects work as well as how to create your own objects and use them.

    A JavaScript object is just a collection of named values. These named values are usually referred to as properties of the object. If you remember from the JavaScript arrays chapter, an array is a collection of values, where each value has an index (a numeric key) that starts from zero and increments by one for each value. An object is similar to an array, but the difference is that you define the keys yourself, such as name, age, gender, and so on. In the following sections we’ll learn about objects in detail.

    Creating Objects

    An object can be created with curly brackets {} with an optional list of properties. A property is a “key: value” pair, where the key (or property name) is always a string, and value (or property value) can be any data type, like strings, numbers, Booleans or complex data type like arrays, functions, and other objects. Additionally, properties with functions as their values are often called methods to distinguish them from other properties. A typical JavaScript object may look like this:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    };

    The above example creates an object called person that has three properties nameage, and gender and one method displayName(). The displayName() method displays the value of this.name, which resolves to person.name. This is the easiest and preferred way to create a new object in JavaScript, which is known as object literals syntax.

    The property names generally do not need to be quoted unless they are reserved words, or if they contain spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number, as shown in the following example:

    Example

    let person = {
    
    "first name": "Peter",
    "current age": 28,
    gender: "Male"
    };

    Note: Since ECMAScript 5, reserved words can be used as object’s property names without quoting. However, you should avoid doing this for better compatibility.


    Accessing Object’s Properties

    To access or get the value of a property, you can use the dot (.), or square bracket ([]) notation, as demonstrated in the following example:

    Example

    let book = {
    
    "name": "Harry Potter and the Goblet of Fire",
    "author": "J. K. Rowling",
    "year": 2000
    }; // Dot notation document.write(book.author); // Prints: J. K. Rowling // Bracket notation document.write(book["year"]); // Prints: 2000

    The dot notation is easier to read and write, but it cannot always be used. If the name of the property is not valid (i.e. if it contains spaces or special characters), you cannot use the dot notation; you’ll have to use bracket notation, as shown in the following example:

    Example

    let book = {
    
    name: "Harry Potter and the Goblet of Fire",
    author: "J. K. Rowling",
    "publication date": "8 July 2000"
    }; // Bracket notation document.write(book["publication date"]); // Prints: 8 July 2000

    The square bracket notation offers much more flexibility than dot notation. It also allows you to specify property names as variables instead of just string literals, as shown in the example below:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let key = prompt("Enter any property name to get its value"); alert(person[key]); // Outputs: Peter (if enter "name")

    Looping Through Object’s Properties

    You can iterate through the key-value pairs of an object using the for...in loop. This loop is specially optimized for iterating over object’s properties. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Iterating over object properties for(let i in person) {
    document.write(person&#91;i] + "&lt;br&gt;"); // Prints: name, age and gender
    }

    Setting Object’s Properties

    Similarly, you can set the new properties or update the existing one using the dot (.) or bracket ([]) notation, as demonstrated in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Setting a new property person.country = "United States"; document.write(person.country); // Prints: United States person["email"] = "[email protected]"; document.write(person.email); // Prints: [email protected] // Updating existing property person.age = 30; document.write(person.age); // Prints: 30 person["name"] = "Peter Parker"; document.write(person.name); // Prints: Peter Parker

    Deleting Object’s Properties

    The delete operator can be used to completely remove properties from an object. Deleting is the only way to actually remove a property from an object. Setting the property to undefined or null only changes the value of the property. It does not remove property from the object.

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; // Deleting property delete person.age; alert(person.age); // Outputs: undefined

    Note: The delete operator only removes an object property or array element. It has no effect on variables or declared functions. However, you should avoid delete operator for deleting an array element, as it doesn’t change the array’s length, it just leaves a hole in the array.


    Calling Object’s Methods

    You can access an object’s method the same way as you would access properties—using the dot notation or using the square bracket notation. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; person.displayName(); // Outputs: Peter person["displayName"](); // Outputs: Peter

    Manipulating by Value vs. Reference

    JavaScript objects are reference types that mean when you make copies of them, you’re really just copying the references to that object. Whereas primitive values like strings and numbers are assigned or copied as a whole value. To better understand all this, let’s check out the following example:

    Example

    let message = "Hello World!";
    
    let greet = message; // Assign message variable to a new variable
    greet = "Hi, there!";
    
    document.write(message);  // Prints: Hello World!
    document.write(greet);  // Prints: Hi, there!

    In the above example, we have made a copy of a variable message and changed the value of that copy (i.e. variable greet). The two variables remain distinct and separate. But, if we do the same thing with an object, we will get a different result, as you see in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let user = person; // Assign person variable to a new variable user.name = "Harry"; document.write(person.name); // Prints: Harry document.write(user.name); // Prints: Harry

    You can clearly see, any changes made to the variable user also change the person variable; it happens because both variables reference the same object. So, simply copying the object does not actually clone it but copies the reference to that object.

  • JavaScript Functions

    What is Function?

    A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions:

    • Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
    • Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
    • Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.

    The following section will show you how to define and call functions in your scripts.

    Defining and Calling a Function

    The declaration of a function start with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. () and finally place your function’s code between curly brackets {}. Here’s the basic syntax for declaring a function:

    function functionName() {
    // Code to be executed
    }

    Here is a simple example of a function, that will show a hello message:

    Example

    // Defining function
    function sayHello() {
    
    alert("Hello, welcome to this website!");
    } // Calling function sayHello(); // 0utputs: Hello, welcome to this website!

    Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like sayHello() in the example above.

    Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names.


    Adding Parameters to Functions

    You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.

    Parameters are set on the first line of the function inside the set of parentheses, like this:

    function functionName(parameter1parameter2parameter3) {
    // Code to be executed
    }

    The displaySum() function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser.

    Example

    // Defining function
    function displaySum(num1, num2) {
    
    let total = num1 + num2;
    alert(total);
    } // Calling function displaySum(6, 20); // 0utputs: 26 displaySum(-5, 17); // 0utputs: 12

    You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined. Let’s consider the following example:

    Example

    // Defining function
    function showFullname(firstName, lastName) {
    
    alert(firstName + " " + lastName);
    } // Calling function showFullname("Clark", "Kent"); // 0utputs: Clark Kent showFullname("John"); // 0utputs: John undefined

    Default Values for Function Parameters ES6

    With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here’s an example:

    Example

    function sayHello(name = 'Guest') {
    
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    While prior to ES6, to achieve the same we had to write something like this:

    Example

    function sayHello(name) {
    
    let name = name || 'Guest'; 
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.


    Returning Values from a Function

    A function can return a value back to the script that called the function as a result using the return statement. The value may be of any type, including arrays and objects.

    The return statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example.

    Example

    // Defining function
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Displaying returned value alert(getSum(6, 20)); // 0utputs: 26 alert(getSum(-5, 17)); // 0utputs: 12

    A function can not return multiple values. However, you can obtain similar results by returning an array of values, as demonstrated in the following example.

    Example

    // Defining function
    function divideNumbers(dividend, divisor){
    
    let quotient = dividend / divisor;
    let arr = &#91;dividend, divisor, quotient];
    return arr;
    } // Store returned value in a variable let all = divideNumbers(10, 2); // Displaying individual values alert(all[0]); // 0utputs: 10 alert(all[1]); // 0utputs: 2 alert(all[2]); // 0utputs: 5

    Working with Function Expressions

    The syntax that we’ve used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression.

    Example

    // Function Declaration
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Function Expression let getSum = function(num1, num2) {
    let total = num1 + num2;
    return total;
    };

    Once function expression has been stored in a variable, the variable can be used as a function:

    Example

    let getSum = function(num1, num2) {
    
    let total = num1 + num2;
    return total;
    }; alert(getSum(5, 10)); // 0utputs: 15 let sum = getSum(7, 25); alert(sum); // 0utputs: 32

    Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon.

    Tip: In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time.

    The syntax of the function declaration and function expression looks very similar, but they differ in the way they are evaluated, check out the following example:

    Example

    declaration(); // Outputs: Hi, I'm a function declaration!
    function declaration() {
    
    alert("Hi, I'm a function declaration!");
    } expression(); // Uncaught TypeError: undefined is not a function let expression = function() {
    alert("Hi, I'm a function expression!");
    };

    As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully.

    JavaScript parse declaration function before the program executes. Therefore, it doesn’t matter if the program invokes the function before it is defined because JavaScript has hoisted the function to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked.

    ES6 has introduced even shorter syntax for writing function expression which is called arrow function, please check out the JavaScript ES6 features chapter to learn more about it.


    Understanding the Variable Scope

    However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable’s availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as variable scope.

    By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from outside of that function, as shown in the example below:

    Example

    // Defining function
    function greetWorld() {
    
    let greet = "Hello World!";
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Uncaught ReferenceError: greet is not defined

    However, any variables declared in a program outside of a function has global scope i.e. it will be available to all script, whether that script is inside a function or outside. Here’s an example:

    Example

    let greet = "Hello World!";
     
    // Defining function
    function greetWorld() {
    
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Outputs: Hello World!
  • JavaScript Loops

    Different Types of Loops in JavaScript

    Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. JavaScript now supports five different types of loops:

    • while — loops through a block of code as long as the condition specified evaluates to true.
    • do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
    • for — loops through a block of code until the counter reaches a specified number.
    • for…in — loops through the properties of an object.
    • for…of — loops over iterable objects such as arrays, strings, etc.

    In the following sections, we will discuss each of these loop statements in detail.


    The while Loop

    This is the simplest looping statement provided by JavaScript.

    The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

    while(condition) {
    // Code to be executed
    }

    The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    let i = 1;
    while(i <= 5) {    
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    }

    Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case).


    The do…while Loop

    The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is:

    do {
    // Code to be executed
    }
    while(condition);

    The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of variable i by 1. After that the condition is evaluated, and the loop will continue to run as long as the variable i is less than, or equal to 5.

    Example

    let i = 1;
    do {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    } while(i <= 5);

    Difference Between while and do…while Loop

    The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

    With a do-while loop, on the other hand, the loop will always be executed once even if the conditional expression evaluates to false, because unlike the while loop, the condition is evaluated at the end of the loop iteration rather than the beginning.


    The for Loop

    The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times. Its syntax is:

    for(initializationconditionincrement) {
    // Code to be executed
    }

    The parameters of the for loop statement have following meanings:

    • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
    • condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends.
    • increment — it updates the loop counter with a new value each time the loop runs.

    The following example defines a loop that starts with i=1. The loop will continued until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    for(let i=1; i<=5; i++) {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    }

    The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the JavaScript array.

    Exampl

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i=0; i<fruits.length; i++) {
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    The for…in Loop

    The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array. The generic syntax of the for-in loop is:

    for(variable in object) {
    // Code to be executed
    }

    The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element.

    The following example will show you how to loop through all properties of a JavaScript object.

    Example

    // An object with some properties 
    let person = {"name": "Clark", "surname": "Kent", "age": "36"};
     
    // Loop through all the properties in the object  
    for(let prop in person) {  
    
    document.write("&lt;p&gt;" + prop + " = " + person&#91;prop] + "&lt;/p&gt;"); 
    }

    Similarly, you can loop through the elements of an array, like this:

    Example

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i in fruits) {  
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    Note: The for-in loop should not be used to iterate over an array where the index order is important. You should better use a for loop with a numeric index.


    The for…of Loop ES6

    ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

    The following example will show you how to loop through arrays and strings using this loop.

    Example

    // Iterating over array
    let letters = ["a", "b", "c", "d", "e", "f"];
    
    for(let letter of letters) {
    
    console.log(letter); // a,b,c,d,e,f
    } // Iterating over string let greet = "Hello World!"; for(let character of greet) {
    console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
    }

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.

  • JavaScript Sorting Arrays

    Sorting an Array

    Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order.

    The JavaScript Array object has a built-in method sort() for sorting array elements in alphabetical order. The following example demonstrates how it works:

    Example

    let fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
    let sorted = fruits.sort();
    
    alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya
    alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

    Reversing an Array

    You can use the reverse() method to reverse the order of the elements of an array.

    This method reverses an array in such a way that the first array element becomes the last, and the last array element becomes the first. Here’s an example:

    Example

    let counts = ["one", "two", "three", "four", "five"];
    let reversed = counts.reverse(); 
    
    alert(counts); // Outputs: five,four,three,two,one
    alert(reversed); // Output: five,four,three,two,one

    Note: The sort() and reverse() method modifies the original array and return a reference to the same array, as you can see in the above examples.


    Sorting Numeric Arrays

    The sort() method may produce unexpected result when it is applied on the numeric arrays (i.e. arrays containing numeric values). For instance:

    Example

    let numbers = [5, 20, 10, 75, 50, 100];
    numbers.sort(); // Sorts numbers array
    alert(numbers); // Outputs: 10,100,20,5,50,75

    As you can see, the result is different from what we’ve expected. It happens because, the sort() method sorts the numeric array elements by converting them to strings (i.e. 20 becomes “20”, 100 becomes “100”, and so on), and since the first character of string “20” (i.e. “2”) comes after the first character of string “100” (i.e. “1”), that’s why the value 20 is sorted after the 100.

    To fix this sorting problem with numeric array, you can pass a compare function, like this:

    Example

    let numbers = [5, 20, 10, 75, 50, 100];
    
    // Sorting an array using compare function
    numbers.sort(function(a, b) {
    
    return a - b;
    }); alert(numbers); // Outputs: 5,10,20,50,75,100

    As you can see, this time we’ve got the correct result. Let’s see how it works.

    When compare function is specified, array elements are sorted according to the return value of the compare function. For example, when comparing a and b:

    • If the compare function returns a value less than 0, then a comes first.
    • If the compare function returns a value greater than 0, then b comes first.
    • If the compare function returns 0, a and b remain unchanged with respect to each other, but sorted with respect to all other elements.

    Hence, since 5 - 20 = -15 which is less than 0, therefore 5 comes first, similarly 20 - 10 = 10 which is greater than 0, therefore 10 comes before 20, likewise 20 - 75 = -55 which is less than 0, so 20 comes before 75, similarly 50 comes before 75, and so on.


    Finding the Maximum and Minimum Value in an Array

    You can use the apply() method in combination with the Math.max() and Math.min() to find the maximum and minimum value inside an array, like this:

    Example

    let numbers = [3, -7, 10, 8, 15, 2];
    
    // Defining function to find maximum value
    function findMax(array) {
    
    return Math.max.apply(null, array);
    } // Defining function to find minimum value function findMin(array) {
    return Math.min.apply(null, array);
    } alert(findMax(numbers)); // Outputs: 15 alert(findMin(numbers)); // Outputs: -7

    The apply() method provides a convenient way to pass array values as arguments to a function that accepts multiple arguments in an array-like manner, but not an array (e.g. Math.max() and Math.min() methods here). So, the resulting statement Math.max.apply(null, numbers) in the example above is equivalent to the Math.max(3, -7, 10, 8, 15, 2).


    Sorting an Array of Objects

    The sort() method can also be used for sorting object arrays using the compare function.

    The following example will show you how to sort an array of objects by property values:

    Example

    let persons = [
    
    { name: "Harry", age: 14 },
    { name: "Ethan", age: 30 },
    { name: "Peter", age: 21 },
    { name: "Clark", age: 42 },
    { name: "Alice", age: 16 }
    ]; // Sort by age persons.sort(function (a, b) {
    return a.age - b.age;
    }); console.log(persons); // Sort by name persons.sort(function(a, b) {
    let x = a.name.toLowerCase(); // ignore upper and lowercase
    let y = b.name.toLowerCase(); // ignore upper and lowercase
    if(x &lt; y) {
        return -1;
    }
    if(x &gt; y) {
        return 1;
    }
    // names must be equal
    return 0;
    }); console.log(persons);
  • JavaScript Arrays

    What is an Array

    Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays, thus making it possible to create more complex data structures such as an array of objects or an array of arrays.

    Let’s suppose you want to store the name of colors in your JavaScript code. Storing the color names one by one in a variable could look something like this:

    Example

    let color1 = "Red";
    let color2 = "Green";
    let color3 = "Blue";

    But what happens if you need to store the state or city names of a country in variables and this time this not just three may be hundred. It is quite hard and boring to store each of them in a separate variable. Also, using so many variables simultaneously and keeping track of them all will be a very difficult task. And here array comes into play. Arrays solve this problem by providing an ordered structure for storing multiple values or a group of values.

    Creating an Array

    The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax:

    var myArray = [element0element1, …, elementN];

    Array can also be created using the Array() constructor as shown in the following syntax. However, for the sake of simplicity previous syntax is recommended.

    var myArray = new Array(element0element1, …, elementN);

    Here are some examples of arrays created using array literal syntax:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    let cities = ["London", "Paris", "New York"];
    let person = ["John", "Wick", 32];

    Note: An array is an ordered collection of values. Each value in an array is called an element, and each element has a numeric position in an array, known as its index.


    Accessing the Elements of an Array

    Array elements can be accessed by their index using the square bracket notation. An index is a number that represents an element’s position in an array.

    Array indexes are zero-based. This means that the first item of an array is stored at index 0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up to the number of elements minus 1. So, array of five elements would have indexes from 0 to 4.

    The following example will show you how to get individual array element by their index.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits[0]); // Prints: Apple
    document.write(fruits[1]); // Prints: Banana
    document.write(fruits[2]); // Prints: Mango
    document.write(fruits[fruits.length - 1]); // Prints: Papaya

    Note: In JavaScript, arrays are really just a special type of objects which has numeric indexes as keys. The typeof operator will return “object” for arrays.


    Getting the Length of an Array

    The length property returns the length of an array, which is the total number of elements contained in the array. Array length is always greater than the index of any of its element.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    document.write(fruits.length); // Prints: 5

    Looping Through Array Elements

    You can use for loop to access each element of an array in sequential order, like this:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Iterates over array elements
    for(let i = 0; i < fruits.length; i++) {    
    
    document.write(fruits&#91;i] + "&lt;br&gt;"); // Print array element
    }

    ECMAScript 6 has introduced a simpler way to iterate over array element, which is for-of loop. In this loop you don’t have to initialize and keep track of the loop counter variable (i).

    Here’s the same example rewritten using the for-of loop:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Iterates over array elements
    for(let fruit of fruits) {    
    
    document.write(fruit + "&lt;br&gt;"); // Print array element
    }

    You can also iterate over the array elements using for-in loop, like this:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i in fruits) {  
    
    document.write(fruits&#91;i] + "&lt;br&gt;");
    }

    Note: The for-in loop should not be used to iterate over an array where the index order is important. The for-in loop is optimized for iterating over object’s properties, you should better use a for loop with a numeric index or for-of loop.


    Adding New Elements to an Array

    To add a new element at the end of an array, simply use the push() method, like this:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    colors.push("Yellow");
     
    document.write(colors); // Prints: Red,Green,Blue,Yellow
    document.write(colors.length); // Prints: 4

    Similarly, to add a new element at the beginning of an array use the unshift() method, like this:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    colors.unshift("Yellow");
     
    document.write(colors); // Prints: Yellow,Red,Green,Blue
    document.write(colors.length); // Prints: 4

    You can also add multiple elements at once using the push() and unshift() methods, like this:

    Example

    let colors = ["Red", "Green", "Blue"];
    colors.push("Pink", "Voilet");
    colors.unshift("Yellow", "Grey");
     
    document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
    document.write(colors.length); // Prints: 7

    Removing Elements from an Array

    To remove the last element from an array you can use the pop() method. This method returns the value that was popped out. Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    let last = colors.pop();
     
    document.write(last); // Prints: Blue
    document.write(colors.length); // Prints: 2

    Similarly, you can remove the first element from an array using the shift() method. This method also returns the value that was shifted out. Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    let first = colors.shift();
     
    document.write(first); // Prints: Red
    document.write(colors.length); // Prints: 2

    Tip: The push() and pop() methods runs faster than unshift() and shift(). Because push() and pop() methods simply add and remove elements at the end of an array therefore the elements do not move, whereas unshift() and shift() add and remove elements at the beginning of the array that require re-indexing of whole array.


    Adding or Removing Elements at Any Position

    The splice() method is a very versatile array method that allows you to add or remove elements from any index, using the syntax arr.splice(startIndex, deleteCount, elem1, ..., elemN).

    This method takes three parameters: the first parameter is the index at which to start splicing the array, it is required; the second parameter is the number of elements to remove (use 0 if you don’t want to remove any elements), it is optional; and the third parameter is a set of replacement elements, it is also optional. The following example shows how it works:

    Example

    let colors = ["Red", "Green", "Blue"];
    let removed = colors.splice(0,1); // Remove the first element
     
    document.write(colors); // Prints: Green,Blue
    document.write(removed); // Prints: Red (one item array)
    document.write(removed.length); // Prints: 1
     
    removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at position one
    document.write(colors); // Prints: Green,Pink,Yellow,Blue
    document.write(removed); // Empty array
    document.write(removed.length); // Prints: 0
     
    removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values, remove one
    document.write(colors); //Prints: Green,Purple,Voilet,Yellow,Blue
    document.write(removed); // Prints: Pink (one item array)
    document.write(removed.length); // Prints: 1

    The splice() method returns an array of the deleted elements, or an empty array if no elements were deleted, as you can see in the above example. If the second argument is omitted, all elements from the start to the end of the array are removed. Unlike slice() and concat() methods, the splice() method modifies the array on which it is called on.


    Creating a String from an Array

    There may be situations where you simply want to create a string by joining the elements of an array. To do this you can use the join() method. This method takes an optional parameter which is a separator string that is added in between each element. If you omit the separator, then JavaScript will use comma (,) by default. The following example shows how it works:

    Example

    let colors = ["Red", "Green", "Blue"];
     
    document.write(colors.join()); // Prints: Red,Green,Blue
    document.write(colors.join("")); // Prints: RedGreenBlue
    document.write(colors.join("-")); // Prints: Red-Green-Blue
    document.write(colors.join(", ")); // Prints: Red, Green, Blue

    You can also convert an array to a comma-separated string using the toString(). This method does not accept the separator parameter like join(). Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    document.write(colors.toString()); // Prints: Red,Green,Blue

    Extracting a Portion of an Array

    If you want to extract out a portion of an array (i.e. subarray) but keep the original array intact you can use the slice() method. This method takes 2 parameters: start index (index at which to begin extraction), and an optional end index (index before which to end extraction), like arr.slice(startIndex, endIndex). Here’s an example:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    let subarr = fruits.slice(1, 3);
    document.write(subarr); // Prints: Banana,Mango

    If endIndex parameter is omitted, all elements to the end of the array are extracted. You can also specify negative indexes or offsets —in that case the slice() method extract the elements from the end of an array, rather then the begining. For example:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya
    document.write(fruits.slice(-2)); // Prints: Orange,Papaya
    document.write(fruits.slice(2, -1)); // Prints: Mango,Orange

    Merging Two or More Arrays

    The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays, instead it returns a new array. For example:

    Example

    let pets = ["Cat", "Dog", "Parrot"];
    let wilds = ["Tiger", "Wolf", "Zebra"];
     
    // Creating new array by combining pets and wilds arrays
    let animals = pets.concat(wilds); 
    document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra

    The concat() method can take any number of array arguments, so you can create an array from any number of other arrays, as shown in the following example:

    Example

    let pets = ["Cat", "Dog", "Parrot"];
    let wilds = ["Tiger", "Wolf", "Zebra"];
    let bugs = ["Ant", "Bee"];
     
    // Creating new array by combining pets, wilds and bugs arrays
    let animals = pets.concat(wilds, bugs); 
    document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

    Searching Through an Array

    If you want to search an array for a specific value, you can simply use the indexOf() and lastIndexOf(). If the value is found, both methods return an index representing the array element. If the value is not found, -1 is returned. The indexOf() method returns the first one found, whereas the lastIndexOf() returns the last one found.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits.indexOf("Apple")); // Prints: 0
    document.write(fruits.indexOf("Banana")); // Prints: 1
    document.write(fruits.indexOf("Pineapple")); // Prints: -1

    Both methods also accept an optional integer parameter from index which specifies the index within the array at which to start the search. Here’s an example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    // Searching forwards, starting at from- index
    document.write(arr.indexOf(1, 2)); // Prints: 3
     
    // Searching backwards, starting at from index
    document.write(arr.lastIndexOf(1, 2)); // Prints: 0

    You can also use includes() method to find out whether an array includes a certain element or not. This method takes the same parameters as indexOf() and lastIndexOf() methods, but it returns true or false instead of index number. For example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    document.write(arr.includes(1)); // Prints: true
    document.write(arr.includes(6)); // Prints: false
    document.write(arr.includes(1, 2)); // Prints: true
    document.write(arr.includes(3, 4)); // Prints: false

    If you want to search an array based on certain condition then you can use the JavaScript find() method which is newly introduced in ES6. This method returns the value of the first element in the array that satisfies the provided testing function. Otherwise it return undefined.

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.find(function(element) {
      return element > 4;
    });
    document.write(result); // Prints: 5

    There is one more method similar to find() is findIndex() method, which returns the index of a found element in the array instead of its value. For example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.findIndex(function(element) {
      return element > 6;
    });
    document.write(result); // Prints: 8

    The find() method only looks for the first element that satisfies the provided testing function. However, if you want to find out all the matched elements you can use the filter() method.

    The filter() method creates a new array with all the elements that successfully passes the given test. The following example will show you how this actually works:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.filter(function(element) {
      return element > 4;
    });
    document.write(result); // Prints: 5,7
    document.write(result.length); // Prints: 2
  • JavaScript Switch…Case Statements

    Using the Switch…Case Statement

    The switch..case statement is an alternative to the if…else if…else statement, which does almost the same thing. The switch…case statement tests a variable or expression against a series of values until it finds a match, and then executes the block of code corresponding to that match. It’s syntax is:

    switch(x){
    case value1:
            // Code to be executed if x === value1
            break;
    case value2:
            // Code to be executed if x === value2
            break;
        …
    default:
            // Code to be executed if x is different from all values
    }

    Consider the following example, which display the name of the day of the week.

    Example

    let d = new Date();
    	
    switch(d.getDay()) {
    	case 0:
    		alert("Today is Sunday.");
    		break;
    	case 1:
    		alert("Today is Monday.");
    		break;
    	case 2:
    		alert("Today is Tuesday.");
    		break;
    	case 3:
    		alert("Today is Wednesday.");
    		break;
    	case 4:
    		alert("Today is Thursday.");
    		break;
    	case 5:
    		alert("Today is Friday.");
    		break;
    	case 6:
    		alert("Today is Saturday.");
    		break;   
    	default:
    		alert("No information available for that day.");
    		break;
    }

    The getDay() method returns the weekday as a number from 0 and 6, where 0 represents Sunday. See the JavaScript date and time chapter to learn more about date methods.

    Note: In a switch…case statement, the value of the expression or variable is compared against the case value using the strict equality operator (===). That means if x = "0", it doesn’t match case 0:, because their data types are not equal.

    The switch…case statement differs from the if…else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once JavaScript finds a case clause that evaluates to true, it’s not only executes the code corresponding to that case clause, but also executes all the subsequent case clauses till the end of the switch block automatically.

    To prevent this you must include a break statement after each case (as you can see in the above example). The break statement tells the JavaScript interpreter to break out of the switch…case statement block once it executes the code associated with the first true case.

    The break statement is however not required for the case or default clause, when it appears at last in a switch statement. Although, it a good programming practice to terminate the last case, or default clause in a switch statement with a break. It prevents a possible programming error later if another case statement is added to the switch statement.

    The default clause is optional, which specify the actions to be performed if no case matches the switch expression. The default clause does not have to be the last clause to appear in a switch statement. Here’s an example, where default is not the last clause.

    Example

    let d = new Date();
    
    switch(d.getDay()) {
    
    default: 
        alert("Looking forward to the weekend.");
        break;
    case 6:
        alert("Today is Saturday.");
        break; 
    case 0:
        alert("Today is Sunday.");
    }

    Multiple Cases Sharing Same Action

    Each case value must be unique within a switch statement. However, different cases don’t need to have a unique action. Several cases can share the same action, as shown here:

    Example

    let d = new Date();
    
    switch(d.getDay()) {
    
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        alert("It is a weekday.");
        break; 
    case 0:
    case 6:
        alert("It is a weekend day.");
        break;
    default: 
        alert("Enjoy every day of your life.");
    }
  • JavaScript If…Else Statements

    JavaScript Conditional Statements

    Like many other programming languages, JavaScript also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.

    There are several conditional statements in JavaScript that you can use to make decisions:

    • The if statement
    • The if…else statement
    • The if…else if….else statement
    • The switch…case statement

    We will discuss each of these statements in detail in the coming sections.

    The if Statement

    The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest JavaScript’s conditional statements and can be written like:

    if(condition) {
    // Code to be executed
    }

    The following example will output “Have a nice weekend!” if the current day is Friday:

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    }

    The if...else Statement

    You can enhance the decision making capabilities of your JavaScript program by providing an alternative choice through adding an else statement to the if statement.

    The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:

    if(condition) {
    // Code to be executed if condition is true
    } else {
    // Code to be executed if condition is false
    }

    The JavaScript code in the following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output the text “Have a nice day!”.

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    } else {
    alert("Have a nice day!");
    }

    The if...else if...else Statement

    The if…else if…else a special statement that is used to combine multiple if…else statements.

    if(condition1) {
    // Code to be executed if condition1 is true
    } else if(condition2) {
    // Code to be executed if the condition1 is false and condition2 is true
    } else {
    // Code to be executed if both condition1 and condition2 are false
    }

    The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday, otherwise it will output “Have a nice day!”

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    } else if(dayOfWeek == 0) {
    alert("Have a nice Sunday!");
    } else {
    alert("Have a nice day!");
    }

    You will learn about the JavaScript switch-case statement in the next chapter.


    The Ternary Operator

    The ternary operator provides a shorthand way of writing the if…else statements. The ternary operator is represented by the question mark (?) symbol and it takes three operands: a condition to check, a result for true, and a result for false. Its basic syntax is:

    let result = (condition) ? value1 : value2

    If the condition is evaluated to true the value1 will be returned, otherwise value2 will be returned. To understand how this operator works, consider the following examples:

    Example

    let userType;
    let age = 21;
    if(age < 18) {
    
    userType = 'Child';
    } else {
    userType = 'Adult';
    } alert(userType); // Displays Adult

    Using the ternary operator the same code could be written in a more compact way:

    Example

    let age = 21;
    let userType = age < 18 ? 'Child' : 'Adult';
    alert(userType); // Displays Adult

    As you can see in the above example, since the specified condition evaluated to false the value on the right side of the colon (:) is returned, which is the string ‘Adult’.