1/7
Flashcards covering key JavaScript concepts like 'this' keyword, arrow functions, try-catch, setTimeout, setInterval, and scope.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
This keyword
Refers to an object that is executing the current piece of code.
try and catch statement
try = to define a block of code to be tested for errors while it is being executed.
catch = to define a block of code to be executed, if an error occurs in the try block.
try {
console.log(a); // Trying to access an undefined variable
} catch (error) {
console.log('a is not defined'); // Handling the error
}
Arrow Functions
A concise way to write functions in JavaScript.
const func = (arg1, arg2, ...) => { function definition }
const sum = (a, b) => { console.log(a + b); }
const hello = () => { console.log("hello world"); }
setTimeout(function, timeout)
Executes a function once after a specified delay.
setTimeout(function() { console.log("This will be logged after 3 seconds");
}, 3000);
setInterval( function, timeout)
Executes a function repeatedly at specified intervals.
const intervalId = setInterval(function() {
console.log("This will be logged every 2 seconds");
}, 2000);
clearInterval( id)
Used to clear a timeout set by setTimeout().
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
this is inherited from the parent scope
this with Regular Functions
In a regular function, 'this' refers to the calling object.
const obj = {
value: 42,
regularFunction: function() {
console.log("Regular function: ", this.value);
},
arrowFunction: () => {
console.log("Arrow function: ", this.value);
} };
obj.regularFunction(); // Output: Regular function: 42 obj.arrowFunction(); // Output: Arrow function: undefined (or the value from the outer scope)