Javascript Concepts 📚
I've compiled down all the popular concepts and questions related to a Javascript Interview. No matter at what level of understanding you're currently at, this will help you out.
Table of content
- Closures
- Promises and Asynchronous
- Async/Await
- Event Loop
- Hoisting, Scope, and Execution Context
- Prototypes and Inheritance
- Event delegation
- Debouncing and Throttling
- Higher order Functions (Map, Filter, Reduce)
- Error Handling
1. Closures
Closures allow functions to access variables from their outer scope, even after the outer function has executed. This is often used to create private variables.
1function outerFunction() {
2 let counter = 0;
3 return function innerFunction() {
4 counter++;
5 return counter;
6 };
7}
8const increment = outerFunction();
9console.log(increment()); // 1
10console.log(increment()); // 2
11
2. Promises and Asynchronous
Promises are used to handle asynchronous operations in JavaScript, allowing you to write cleaner and more readable code.
1const fetchData = () => {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => resolve('Data fetched!'), 1000);
4 });
5};
6
7fetchData().then(data => console.log(data));
8
3. Async/Await
Async/Await is a cleaner way to handle asynchronous code compared to Promises.
1async function fetchData() {
2 const data = await new Promise(resolve => setTimeout(() => resolve('Data fetched!'), 1000));
3 console.log(data);
4}
5fetchData();
6
4. Event Loop and Callbacks
The event loop handles asynchronous operations by processing tasks from the callback queue.
1console.log('Start');
2setTimeout(() => console.log('Async Call'), 0);
3console.log('End');
4// Output: Start, End, Async Call
5
5. Hoisting, Scope, and Execution Context
Variables and functions are "hoisted" to the top of their scope. Understanding scope and execution context is key to avoiding bugs.
1console.log(a); // undefined (hoisting)
2var a = 5;
3
4function scopeDemo() {
5 let b = 10; // Block-scoped
6 console.log(b);
7}
8scopeDemo();
9
6. Prototypes and Inheritance
Prototypes enable inheritance in JavaScript, allowing objects to share methods and properties.
1function Person(name) {
2 this.name = name;
3}
4Person.prototype.greet = function() {
5 console.log(Hello);
6};
7
8const person = new Person('Alice');
9person.greet(); // Hello, Alice
10
7. Event Delegation
Event delegation uses a single event listener for multiple child elements, improving performance.
1document.getElementById('parent').addEventListener('click', (event) => {
2 if (event.target.tagName === 'BUTTON') {
3 console.log('Button clicked:', event.target.textContent);
4 }
5});
6
8. Debouncing and Throttling
Debouncing: Delays execution until after a specified time has elapsed.
1function debounce(func, delay) {
2 let timer;
3 return function(...args) {
4 clearTimeout(timer);
5 timer = setTimeout(() => func.apply(this, args), delay);
6 };
7}
8
Throttling: Ensures a function is called at most once in a specified interval.
1function throttle(func, limit) {
2 let lastFunc;
3 let lastRan;
4 return function(...args) {
5 const context = this;
6 if (!lastRan) {
7 func.apply(context, args);
8 lastRan = Date.now();
9 } else {
10 clearTimeout(lastFunc);
11 lastFunc = setTimeout(() => {
12 if (Date.now() - lastRan >= limit) {
13 func.apply(context, args);
14 lastRan = Date.now();
15 }
16 }, limit - (Date.now() - lastRan));
17 }
18 };
19}
20
9. Higher-order Functions
Higher-order functions like map, filter, and reduce simplify array manipulation and functional programming.
1const numbers = [1, 2, 3, 4];
2const doubled = numbers.map(num => num * 2);
3const evens = numbers.filter(num => num % 2 === 0);
4const sum = numbers.reduce((total, num) => total + num, 0);
5console.log(doubled, evens, sum);
6
10. Error Handling
Handle errors gracefully using try-catch blocks to ensure your code doesn't crash unexpectedly.
1try {
2 throw new Error('Something went wrong!');
3} catch (error) {
4 console.error(error.message);
5}
6