js-icon

JavaScript Reference

  • Scripts can be added in 3 ways:
    • In the <head> section: It loads first.
    • In at the end of the <body>: It loads last.
    • Externally: <script src="demo.js"></script>
  • Comments can be added into code using // or /* */

String symbols

Code Output
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b backspace
\f formfeed

Operators

Operator Description
++, -- increment, decrement
%, / modulos, division
* multiplication
+, - addition, subtraction
Operator Equivalent to
= x = yx=yx = y
+= x = x + yx=x+yx = x + y
-= x = x - yx=xyx = x - y
*= x = x * yx=xyx = x * y
/= x = x / yx=x/yx = x / y
%= x = x % yx=xx = x % y
== equal to
=== identical to
!= not equal to
!== not identical
> greater than
>= greater than or equal to
< less than
<= less than or equal to

Variables are containers used for storing values.

  • Setting variables can be done in 3 ways:

    • var: For global variables
    • let: with let, you can re-assign values
    • const: You cannot re-assign values
  • Primitive Data Types

    • Strings
    • Numbers
    • Boolean
    • null
    • undefined
    • Symbol

Sample:

const iden = "John";
const years = 30;
const isCool = true;
const rating = 2.5;
const x = null;
const y = undefined;
let z; The same as const z = undefined
/* typeof method returns the data type of a variable */
console.log(typeof years);  see the datatype
const iden = "John";
const years = 30;
const isCool = true;
const rating = 2.5;
const x = null;
const y = undefined;
let z; The same as const z = undefined
/* typeof method returns the data type of a variable */
console.log(typeof years);  see the datatype

Naming Rules

  • The first letter must be a character, underscore(_) or a dollar sign($).
  • Numbers are not allowed as the first character.
  • Cannot include a mathematical or logical operator.
  • Must not contain spaces.
  • Hypens(-) are not allowed, it is reserved for subtraction.

Concatenation

  • It is used join multiple strings together with the use of +.
    const iden = "John";
    const years = 30;
    console.log("My name is " + iden + " and I am " + years + " years of age.");
    const iden = "John";
    const years = 30;
    console.log("My name is " + iden + " and I am " + years + " years of age.");

Template literial

  • It allows the use of raw strings with variables.
  • It is declared using backticks.
    console.log(`My name is ${iden} and I am ${years} years`);
    console.log(`My name is ${iden} and I am ${years} years`);

String Properties

const x = "Hello World";
const y = "technology, computers, it, code"
console.log(x.length); 	//checks the length
console.log(x.toUpperCase()); 	//converts to uppercase
console.log(x.toLowerCase()); 	//converts to lowercase
console.log(x.substring(0, 5)); 	//returns string within the indexes. 
console.log(y.split(',')); 	//splits string based on any specified character
    ```
    
const x = "Hello World";
const y = "technology, computers, it, code"
console.log(x.length); 	//checks the length
console.log(x.toUpperCase()); 	//converts to uppercase
console.log(x.toLowerCase()); 	//converts to lowercase
console.log(x.substring(0, 5)); 	//returns string within the indexes. 
console.log(y.split(',')); 	//splits string based on any specified character
    ```
    

Declaring Arrays

  • It is a variable that holds multiple values.
    Sample:
    const num = new Array(1, 2, 3, 4, 5);
    /* OR */
    const fruits = ["apples", "oranges", "pears"];
    /* OR */
    var array_name = new Array(n); 	//where n = specified number of items in the array
    array_name[0] = value;	//assign values later
    /* OR */
    var array_name = new Array(); 	//can contain any number of values.
    const num = new Array(1, 2, 3, 4, 5);
    /* OR */
    const fruits = ["apples", "oranges", "pears"];
    /* OR */
    var array_name = new Array(n); 	//where n = specified number of items in the array
    array_name[0] = value;	//assign values later
    /* OR */
    var array_name = new Array(); 	//can contain any number of values.

Manipulating an array

// Add values by assigning
fruits[3] = "grapes";

/* push("new element") adds a new element at the end of an array */	
fruits.push("mangoes");
    
/* unshift("element") adds an element at the beginning of an array */
fruits.unshift("Lemon");

/* pop() removes the last element in an array */
fruits.pop();
    
/* concat() creates a new array by merging existing arrays */
let bikes = ["haha", "toy", "food"];
let vech = cars.concat(bikes);
console.log(vech);

/* toString() converts an array into a string */
console.log(cars.toString())
// Add values by assigning
fruits[3] = "grapes";

/* push("new element") adds a new element at the end of an array */	
fruits.push("mangoes");
    
/* unshift("element") adds an element at the beginning of an array */
fruits.unshift("Lemon");

/* pop() removes the last element in an array */
fruits.pop();
    
/* concat() creates a new array by merging existing arrays */
let bikes = ["haha", "toy", "food"];
let vech = cars.concat(bikes);
console.log(vech);

/* toString() converts an array into a string */
console.log(cars.toString())
  • shift() removes the first element in an array.
  • sort() sort an array in ascending order.
  • reverse() reverses the elements of an array.

Iterating through arrays

  • forEach: It loops through an array.
    /*
    SYNTAX:
     array_name.forEach(function(variable){
        //statements
        e.g. console.log(variable)
     });
    */
    
    let cars = ["BMW", "Volvo", "Honda"];
    cars.forEach((item, index, array) => (console.log(item, index)));
    /*
    SYNTAX:
     array_name.forEach(function(variable){
        //statements
        e.g. console.log(variable)
     });
    */
    
    let cars = ["BMW", "Volvo", "Honda"];
    cars.forEach((item, index, array) => (console.log(item, index)));
  • of: It goes through all values in an array.
    for(let todo of todos){
       console.log(todo.text);
    }
    for(let todo of todos){
       console.log(todo.text);
    }

MAP, REDUCE & FILTER

  • map: Creates a new array from an array and performs a function on each array element.

    let num1 = [2, 3, 4];
    
    function multiply(val){
        return val * 2;
    }
    
    let num2 = num1.map(multiply);
    console.log(num2);
    //outputs [4, 6, 8]
    let num1 = [2, 3, 4];
    
    function multiply(val){
        return val * 2;
    }
    
    let num2 = num1.map(multiply);
    console.log(num2);
    //outputs [4, 6, 8]
  • The filter() method takes each element in an array and it applies a conditional statement against it.

    //checks if even
    function even(val){
        return val % 2 == 0;
    }
    
    let num2 = num1.filter(even);
    console.log(num2);
    //checks if even
    function even(val){
        return val % 2 == 0;
    }
    
    let num2 = num1.filter(even);
    console.log(num2);
  • reduce() method reduces an array of values down to just one value using a function.

    function sum(total, val){
        return total + val;
    }
    
    let num2 = num1.reduce(sum);
    console.log(num2);
    //outputs the sum
    function sum(total, val){
        return total + val;
    }
    
    let num2 = num1.reduce(sum);
    console.log(num2);
    //outputs the sum

  • It can created in different events.

  • Method1: Using {name: value} pairs

    const student = {
         name: "Chris",
         age: 21,
         studies: "Computer Science",
     };
    
    document.getElementById("demo").innerHTML = `${student.name} is ${student.age}yrs of age and he studies ${student.studies}.`;
    const student = {
         name: "Chris",
         age: 21,
         studies: "Computer Science",
     };
    
    document.getElementById("demo").innerHTML = `${student.name} is ${student.age}yrs of age and he studies ${student.studies}.`;
  • Method2: Using new keyword.

    const stu = new Object();
    stu.name = "Chris";
    stu.studies = "Computer Science";
     stu.age = 21;
    
    document.getElementById("demo").innerHTML = `${stu.name} is ${stu.age}yrs of age and he studies ${stu.studies}.`;
    const stu = new Object();
    stu.name = "Chris";
    stu.studies = "Computer Science";
     stu.age = 21;
    
    document.getElementById("demo").innerHTML = `${stu.name} is ${stu.age}yrs of age and he studies ${stu.studies}.`;
  • Method3: Using functions

    function student(name, age, study){
         this.name = name;
         this.age = age;
         this.study = study;
        }
    
    function student(name, age, study){
         this.name = name;
         this.age = age;
         this.study = study;
        }
    

const cate = new student("Chris", 21, "Computer");
console.log(cate);
```

Getters & Setters

 var car = {
     name: "BMW",
     color: "Navy Blue",
     fuel_type: "Diesel",
     
     //setter
     set fuel(fuel){
          this.fuel_type = fuel;
      }
     
     //getter
    get color(){
         return this.color;
   }
};

car.fuel_type = "Petrol";
console.log(car.fuel_type);
 var car = {
     name: "BMW",
     color: "Navy Blue",
     fuel_type: "Diesel",
     
     //setter
     set fuel(fuel){
          this.fuel_type = fuel;
      }
     
     //getter
    get color(){
         return this.color;
   }
};

car.fuel_type = "Petrol";
console.log(car.fuel_type);

Object Literials

  • It is more like key value pairs more like a python dictionary
    Sample"

     const person = {
         firstName: "John",
         lastName: "Doe",
         age: 30,
         hobbies: ["music", "movies", "sleeping"],
         address: {
             street: "50 main st",
             city: "Boston",
             state: "MA"
       }
    };
    
    console.log(person); 	//outputs person object
     const person = {
         firstName: "John",
         lastName: "Doe",
         age: 30,
         hobbies: ["music", "movies", "sleeping"],
         address: {
             street: "50 main st",
             city: "Boston",
             state: "MA"
       }
    };
    
    console.log(person); 	//outputs person object
  • Keys can be accessed using dot(.) syntax

    console.log(person.firstName, person.lastName);
    console.log(person.hobbies[1]);
    console.log(person.firstName, person.lastName);
    console.log(person.hobbies[1]);
  • Destructuring can be done and keys pulled out from object literials into actual vaiables.

    const { lastName, firstName, address: {city} } = person;
    console.log(lastName, firstName, city);
    const { lastName, firstName, address: {city} } = person;
    console.log(lastName, firstName, city);
  • Properties can be added later

    person.email = "johndoe@gamil.com";
    console.log(person);
    person.email = "johndoe@gamil.com";
    console.log(person);

JSON - Javascript Object Notation

Sample:

const todos = [
     {
         id: 1,
         text: "Take out trash",
         isCompleted: true
     },
    {
         id: 2,
         text: "Meeting with boss",
        isCompleted: true
     },
     {
         id: 3,
         text: "Dentist Appointment",
         isCompleted: false
     },
 ];

console.log(todos);
console.log(todos[1].text)

// // Converting to JSON
const todosJSON = JSON.stringify(todos);
console.log(todosJSON);
const todos = [
     {
         id: 1,
         text: "Take out trash",
         isCompleted: true
     },
    {
         id: 2,
         text: "Meeting with boss",
        isCompleted: true
     },
     {
         id: 3,
         text: "Dentist Appointment",
         isCompleted: false
     },
 ];

console.log(todos);
console.log(todos[1].text)

// // Converting to JSON
const todosJSON = JSON.stringify(todos);
console.log(todosJSON);

Loops

For loops

Syntax:

for(statement1; statement2; statement3){
    //Codes
}
for(statement1; statement2; statement3){
    //Codes
}
  • statement1 is executed before the loop starts. (Initialisation is done here.)
  • statement2 defines the condition for running the loop.
  • statement3 is executed each time after the loop has been executed. (Normally, increments or decrements are declared here.)

While loops

  • The code only runs when the condition is true.

Syntax:

while(condition){
   //codes
}
while(condition){
   //codes
}

Do-while loop

  • The code only runs when the condition is true.
  • It runs at least once since the block of code runs before the condition is checked.

Syntax:

do{
   //codes
}
while(condition);
do{
   //codes
}
while(condition);

Conditionals (if statement)

const x = 10;
const y = 5;
const x = 10;
const y = 5;
  • == matches the value not the data type.

    if(x == 10){
        console.log("x is 10");
    }
    else {
       console.log("x is not 10");
    }
    if(x == 10){
        console.log("x is 10");
    }
    else {
       console.log("x is not 10");
    }
  • === matches both the value and the data type.

    if(x === 10){
       console.log("x is 10");
    }
    
    if (x > 5 || y === 10){
       console.log("True condition");
    }
    if(x === 10){
       console.log("x is 10");
    }
    
    if (x > 5 || y === 10){
       console.log("True condition");
    }

Ternary operator

  • It is a single line if statement used to set a variable based on a condition.
    const x  = 20;
    const color = x > 10 ? 'Red' : "Blue";
    console.log(color);
    //if x>10, color=Red, else color=Blue
    const x  = 20;
    const color = x > 10 ? 'Red' : "Blue";
    console.log(color);
    //if x>10, color=Red, else color=Blue

Switches

Syntax:

switch(expression){
    case n1:
        //Statements
        break;
    case n2:
        //Statements
        break;
    case n3:
        //Statements
        break;
    // Any number of cases
    default:
        //Statements
}
switch(expression){
    case n1:
        //Statements
        break;
    case n2:
        //Statements
        break;
    case n3:
        //Statements
        break;
    // Any number of cases
    default:
        //Statements
}
  • The default keyword specifies a code to run if there is no match.
  • The break keyword allows a code to jump out of a loop.

The continue keyword only breaks one iteration in a loop and continues with the next iteration.

Declaring functions

Using let keyword

let x = function(val){ return val * val; };
console.log(x(5));
let x = function(val){ return val * val; };
console.log(x(5));

Using Function constructor

var myfunction = new Function("a", "b", "return a + b");
console.log(myfunction(5, 20));
var myfunction = new Function("a", "b", "return a + b");
console.log(myfunction(5, 20));

Self-invoking functions

  • They are invoked automatically without being called.
    //Syntax:
    (function() {
           function_body   //It calls itself
      })();
    
    //Sample
    (function() {
        console.log(5+8);
    })();
    //Syntax:
    (function() {
           function_body   //It calls itself
      })();
    
    //Sample
    (function() {
        console.log(5+8);
    })();

Arrow functions

  • They are not recommended for use as methods and constructors.
    const myfunc = (a, b, c) => {return a*b*c};
    console.log(myfunc(2,3,4));
    
    //Another sample
    const addNums = (a = 1, b = 1) => a + b;
    const addNums = num1 => num1 + 5;
    console.log(addNums(5, 5));
    const myfunc = (a, b, c) => {return a*b*c};
    console.log(myfunc(2,3,4));
    
    //Another sample
    const addNums = (a = 1, b = 1) => a + b;
    const addNums = num1 => num1 + 5;
    console.log(addNums(5, 5));

Predefined functions

  • eval: evaluates a string and returns a value
  • parseInt: parses a string arguement and returns an integer of the specified radix or base.
  • parseFloat: parses a string arguement and returns a float.
  • escape: returns the hexadecimal encoding of an arguement.
  • unescape: Returns the ASCII string for a specified value.

Closures

  • It is a feature where an inner function has access to the outer function's variables.
  • A closure has three scope chains.
    • Has access to variables its own scope, outer functions and global variables.
  • A scope chain is a stack consisting of all the references to the variables for the function being executed.

Sample:

let a = 10;
function first(){
    let b = 20;
    function second(){
        let c = 20 + a + b;
        return c;
    }
    return second()
}

let sum = first();
console.log(`The sum is ${sum}`);
let a = 10;
function first(){
    let b = 20;
    function second(){
        let c = 20 + a + b;
        return c;
    }
    return second()
}

let sum = first();
console.log(`The sum is ${sum}`);

  • Alert Box: It is used when you want to ensure that information gets to the user. When it pops up, the user must click ok to proceed.
    E.g.

    alert("Do you know?");
    alert("Do you know?");
  • Prompt Box: It is often used to have the user input a value before entering a page. When a prompt box opens up, the user will either have to click ok or cancel to proceed.

    • If user clicks ok, the box returns the input value.
    • If the user clicks cancel, the box returns null.
    • The prompt() method takes 2 params: The label and the string to display in the text box(optional).
      E.g.
    var user = prompt("Enter your name");
    alert(user);
    var user = prompt("Enter your name");
    alert(user);
  • Confirm Box: It is often used to have the user verify something. The user must click ok or cancel to proceed.

    • If the user clicks ok, the box returns true; cancel, false.
      E.g.
    var result = confirm("How are you?");
    if(result == true){
        alert("fine");
    } else{
        alert("not fine");
    }
    var result = confirm("How are you?");
    if(result == true){
        alert("fine");
    } else{
        alert("not fine");
    }

Contructor Function

  • It makes use of functions.
  • Getters and setters are manually set as prototypes.
    function Person(firstName, lastName, dob) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.dob = new Date(dob);
     }
     // Prototyping is used to set constructors; it is the recommended practice
     Person.prototype.getFullName = function(){
         return `${this.firstName} ${this.lastName}`;
     }
    function Person(firstName, lastName, dob) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.dob = new Date(dob);
     }
     // Prototyping is used to set constructors; it is the recommended practice
     Person.prototype.getFullName = function(){
         return `${this.firstName} ${this.lastName}`;
     }

Syntatic sugar OOP

  • It makes use of classes.
  • It automatically prototypes the getters and setters.
  • It is the most recommended method OOP in javascript.
     class Person {
         constructor(firstName, lastName, dob) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.dob = new Date(dob);
        }
    
        getFullName(){
             return `${this.firstName} ${this.lastName}`;
           }
     }
     class Person {
         constructor(firstName, lastName, dob) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.dob = new Date(dob);
        }
    
        getFullName(){
             return `${this.firstName} ${this.lastName}`;
           }
     }

Instantiate object

const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '4-3-1890');

console.log(person1.getFullName());
console.log(person2);
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '4-3-1890');

console.log(person1.getFullName());
console.log(person2);

  • Syntax: Math.method()
  • Some of the methods are listed below:
Method Description
abs(x)abs(x)abs(x) Returns the absolute value of xxx
ceil(x)ceil(x)ceil(x) Returns xxx, rounded upwards to the nearest integer
cos(x)cos(x)cos(x) Returns the cosine of xxx, where xxx is in radians
max(x, y, ...)max(x,y,...)max(x, y, ...) Returns the number with the highest value
min(x, y, ...)min(x,y,...)min(x, y, ...) Returns the number with the lowest value
pow(x, y)pow(x,y)pow(x, y) Returns the value of xxx to the power yyy
round(x)round(x)round(x) Returns xxx to the nearest integer
sin(x)sin(x)sin(x) Returns the sine of xxx, where xxx is in radians
sqrt(x)sqrt(x)sqrt(x) Returns the square root of xxx
tan(x)tan(x)tan(x) Returns the tangent of an angle, where xxx is in radians
random()random()random() Returns a random number between 0 and 1

Example(using random and ceil):

  • To get a random number between say 1 - 10, Math.random() is multiplied by 10; and take Math.ceil() from it.
    Math.ceil(Math.random()*10)
    Math.ceil(Math.random()*10)

  • It consists of a: year, month, day, hour, minute, second, milliseconds.
  • Using new Date() statement to create a new change object with the current time and date.
    E.g.
    var d = new Date();
    var d = new Date();

One day consists of 86,400,00086,400,00086,400,000 milliseconds.
Date objects don't change once created.

Date Methods

Method Description
getFullYear gets the year
getMonth gets the month
getDate get the day of the month
getDay get the day of the week
getHours gets the hours
getMinutes gets the minutes
getSeconds gets the seconds
getMilliseconds gets the milliseconds

Sample: Displays the current time

function printTime(){
    var  d = new Date();
    var hours = d.getHours();
    var mins = g.getMinutes();
    var secs = d.getSeconds();
    document.body.innerHTML = `${hours}:${mins}:${secs}`;
}
setInterval(printTime, 1000);
function printTime(){
    var  d = new Date();
    var hours = d.getHours();
    var mins = g.getMinutes();
    var secs = d.getSeconds();
    document.body.innerHTML = `${hours}:${mins}:${secs}`;
}
setInterval(printTime, 1000);

The innerHTML property sets or returns the HTML content of an element.

  • A promise is an asynchronous action that may complete at some point in the future and produce a value.

  • Promises has 3 states: pending, fulfilled and rejected.

  • General syntax:

    /* let some_action = new Promise(function(resolve, reject){
        //perform some work
    })*/
    /* let some_action = new Promise(function(resolve, reject){
        //perform some work
    })*/
  • E.g.

    let car = new Promise(function(resolve, reject){
        fuel_fullTank = true;
        if(fuel_fullTank){
            resolve();
        }
        else{
             reject();
        }
    });
    
    car.then(function(){
        console.log("The fuel tank is full");
    });
    
    car.catch(function(){
        console.log("The fuel tank is empty")
    });
    let car = new Promise(function(resolve, reject){
        fuel_fullTank = true;
        if(fuel_fullTank){
            resolve();
        }
        else{
             reject();
        }
    });
    
    car.then(function(){
        console.log("The fuel tank is full");
    });
    
    car.catch(function(){
        console.log("The fuel tank is empty")
    });
  • The resolve() function is called by using the then() method and the reject() function is called by using the catch() method is called.

Nested promises

Sample:

let empty_tank = function(){
    return new Promise(function(resolve, reject){
        resolve("The car doesn't have enough fuel.");
    });
}

let hot_engine = function(msg){
    return new Promise(function(resolve, reject){
        resolve( msg + "The engine is overheating.");
    });
}

let travel = function(msg){
    return new Promise(function(resolve, reject){
        resolve(msg + "The car is not safe for travelling.");
    });
}


// The message in the resolve can be retrieved from the `res` param
// The function name is the arguement
empty_tank().then(res => {
    return hot_engine(res)
}).then( res => {
    return travel(res)
}).then(res => {
     return console.log(res)
})
let empty_tank = function(){
    return new Promise(function(resolve, reject){
        resolve("The car doesn't have enough fuel.");
    });
}

let hot_engine = function(msg){
    return new Promise(function(resolve, reject){
        resolve( msg + "The engine is overheating.");
    });
}

let travel = function(msg){
    return new Promise(function(resolve, reject){
        resolve(msg + "The car is not safe for travelling.");
    });
}


// The message in the resolve can be retrieved from the `res` param
// The function name is the arguement
empty_tank().then(res => {
    return hot_engine(res)
}).then( res => {
    return travel(res)
}).then(res => {
     return console.log(res)
})

  • They are built on top of promises.

  • Genereal Syntax:

    async function func_name(){
        await some_promsise();
    }
    async function func_name(){
        await some_promsise();
    }
  • Sample:

let result = function (score) {
    return new Promise(function (resolve, reject) {
        console.log("Calculating results...")
        if (score > 50) {
            resolve("congratulations! You passed")
        } else if(typeof score != "number"){
            reject("Please enter a valid score")
        }
        else {
            reject("You have failed")
        }
    })
}

let grade = function (response) {
    return new Promise(function (resolve, reject) {
        console.log("Calculating your grade...")
        resolve("Your grade is A, " + response)
    })
}

// Implemented using normal promises method
result(80).then(response => {
    console.log("Results received")
    return grade(response)
}).then(final_grade => {
    console.log(final_grade)
}).catch(err => {
    console.log(err)
})


// Implemented using async & await
//async declarations cannot be initialsed as an arrow function
async function Calc() {
    try{
        const response = await result(80)
        console.log("Results received")
        const final_grade = await grade(response)
        console.log(final_grade)
    } catch(err){
        console.log(err)
    }
}

// Calling the async function
Calc()
let result = function (score) {
    return new Promise(function (resolve, reject) {
        console.log("Calculating results...")
        if (score > 50) {
            resolve("congratulations! You passed")
        } else if(typeof score != "number"){
            reject("Please enter a valid score")
        }
        else {
            reject("You have failed")
        }
    })
}

let grade = function (response) {
    return new Promise(function (resolve, reject) {
        console.log("Calculating your grade...")
        resolve("Your grade is A, " + response)
    })
}

// Implemented using normal promises method
result(80).then(response => {
    console.log("Results received")
    return grade(response)
}).then(final_grade => {
    console.log(final_grade)
}).catch(err => {
    console.log(err)
})


// Implemented using async & await
//async declarations cannot be initialsed as an arrow function
async function Calc() {
    try{
        const response = await result(80)
        console.log("Results received")
        const final_grade = await grade(response)
        console.log(final_grade)
    } catch(err){
        console.log(err)
    }
}

// Calling the async function
Calc()

  • this keyword refers to an object which is executing the current piece of code.

  • If the function being referenced is a regular function, this references the global object.
    E.g.

    var value = 100
    
    let func = () => {
        let value = 50
        console.log(`Function's value: ${value}`)
        console.log((`Global value: ${this.value}`))
    }
    
    func()
    var value = 100
    
    let func = () => {
        let value = 50
        console.log(`Function's value: ${value}`)
        console.log((`Global value: ${this.value}`))
    }
    
    func()
  • If the function that is being referenced is a method in an object, 'this' references the object itself.
    E.g.

    const random = {
        name: "John",
        info(){
            console.log(`My name is ${this.name}`)
        }
    }
    
    random.info()
    const random = {
        name: "John",
        info(){
            console.log(`My name is ${this.name}`)
        }
    }
    
    random.info()
  • It references the object that is executing the current function.
    E.g.

    const rand = {
        name: "Tutorial",
        video: ["JavaScript", "Python", "CSS"],
        info(){
            this.video.forEach(tag =>{
                console.log(tag, this.name)
            })
        }
    }
    
    
    const rand = {
        name: "Tutorial",
        video: ["JavaScript", "Python", "CSS"],
        info(){
            this.video.forEach(function (tag){
                console.log(tag, this.name)
            }, this)
        }
    }
    
    rand.info()
    const rand = {
        name: "Tutorial",
        video: ["JavaScript", "Python", "CSS"],
        info(){
            this.video.forEach(tag =>{
                console.log(tag, this.name)
            })
        }
    }
    
    
    const rand = {
        name: "Tutorial",
        video: ["JavaScript", "Python", "CSS"],
        info(){
            this.video.forEach(function (tag){
                console.log(tag, this.name)
            }, this)
        }
    }
    
    rand.info()

  • A regular expression is a sequence of characters that forms a search pattern.
  • Syntax: /patttern/flags

Flags

  • It specifies the behavior of regular expressions.
  • Examples of the flags used include:
    • g - global - finds all matches instead of stopping at the first.
    • i - ignore case - /[a-z]i is equivalent to /[a-zA-Z]/.
    • m - multiline - ^ and $ match the beginning and the end of each line respectively.
    • u - unicode.
    • y - finds all consecutive adjacent matches.

Patterns

  • They are usually brackets used to find the range of characters.
  • Examples of some patterns:
    • [a-z] - Finds all characters from a to z (lowercase)
    • [0-9] - Finds any digit berween 0 and 9
    • [a-z|0-9] - Finds any character of digits separated by '|'
Quantifiers
  • They define the number of occurences in a string.
  • Some include:
    • + - indicates one or more occurence of a character
    • * - indicates zero or more occurences of a character
    • ? - indicates zero or one occurence of a character

Practical Examples:
/*PHONE NUMBER VALIDATION*/
const num = "(555)-555-1254"
const regex = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/g
const found = regex.test(num)

if(!found){
    console.log("Not valid!")
} else{
    console.log("Valid")
}


/* EMAIL VALIDATION */
const email = "dasorange@gmail.com"
const regex = /^([a-zA-Z0-9\._]+)@([a-zA-Z0-9\._])+.[com]$/g
const found = regex.test(email)

if(!found){
    console.log("Not valid!")
} else{
    console.log("Valid")
}
/*PHONE NUMBER VALIDATION*/
const num = "(555)-555-1254"
const regex = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/g
const found = regex.test(num)

if(!found){
    console.log("Not valid!")
} else{
    console.log("Valid")
}


/* EMAIL VALIDATION */
const email = "dasorange@gmail.com"
const regex = /^([a-zA-Z0-9\._]+)@([a-zA-Z0-9\._])+.[com]$/g
const found = regex.test(email)

if(!found){
    console.log("Not valid!")
} else{
    console.log("Valid")
}

Events

Event Description
onclick occurs when a user clicks on an element
onload occurs when an object has been loaded
onunload occurs once a page has been unloaded (for <body>)
onchange occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <keygen>, <select> and <textarea>)
onmouseover occurs when a pointer is moved onto an element, or onto one of its children
onmouseout occurs when a user moves the mouse pointer out of an element, or out of one of its children
onmousedown occurs when a user presses a mouse button over an element
onmouseup occurs when a user relaxes a mouse button over an element
onblur occurs when an element loses focus
onfocus occurs when an element gets focus

Samples:

<script>
    var x = document.getElementById("demo")
    x.onclick = function(){
        document.body.innerHTML = Date()
    }
</script>

<!-- OR -->

<button onclick="func()">Date</button>

<script>
    func= () => {
        document.body.innerHTML = Date()
    }
</script>
<script>
    var x = document.getElementById("demo")
    x.onclick = function(){
        document.body.innerHTML = Date()
    }
</script>

<!-- OR -->

<button onclick="func()">Date</button>

<script>
    func= () => {
        document.body.innerHTML = Date()
    }
</script>

  • The onload and onunload events are triggered when the user enters or leave a page.
  • The window.onload event can be used to run a code after the whole page is loaded.

Event Listeners

  • They attach an event handlerto an element without over writing existing event handlers.
  • Syntax:
    element.addEventListener(event, function, useCapture)
    element.addEventListener(event, function, useCapture)
    • The 1^{st}1st1^{st} parameter specifies the event type.
    • The 2^{nd}2nd2^{nd} parameter specifies the function to call when an event occurs.
    • The 3^{rd}3rd3^{rd} parameter specifies to use event bubbling or event capturing. It is optional.

Event Propagation

  • bubbling: The innermost elements' events are handleed first and then the outermost elements' events are handled.
  • capturing: The outermost elements' events are handleed first and then the innermost elements' events are handled.

The useCapture parameter specifies the event propagation

Samples

//selects button
const btn = document.querySelector(".btn");

//event listener for mouseout event
//changes the background color of element with id="my-form" and the body 
btn.addEventListener('mouseout', (e) => {
    e.preventDefault();
    document.querySelector("#my-form").style.background = '#ccc';
    document.querySelector("body").style.background = "#000";
});
//selects button
const btn = document.querySelector(".btn");

//event listener for mouseout event
//changes the background color of element with id="my-form" and the body 
btn.addEventListener('mouseout', (e) => {
    e.preventDefault();
    document.querySelector("#my-form").style.background = '#ccc';
    document.querySelector("body").style.background = "#000";
});
/* Form handling test */
//selecting the elements from the DOM
const myForm = document.querySelector("#my-form");
const nameInput = document.querySelector("#name");
const emailInput = document.querySelector("#email");
const msg = document.querySelector(".msg");
const userList = document.querySelector("#users");

//Adding an event listener to execute onsubmit function when event occurs
myForm.addEventListener("submit", onsubmit);

//onsubmit function
function onsubmit(e) {
    //prevents default action of button
    e.preventDefault();
    
    //checks if input fields are empty
    if(nameInput.value === "" || emailInput.value === ""){
        msg.innerHTML = "Please enter all fields!";
        setTimeout(() => msg.remove(), 3000);
    }
    
    //A new list element is created if the fields are not empty
    else {
        const li = document.createElement("li");
        
        //Appends values to the `<li>`
        li.appendChild(document.createTextNode(`${nameInput.value}: ${emailInput.value}`));

        //Adds the new <li> item to the parent <ul> and displays data on the screen.
        userList.appendChild(li);

        //Clear fields for next input
        nameInput.value = "";
        emailInput.value = "";
    }
}
/* Form handling test */
//selecting the elements from the DOM
const myForm = document.querySelector("#my-form");
const nameInput = document.querySelector("#name");
const emailInput = document.querySelector("#email");
const msg = document.querySelector(".msg");
const userList = document.querySelector("#users");

//Adding an event listener to execute onsubmit function when event occurs
myForm.addEventListener("submit", onsubmit);

//onsubmit function
function onsubmit(e) {
    //prevents default action of button
    e.preventDefault();
    
    //checks if input fields are empty
    if(nameInput.value === "" || emailInput.value === ""){
        msg.innerHTML = "Please enter all fields!";
        setTimeout(() => msg.remove(), 3000);
    }
    
    //A new list element is created if the fields are not empty
    else {
        const li = document.createElement("li");
        
        //Appends values to the `<li>`
        li.appendChild(document.createTextNode(`${nameInput.value}: ${emailInput.value}`));

        //Adds the new <li> item to the parent <ul> and displays data on the screen.
        userList.appendChild(li);

        //Clear fields for next input
        nameInput.value = "";
        emailInput.value = "";
    }
}

DOM: Document Object Module

  • To see all objects in the window:

    console.log(window);
    console.log(window);
  • To be able to manipulate the DOM elements, they must first be selected.

Selecting Elements

Single Elements

  • To find element by id:
    document.getElementById("id_name")
    document.getElementById("id_name")
  • Using query selector (It takes class, id or tags as an arguement):
    console.log(document.querySelector("h1"));
    console.log(document.querySelector("h1"));

Multiple Elements

  • To find element by class name:

    document.getElementsByClassName("class_name")
    document.getElementsByClassName("class_name")
  • To find element by tag name:

    document.getElementsByTagName("tag_name")
    document.getElementsByTagName("tag_name")
  • Using querySelectorAll (It takes class, id or tags as an arguement):

    console.log(document.querySelectorAll(".item"));
    console.log(document.querySelectorAll(".item"));

  • Using the document.getElementsByClassName() method, it treats the tags with class=class_name as arrays.
  • It also applies to the other methods of selecting elements.
    E.g.
    var arr = document.getElementsByClassName("demo")
    // accesing the second element
    arr[1].innerHTML = "Hi"
    var arr = document.getElementsByClassName("demo")
    // accesing the second element
    arr[1].innerHTML = "Hi"

Changing Attributes

Sample:

<img id="myimg" src="orange.png" />
<a href="google.com">link</a>
<img id="myimg" src="orange.png" />
<a href="google.com">link</a>
var img = document.getElementById("myimg")
//changing the src attribute
img.src = "pear.jpg"

var links = document.getElementsByTagName('a')
link[0] = "duckduckgo.com"
var img = document.getElementById("myimg")
//changing the src attribute
img.src = "pear.jpg"

var links = document.getElementsByTagName('a')
link[0] = "duckduckgo.com"

Changing Style

Sample:

<div id="demo" style="width:200px;">text</div>
<div id="demo" style="width:200px;">text</div>
var text = document.getElementById("demo")
//Changing width
text.style.width = "100px"
//Adding color attribute
text.style.color = "#ffffff"
var text = document.getElementById("demo")
//Changing width
text.style.width = "100px"
//Adding color attribute
text.style.color = "#ffffff"

All CSS properties can be set using JavaScript

Extra Samples:

ul.firstElementChild.textContent = "Hello";
ul.children[1].innerText = "Brad";
ul.lastElementChild.innerHTML = "<h4>Hello</h4>";
const btn = document.querySelector(".btn");
btn.style.background = 'red';
ul.firstElementChild.textContent = "Hello";
ul.children[1].innerText = "Brad";
ul.lastElementChild.innerHTML = "<h4>Hello</h4>";
const btn = document.querySelector(".btn");
btn.style.background = 'red';

Creating Elements

  • Clones an element and resturns a resulting node.

    element.cloneNode()
    element.cloneNode()
  • To create a new element node

    document.createElement(element)
    document.createElement(element)
  • To create a new text node

    document.createTextNode(text)
    document.createTextNode(text)
  • Adding a new child node to an element as the last child node

    element.appendChild(newNode)
    element.appendChild(newNode)
  • This inserts node1 as a child before node2

    element.insertBefore(node1, node2)
    element.insertBefore(node1, node2)

Examples:

<div id="demo">Some Content</div>
<div id="demo">Some Content</div>
// Creating a new paragraph
let p = document.createElement('p')
var node = document.createTextNode("Some new text")

// Adding the text to the paragraph
p.appendChild(node)

// Adding the paragraph to the div
var div = document.getElementById("demo")
div.appendChild(p)
// Creating a new paragraph
let p = document.createElement('p')
var node = document.createTextNode("Some new text")

// Adding the text to the paragraph
p.appendChild(node)

// Adding the paragraph to the div
var div = document.getElementById("demo")
div.appendChild(p)

Removing Elements

  • To remove an element, you must select the parent of the element and use the removeChild(node) method.

Samples:

<div id="demo">
    <p id="p1"></p>
    <p id="p2"></p>
</div>
<div id="demo">
    <p id="p1"></p>
    <p id="p2"></p>
</div>
var parent = document.getElementById("demo")
var node = document.getElementById("p1")
parent.removeChild(node)

/* OR */

var node = document.getElementById("p1")
node.parentNode.removeChild(node)

//removing the last child
div.lastElementChild.remove();
var parent = document.getElementById("demo")
var node = document.getElementById("p1")
parent.removeChild(node)

/* OR */

var node = document.getElementById("p1")
node.parentNode.removeChild(node)

//removing the last child
div.lastElementChild.remove();
  • The parent can also be removed using the .remove() method.
    E.g.
    ul.remove();
    ul.remove();

Replacing an element

  • Syntax:
    element.replaceChild(newNode, oldNode)
    element.replaceChild(newNode, oldNode)
  • Sample:
    <div id="demo">
        <p id="p1">Hello</p>
        <p id="p2">Hi</p>
    </div>
    <div id="demo">
        <p id="p1">Hello</p>
        <p id="p2">Hi</p>
    </div>
    var p = document.createElement('p')
    var text = document.createTextNode("This is new")
    p.appendChild(text)
    
    var parent = document.getElementById("demo")
    var child = document.getElementById("p1")
    parent.replaceChild(p, child)
    var p = document.createElement('p')
    var text = document.createTextNode("This is new")
    p.appendChild(text)
    
    var parent = document.getElementById("demo")
    var child = document.getElementById("p1")
    parent.replaceChild(p, child)

SetInterval

  • It calls a function or evaluates an expression at specified intervals(in milliseconds).
  • It will contine calling the function until clearInterval() is called or the window is closed.
    E.g.
    function myAlert(){
        alert("Hi");
    }
    setInterval(myAlert, 3000);
    //calls myAlert function every 3 seconds
    function myAlert(){
        alert("Hi");
    }
    setInterval(myAlert, 3000);
    //calls myAlert function every 3 seconds

Form Validation

Sample:

let validate = () => {
    if(document.myform.Email.value == ""){
        alert("Please provide your Email ID")
        document.myform.Email.focus()
        return false
    } else if(document.myform.Password.value == ""){
        alert("Please provide your Password")
        document.myform.Password.focus()
        return false
    } else {
        return true
    }
}
let validate = () => {
    if(document.myform.Email.value == ""){
        alert("Please provide your Email ID")
        document.myform.Email.focus()
        return false
    } else if(document.myform.Password.value == ""){
        alert("Please provide your Password")
        document.myform.Password.focus()
        return false
    } else {
        return true
    }
}

Note: action attribute redirects the user to a new page after successful form submission.

Animation: Moving an element

<div id="box" style="background-color: blue; width: 100px; height: 100px; position: relative; border-radius: 50px;"></div>
<div id="box" style="background-color: blue; width: 100px; height: 100px; position: relative; border-radius: 50px;"></div>
var pos = 0 	//starting position

// Getting the box element
var box = document.getElementById("box")

function move(){
    console.log(this.pos)
    this.pos += 10
    box.style.left = String(this.pos + "px") 
}


setInterval(move, 1000)
var pos = 0 	//starting position

// Getting the box element
var box = document.getElementById("box")

function move(){
    console.log(this.pos)
    this.pos += 10
    box.style.left = String(this.pos + "px") 
}


setInterval(move, 1000)