js 7 Flashcards
This Keyword
The
thiskeyword 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
thischanges based on context. In a method of an object,thisrefers to the object itself. In a global scope,thisrefers to the global object (e.g.,Windowin browsers).
// In a browser
console.log(this === window); // true
Student Object and 'this'
A
studentobject demonstratesthisusage with properties likename,age, subject marks (eng,math,phy), and a methodgetAvgto 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;
}
};
getAvgusesthisto correctly access the student's properties (this.eng,this.math,this.phy) to calculate the average marks.
Correcting the getAvg Method with 'this'
Using
thisensures 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 ofthis. Whenstudent.getAvg()is called,thisrefers to thestudentobject.
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
getAvgfunction showsthisreferring to theWindowobject 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
Windowobject represents the global scope in a browser, containing properties likewindow,document,location, and methods likealert,atob,btoa, etc.
console.log(window);
console.log(window.document);
console.log(window.location);
Try & Catch Block
trytests a block of code for errors, whilecatchhandles errors, preventing script termination.
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
}
Error Handling
Error handling with
try...catchprevents 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...catchhandling aReferenceErrorwhen logging an undefined variablea.
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
cubecalculates 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, andclearInterval(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
thisfrom their surrounding context (lexical scope), making it predictable.
Regular Functions:
thisis 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
thiscontext within astudentobject, showing howthisrefers 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
getNamemethod usesthisto access thenameproperty of the student object.
const student = {
name: 'Bob',
getName: function() {
console.log(this.name);
}
};
student.getName();
getMarks Method
getMarksmethod uses an arrow function, sothisrefers to the global scope, not the student object.
const student = {
name: 'Charlie',
getMarks: () => {
console.log(this);
}
};
student.getMarks();
getInfo1 and getInfo2 Methods
getInfo1uses an arrow function withinsetTimeout, sothisrefers to the student object.getInfo2uses a regular function withinsetTimeout, sothisrefers 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
arrayAverageto 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);