L

js 7 Flashcards

This Keyword
  • The this keyword refers to the object that is currently executing the code. It provides a reference to the object upon which a method or function is called.

console.log(this);

Understanding Context

  • The value of this changes based on context. In a method of an object, this refers to the object itself. In a global scope, this refers to the global object (e.g., Window in browsers).

// In a browser
console.log(this === window); // true
Student Object and 'this'
  • A student object demonstrates this usage with properties like name, age, subject marks (eng, math, phy), and a method getAvg to calculate the average.

const student = {
    name: 'John',
    age: 20,
    eng: 90,
    math: 85,
    phy: 75,
    getAvg: function() {
        return (this.eng + this.math + this.phy) / 3;
    }
};
  • getAvg uses this to correctly access the student's properties (this.eng, this.math, this.phy) to calculate the average marks.

Correcting the getAvg Method with 'this'
  • Using this ensures properties are accessed in the correct context, demonstrated by calculating the average marks of a student.

  • ${this.name} includes the student's name in the output, personalizing the message with the student's name and average score.

Logging 'this' Context
  • console.log(this) is a debugging tool to inspect the context of this. When student.getAvg() is called, this refers to the student object.

const student = {
    name: 'John',
    age: 20,
    eng: 90,
    math: 85,
    phy: 75,
    getAvg: function() {
        console.log(this); // Logs the student object
        return (this.eng + this.math + this.phy) / 3;
    }
};

student.getAvg();
Global Function getAvg (Incorrect)
  • A global getAvg function shows this referring to the Window object in browsers, differing from the object-specific context.

function getAvg() {
    console.log(this); // Logs the Window object in browsers
    return NaN;
}

getAvg();
Window Object
  • The Window object represents the global scope in a browser, containing properties like window, document, location, and methods like alert, atob, btoa, etc.

console.log(window);
console.log(window.document);
console.log(window.location);
Try & Catch Block
  • try tests a block of code for errors, while catch handles errors, preventing script termination.

try {
    // Code that might throw an error
} catch (error) {
    // Code to handle the error
}
Error Handling
  • Error handling with try...catch prevents script termination due to runtime errors, ensuring a smoother user experience.

try {
    console.log(a); // 'a' is not defined
} catch (error) {
    console.error('Error:', error.message); // Handles the ReferenceError
}
Example of Try & Catch
  • Demonstrates try...catch handling a ReferenceError when logging an undefined variable a.

try {
    console.log(a); // Trying to access an undefined variable
} catch (error) {
    console.log('a is not defined'); // Handling the error
}
Arrow Functions
  • Arrow functions (const func = (arg1, arg2, ...) => { function definition }) offer a concise syntax for function expressions.

const sum = (a, b) => {
    return a + b;
};

console.log(sum(5, 3)); // Output: 8
Cube Function
  • An arrow function cube calculates the cube of a number.

const cube = (n) => {
    return n * n * n;
};

console.log(cube(3)); // Output: 27
Implicit Return
  • Arrow functions can have an implicit return when the body is a single expression, like const mul = (a, b) => (a * b);

const mul = (a, b) => (a * b);

console.log(mul(5, 4)); // Output: 20
setTimeout
  • setTimeout(function, timeout) executes a function after a specified delay (in milliseconds), useful for asynchronous operations.

setTimeout(function() {
    console.log("This will be logged after 3 seconds");
}, 3000);
Usage Example
  • Demonstrates logging messages immediately and after a delay using setTimeout.

console.log("Hi there!");
setTimeout(function() {
    console.log("Apna College");
}, 4000);
console.log("Welcome to");
setInterval
  • setInterval(function, timeout) executes a function repeatedly at a specified interval, ideal for recurring tasks, and clearInterval(id) stops the interval.

const intervalId = setInterval(function() {
    console.log("This will be logged every 2 seconds");
}, 2000);

// Stop the interval after 10 seconds
setTimeout(function() {
    clearInterval(intervalId);
    console.log("Interval stopped");
}, 10000);
'this' with Arrow Functions
  • Arrow Functions:

    • Inherit this from their surrounding context (lexical scope), making it predictable.

  • Regular Functions:

    • this is determined by the calling object, which can be more dynamic.

const obj = {
    value: 42,
    regularFunction: function() {
        console.log("Regular function: ", this.value);
    },
    arrowFunction: () => {
        console.log("Arrow function: ", this.value);
    }
};

obj.regularFunction();
obj.arrowFunction();
Student Object and 'this' Context
  • Demonstrates this context within a student object, showing how this refers to the global scope when assigned to an object property in the global context.

const student = {
    name: 'Alice',
    marks: [80, 90, 75],
    prop: this // In global context, this refers to the Window object
};

console.log(student.prop);
Global Scope
  • Variables declared outside any function or block have global scope.

const a = 5;
console.log(window.a);
getName Method
  • getName method uses this to access the name property of the student object.

const student = {
    name: 'Bob',
    getName: function() {
        console.log(this.name);
    }
};

student.getName();
getMarks Method
  • getMarks method uses an arrow function, so this refers to the global scope, not the student object.

const student = {
    name: 'Charlie',
    getMarks: () => {
        console.log(this);
    }
};

student.getMarks();
getInfo1 and getInfo2 Methods
  • getInfo1 uses an arrow function within setTimeout, so this refers to the student object.

  • getInfo2 uses a regular function within setTimeout, so this refers to the Window object.

const student = {
    name: 'David',
    getInfo1: function() {
        setTimeout(() => {
            console.log(this.name); // Refers to student object
        }, 1000);
    },
    getInfo2: function() {
        setTimeout(function() {
            console.log(this); // Refers to Window object
        }, 1000);
    }
};

student.getInfo1(); // Output: David (after 1 second)
student.getInfo2(); // Output: Window object (after 1 second)
Practice Questions: Arrow Functions and Intervals
  • Q1: Arrow function to return the square of a number.

  • Q2: Function to print "Hello World" 5 times at 2s intervals.

function printHello() {
    let count = 0;
    const intervalId = setInterval(() => {
        console.log("Hello World");
        count++;
        if (count === 5) {
            clearInterval(intervalId);
        }
    }, 2000);
}

printHello();
Practice Solutions
  • Ans 1: (arrayAverage)

const arrayAverage = (arr) => {
    let total = 0;
    for (let number of arr) {
        total += number;
    }
    return total / arr.length;
};

let arr = [1, 2, 3, 4, 5, 6];
console.log(arrayAverage(arr));
  • Ans 2: (isEven)

let num;
const isEven = (num) => num % 2 === 0;
Additional Practice Questions
  • QS1: Arrow function arrayAverage to return the average of an array of numbers.

  • QS2: Arrow function isEven() to check if a number is even.

  • QS3: What is the output of the following code?

const object = {
    message: 'Hello, World!',
    logMessage() {
        console.log(this.message);
        setTimeout(object.logMessage, 1000);
    }
};
  • QS4: What is the output of the following code?

let length = 4;
function callback() {
    console.log(this.length);
}

const object = {
    length: 5,
    method (callback) {
        callback();
    }
};

object.method(callback, 1, 2);