Author: Saim Khalid

  • 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 < y) {
        return -1;
    }
    if(x > 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’.

  • JavaScript Numbers

    Working with Numbers

    JavaScript supports both integer and floating-point numbers that can be represented in decimal, hexadecimal or octal notation. Unlike other languages, JavaScript does not treat integer and floating-point numbers differently. All numbers in JavaScript are represented as floating-point numbers. Here’s an example demonstrating the numbers in different formats:

    Example

    let x = 2;  // integer number
    let y = 3.14;  // floating-point number
    let z = 0xff;  // hexadecimal number

    Extra large numbers can be represented in exponential notation e.g. 6.02e+23 (same as 6.02×1023).

    Example

    let x = 1.57e4;  // same as 15700
    let y = 4.25e+6;  // same as 4.25e6 or 4250000
    let z = 4.25e-6;  // same as 0.00000425

    Tip: The biggest safe integer in JavaScript is 9007199254740991 (253-1), whereas the smallest safe integer is -9007199254740991 (-(253-1)).

    Numbers can also be represented in hexadecimal notation (base 16). Hexadecimal numbers are prefixed with 0x. They are commonly used to represent colors. Here’s an example:

    Example

    let x = 0xff;  // same as 255
    let y = 0xb4;  // same as 180
    let z = 0x00;  // same as 0

    Note: Integers can be represented in decimal, hexadecimal, and octal notation. Floating-point numbers can be represented in decimal or exponential notation.


    Operating on Numbers and Strings

    As you know from the previous chapters, the + operator is used for both addition and concatenation. So, performing mathematical operations on numbers and strings may produce interesting results. The following example will show you what happens when you add numbers and strings:

    Example

    let x = 10;
    let y = 20;
    let z = "30";
    
    // Adding a number with a number, the result will be sum of numbers
    console.log(x + y); // 30
    
    // Adding a string with a string, the result will be string concatenation
    console.log(z + z); // '3030'
    
    // Adding a number with a string, the result will be string concatenation
    console.log(x + z); // '1030'
    
    // Adding a string with a number, the result will be string concatenation
    console.log(z + x); // '3010'
    
    // Adding strings and numbers, the result will be string concatenation
    console.log("The result is: " + x + y); // 'The result is: 1020'
    
    // Adding numbers and strings, calculation performed from left to right
    console.log(x + y + z); // 'The result is: 3030'

    If you observe the above example carefully, you will find that the result of the last operation is not just a simple string concatenation, because operators with the same precedence are evaluated from left to right. That’s why, since variables x and y both are numbers they are added first then the result is concatenated with the variable z which is a string, hence final result is 30 + "30" = "3030".

    But, if you perform other mathematical operations like multiplication, division, or subtraction the result will be different. JavaScript will automatically convert numeric strings (i.e. strings containing numeric values) to numbers in all numeric operations, as shown in the following example:

    Example

    let x = 10;
    let y = 20;
    let z = "30";
    
    // Subtracting a number from a number
    console.log(y - x); // 10
    
    // Subtracting a number from a numeric string
    console.log(z - x); // 20
    
    // Multiplying a number with a numeric string
    console.log(x * z); // 300
    
    // Dividing a number with a numeric string
    console.log(z / x); // 3

    Moreover, if you try to multiply or divide numbers with strings that are not numeric, it returns NaN (Not a Number). Also, if you use NaN in a mathematical operation, the result will also be NaN.

    Example

    let x = 10;
    let y = "foo";
    let z = NaN;
    
    // Subtracting a number from a non-numeric string
    console.log(y - x); // NaN
    
    // Multiplying a number with a non-numeric string
    console.log(x * y); // NaN
    
    // Dividing a number with a non-numeric string
    console.log(x / y); // NaN
    
    // Adding NaN to a number 
    console.log(x + z); // NaN
    
    					
    // Adding NaN to a string console.log(y + z); // fooNaN

    Representing Infinity

    Infinity represents a number too big for JavaScript to handle. JavaScript has special keyword Infinity and -Infinity to represent positive and negative infinity respectively. For example, dividing by 0 returns Infinity, as demonstrated below:

    Example

    let x = 5 / 0;
    console.log(x); // Infinity
    
    let y = -5 / 0;
    console.log(y); // -Infinity

    Note: Infinity is a special value that represents the mathematical Infinity , which is greater than any number. The typeof operator return number for an Infinity value.


    Avoiding Precision Problems

    Sometimes, operations on floating-point numbers produce unexpected results, as shown here:

    Example

    let x = 0.1 + 0.2;
    console.log(x) // 0.30000000000000004

    As you can see the result is 0.30000000000000004 rather than the expected 0.3. This difference is called representation error or roundoff error. It occurs because JavaScript and many other languages uses binary (base 2) form to represent decimal (base 10) numbers internally. Unfortunately, most decimal fractions can’t be represented exactly in binary form, so small differences occur.

    To avoid this problem you can use the solution something like this:

    Example

    Try this code »

    let x = (0.1 * 10 + 0.2 * 10) / 10;
    console.log(x) // 0.3

    JavaScript round floating-point numbers to 17 digits, which is enough precision or accuracy in most cases. Also, in JavaScript integers (numbers without fractional parts or exponential notation) are accurate is up to 15 digits, as demonstrated in the following example:

    Example

    let x = 999999999999999;
    console.log(x); // 999999999999999
    
    let y = 9999999999999999;
    console.log(y); // 10000000000000000

    Performing Operations on Numbers

    JavaScript provides several properties and methods to perform operations on number values. As you already know from the previous chapters, in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

    In the following sections, we will look at the number methods that are most commonly used.

    Parsing Integers from Strings

    The parseInt() method can be used to parse an integer from a string. This method is particularly handy in situations when you are dealing with the values like CSS units e.g. 50px12pt, etc. and you would like to extract the numeric value out of it.

    If the parseInt() method encounters a character that is not numeric in the specified base, it stops parsing and returns the integer value parsed up to that point. If the first character cannot be converted into a number, the method will return NaN (not a number).

    Leading and trailing spaces are allowed. Here’s an example:

    Example

    console.log(parseInt("3.14"));  // 3
    console.log(parseInt("50px"));  // 50
    console.log(parseInt("12pt"));  // 12
    console.log(parseInt("0xFF", 16));  // 255
    console.log(parseInt("20 years"));  // 20
    console.log(parseInt("Year 2048"));  // NaN
    console.log(parseInt("10 12 2018"));  // 10

    Note: The parseInt() method truncates numbers to integer values, but it should not be used as a substitute for Math.floor() method.

    Similarly, you can use the parseFloat() method to parse floating-point number from a string. The parseFloat() method works the same way as the parseInt() method, except that it retrieves both integers and numbers with decimals.

    Example

    console.log(parseFloat("3.14"));  // 3.14
    console.log(parseFloat("50px"));  // 50
    console.log(parseFloat("1.6em"));  // 1.6
    console.log(parseFloat("124.5 lbs"));  // 124.5
    console.log(parseFloat("weight 124.5 lbs"));  // NaN
    console.log(parseFloat("6.5 acres"));  // 6.5

    Converting Numbers to Strings

    The toString() method can be used to convert a number to its string equivalent. This method optionally accepts an integer parameter in the range 2 through 36 specifying the base to use for representing numeric values. Here’s an example:

    Example

    let x = 10;
    let y = x.toString();
    console.log(y);  // '10'
    console.log(typeof y);  // string
    console.log(typeof x);  // number
    
    console.log((12).toString());  // '12'
    console.log((15.6).toString());  // '15.6'
    console.log((6).toString(2));  // '110'
    console.log((255).toString(16));  // 'ff'

    Formatting Numbers in Exponential Notation

    You can use the toExponential() method to format or represent a number in exponential notation. This method optionally accepts an integer parameter specifying the number of digits after the decimal point. Also, the returned value is a string not a number. Here’s an example:

    Example

    let x = 67.1234;
    
    console.log(x.toExponential());  // 6.71234e+1
    console.log(x.toExponential(6));  // 6.712340e+1
    console.log(x.toExponential(4));  // 6.7123e+1
    console.log(x.toExponential(2));  // 6.71e+1

    Note: Exponential notation is useful for representing numbers that are either very large or very small in magnitude. For example, 62500000000 can be written as 625e+8 or 6.25e+10.


    Formatting Numbers to Fixed Decimals

    You can use the toFixed() method when you want to format a number with a fixed number of digits to the right of the decimal point. The value returned by this method is a string and it has exactly specified number of digits after the decimal point. If the digits parameter is not specified or omitted, it is treated as 0. Here’s an example:

    Example

    let x = 72.635;
    
    console.log(x.toFixed());  // '73' (note rounding, no fractional part)
    console.log(x.toFixed(2));  // '72.64' (note rounding)
    console.log(x.toFixed(1));  // '72.6'
    
    let y = 6.25e+5;
    console.log(y.toFixed(2)); // '625000.00'
    
    let z = 1.58e-4;
    console.log(z.toFixed(2));  // '0.00' (since 1.58e-4 is equal to 0.000158)

    Formatting Numbers with Precision

    If you want most appropriate form of a number, you can use the toPrecision() method instead. This method returns a string representing the number to the specified precision.

    If precision is large enough to include all the digits of the integer part of number, then the number is formatted using fixed-point notation. Otherwise, the number is formatted using exponential notation. The precision parameter is optional. Here’s an example:

    Example

    let x = 6.235;
    
    console.log(x.toPrecision());  // '6.235'
    console.log(x.toPrecision(3));  // '6.24' (note rounding)
    console.log(x.toPrecision(2));  // '6.2'
    console.log(x.toPrecision(1));  // '6'
    
    let y = 47.63;
    console.log(y.toPrecision(2)); // '48' (note rounding, no fractional part)
    
    let z = 1234.5;
    console.log(z.toPrecision(2));  // '1.2e+3'

    Finding the Largest and Smallest Possible Numbers

    The Number object also has several properties associated with it. The Number.MAX_VALUE and Number.MIN_VALUE properties of the Number object represent the largest and smallest (closest to zero, not most negative) possible positive numbers that JavaScript can handle. They are constants and their actual values are 1.7976931348623157e+308, and 5e-324, respectively.

    A number that falls outside of the range of possible numbers is represented by a constant Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY. Here’s an example:

    Example

    let a = Number.MAX_VALUE;
    console.log(a); // 1.7976931348623157e+308
    
    let b = Number.MIN_VALUE;
    console.log(b); // 5e-324
    
    let x = Number.MAX_VALUE * 2;
    console.log(x); // Infinity
    
    let y = -1 * Number.MAX_VALUE * 2;
    console.log(y); // -Infinity

    Also, check out the JavaScript math operations chapter to learn about rounding numbers, generating a random number, finding maximum or minimun value from a set of numbers, etc.

  • JavaScript Strings

    What is String in JavaScript

    A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. Strings can be created by enclosing the string literal (i.e. string characters) either within single quotes (') or double quotes ("), as shown in the example below:

    Example

    let myString = 'Hello World!'; // Single quoted string
    let myString = "Hello World!"; // Double quoted string

    You can use quotes inside a string, as long as they don’t match the quotes surrounding the string:

    Example

    let str1 = "it's okay";
    let str2 = 'He said "Goodbye"';
    let str3 = "She replied 'Calm down, please'";
    let str4 = 'Hi, there!"; // Syntax error - quotes must match

    However, you can still use single quotes inside a single quoted strings or double quotes inside double quoted strings by escaping the quotes with a backslash character (\), like this:

    Example

    let str1 = 'it\'s okay';
    let str2 = "He said \"Goodbye\"";
    let str3 = 'She replied \'Calm down, please\'';

    The backslash (\) is called an escape character, whereas the sequences \' and \" that we’ve used in the example above are called escape sequences.


    JavaScript Escape Sequences

    Escape sequences are also useful for situations where you want to use characters that can’t be typed using a keyboard. Here are some other most commonly used escape sequences.

    • \n is replaced by the newline character
    • \t is replaced by the tab character
    • \r is replaced by the carriage-return character
    • \b is replaced by the backspace character
    • \\ is replaced by a single backslash (\)

    Here’s an example to clarify the how escape sequences actually works:

    Example

    let str1 = "The quick brown fox \n jumps over the lazy dog.";
    document.write("<pre>" + str1 + "</pre>"); // Create line break
     
    let str2 = "C:\Users\Downloads";
    document.write(str2); // Prints C:UsersDownloads
     
    let str3 = "C:\\Users\\Downloads";
    document.write(str3); // Prints C:\Users\Downloads

    Performing Operations on Strings

    JavaScript provides several properties and methods to perform operations on string values. Technically, only objects can have properties and methods. But in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

    JavaScript making it possible by creating a temporary wrapper object for primitive data types. This process is done automatically by the JavaScript interpreter in the background.

    Getting the Length of a String

    The length property returns the length of the string, which is the number of characters contained in the string. This includes the number of special characters as well, such as \t or \n.

    Example

    let str1 = "This is a paragraph of text.";
    document.write(str1.length); // Prints 28
     
    let str2 = "This is a \n paragraph of text.";
    document.write(str2.length); // Prints 30, because \n is only one character

    Note: Since length is a property, not a function, so don’t use parentheses after it like str.length(). Instead just write str.length, otherwise it will produce an error.


    Finding a String Inside Another String

    You can use the indexOf() method to find a substring or string within another string. This method returns the index or position of the first occurrence of a specified string within a string.

    Example

    let str = "If the facts don't fit the theory, change the facts.";
    let pos = str.indexOf("facts");
    alert(pos); // 0utputs: 7

    Similarly, you can use the lastIndexOf() method to get the index or position of the last occurrence of the specified string within a string, like this:

    Example

    let str = "If the facts don't fit the theory, change the facts.";
    let pos = str.lastIndexOf("facts");
    alert(pos); // 0utputs: 46

    Both the indexOf(), and the lastIndexOf() methods return -1 if the substring is not found. Both methods also accept an optional integer parameter which specifies the position within the string at which to start the search. Here’s an example:

    Example

    let str = "If the facts don't fit the theory, change the facts.";
     
    // Searching forwards
    let pos1 = str.indexOf("facts", 20);
    alert(pos1); // 0utputs: 46
     
    // Searching backwards
    let pos2 = str.lastIndexOf("facts", 20);
    alert(pos2); // 0utputs: 7

    Note: Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called myStr is myStr.length - 1.


    Searching for a Pattern Inside a String

    You can use the search() method to search a particular piece of text or pattern inside a string.

    Like indexOf() method the search() method also returns the index of the first match, and returns -1 if no matches were found, but unlike indexOf() method this method can also take a regular expression as its argument to provide advanced search capabilities.

    Example

    let str = "Color red looks brighter than color blue.";
     
    // Case sensitive search
    let pos1 = str.search("color");
    alert(pos1); // 0utputs: 30
     
    // Case insensitive search using regexp
    let pos2 = str.search(/color/i);
    alert(pos2); // 0utputs: 0

    Note: The search() method does not support global searches; it ignores the g flag or modifier (i.e. /pattern/g) of its regular expression argument.

    You will learn more about regular expressions in the upcoming chapters.


    Extracting a Substring from a String

    You can use the slice() method to extract a part or substring from a string.

    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 str.slice(startIndex, endIndex).

    The following example slices out a portion of a string from position 4 to position 15:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    let subStr = str.slice(4, 15);
    document.write(subStr); // Prints: quick brown

    You can also specify negative values. The negative value is treated as strLength + startIndex, where strLength is the length of the string (i.e. str.length), for example, if startIndex is -5 it is treated as strLength - 5. If startIndex is greater than or equal to the length of the string, slice() method returns an empty string. Also, if optional endIndex is not specified or omitted, the slice() method extracts to the end of the string.

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.slice(-28, -19)); // Prints: fox jumps
    document.write(str.slice(31)); // Prints: the lazy dog.

    You can also use the substring() method to extract a section of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method is very similar to the slice() method, except few differences:

    • If either argument is less than 0 or is NaN, it is treated as 0.
    • If either argument is greater than str.length, it is treated as if it were str.length.
    • If startIndex is greater than endIndex, then substring() will swap those two arguments; for example, str.substring(5, 0) == str.substring(0, 5).

    The following example will show you how this method actuallty works:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.substring(4, 15)); // Prints: quick brown
    document.write(str.substring(9, 0)); // Prints: The quick
    document.write(str.substring(-28, -19)); // Prints nothing
    document.write(str.substring(31)); // Prints: the lazy dog.

    Extracting a Fixed Number of Characters from a String

    JavaScript also provide the substr() method which is similar to slice() with a subtle difference, the second parameter specifies the number of characters to extract instead of ending index, like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is returned. The following example demonstrates how it works:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.substr(4, 15)); // Prints: quick brown fox
    document.write(str.substr(-28, -19)); // Prints nothing
    document.write(str.substr(-28, 9)); // Prints: fox jumps
    document.write(str.substr(31)); // Prints: the lazy dog.

    Replacing the Contents of a String

    You can use the replace() method to replace part of a string with another string. This method takes two parameters a regular expression to match or substring to be replaced and a replacement string, like str.replace(regexp|substr, newSubstr).

    This replace() method returns a new string, it doesn’t affect the original string that will remain unchanged. The following example will show you how it works:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace("color", "paint");
    alert(result); // 0utputs: Color red looks brighter than paint blue.

    By default, the replace() method replaces only the first match, and it is case-sensitive. To replace the substring within a string in a case-insensitive manner you can use a regular expression (regexp) with an i modifier, as shown in the example below:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace(/color/i, "paint");
    alert(result); // 0utputs: paint red looks brighter than color blue.

    Similarly, to replace all the occurrences of a substring within a string in a case-insensitive manner you can use the g modifier along with the i modifier, like this:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace(/color/ig, "paint");
    alert(result); // 0utputs: paint red looks brighter than paint blue.

    Converting a String to Uppercase or Lowercase

    You can use the toUpperCase() method to convert a string to uppercase, like this:

    Example

    let str = "Hello World!";
    let result = str.toUpperCase();
    document.write(result); // Prints: HELLO WORLD!

    Similarly, you can use the toLowerCase() to convert a string to lowercase, like this:

    Example

    let str = "Hello World!";
    let result = str.toLowerCase();
    document.write(result); // Prints: hello world!

    Concatenating Two or More Strings

    You can concatenate or combine two or more strings using the + and += assignment operators.

    Example

    let hello = "Hello";
    let world = "World";
    let greet = hello + " " + world;
    document.write(greet); // Prints: Hello World
     
    let wish  = "Happy";
    
    wish += " New Year";
    document.write(wish); // Prints: Happy New Year

    JavaScript also provides concat() method to combine strings, but it is not recommended.


    Accessing Individual Characters from a String

    You can use the charAt() method to access individual character from a string, like str.charAt(index). The index specified should be an integer between 0 and str.length - 1. If no index is provided the first character in the string is returned, since the default is 0.

    Example

    let str = "Hello World!";
    document.write(str.charAt());  // Prints: H
    document.write(str.charAt(6)); // Prints: W
    document.write(str.charAt(30)); // Prints nothing
    document.write(str.charAt(str.length - 1)); // Prints: !

    There is even better way to do this. Since ECMAScript 5, strings can be treated like read-only arrays, and you can access individual characters from a string using square brackets ([]) instead of the charAt() method, as demonstrated in the following example:

    Example

    let str = "Hello World!";
    document.write(str[0]); // Prints: H
    document.write(str[6]); // Prints: W
    document.write(str[str.length - 1]); // Prints: !
    document.write(str[30]); // Prints: undefined

    Note: The only difference between accessing the character from a string using the charAt() and square bracket ([]) is that if no character is found, [] returns undefined, whereas the charAt() method returns an empty string.


    Splitting a String into an Array

    The split() method can be used to splits a string into an array of strings, using the syntax str.split(separator, limit). The seperator argument specifies the string at which each split should occur, whereas the limit arguments specifies the maximum length of the array.

    If separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The following example shows how it works:

    Example

    let fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
    let fruitsArr = fruitsStr.split(", ");
    document.write(fruitsArr[0]); // Prints: Apple
    document.write(fruitsArr[2]); // Prints: Mango
    document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya
     
    // Loop through all the elements of the fruits array 
    for(let i in fruitsArr) {  
    
    document.write("&lt;p&gt;" + fruitsArr&#91;i] + "&lt;/p&gt;");
    }

    To split a string into an array of characters, specify an empty string ("") as a separator.

    Example

    let str = "INTERSTELLAR";
    let strArr = str.split("");
    document.write(strArr[0]); // Prints: I
    document.write(strArr[1]); // Prints: N
    document.write(strArr[strArr.length - 1]); // Prints: R
     
    // Loop through all the elements of the characters array and print them
    for(let i in strArr) {  
    
    document.write("&lt;br&gt;" + strArr&#91;i]);
    }

    You will learn about looping statements in detail JavaScript loops chapter.

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