JavaScript Concepts
Asynchronous Execution (2 questions):
What is the expected output of the following code snippet?
JavaScript
console.log("first");
setTimeout(() => { console.log("second"); }, 0);
console.log("third");
Explanation: The output will be "first", "third", "second". Even though setTimeout is called after "first", the callback function inside setTimeout is placed in the event queue and executed later.
Explain the difference between synchronous and asynchronous code execution.
Explanation: In synchronous execution, code runs line by line, and the program waits for each line to finish before moving on. Asynchronous execution allows the program to continue running other parts of the code while waiting for an asynchronous operation (like network requests) to complete.
Async/Await (2 questions):
What does the
asynckeyword do in JavaScript functions?
Explanation: The async keyword declares a function as asynchronous. It means the function always returns a Promise, even if you don't explicitly return one.
Provide a simple example of using
asyncandawaitto fetch data from an API.
JavaScript
async function fetchData() {
const response = await fetch('https://example.com/api/data');
const data = await response.json();
return data;
}
Explanation: This code defines an async function fetchData that fetches data from an API. await is used before fetch and response.json() to wait for the asynchronous operations to complete before continuing.
Promises and then() callback (2 questions):
What is the purpose of promises in JavaScript?
Explanation: Promises provide a way to handle asynchronous operations and represent the eventual completion (or failure) of an operation. They help avoid callback hell and improve code readability.
Explain the basic syntax of the
then()method with promises.
Explanation: The then() method is used with promises to define what happens when a promise resolves (completes successfully) or rejects (fails). It takes two optional callback functions: one for the resolved value and another for the error object in case of rejection.
JavaScript Basics (4 questions):
What are the different data types in JavaScript?
Explanation: JavaScript has various data types, including: - Numbers (integers, decimals) - Strings (text) - Booleans (true/false) - Objects (collections of key-value pairs) - Arrays (ordered lists of values) - undefined (variable declared but not assigned) - null (intentional absence of a value)
What is the difference between
var,let, andconstin JavaScript?
Explanation: These keywords are used for variable declaration. - var (mostly outdated): has global or function scope, can be re-declared and re-assigned. - let: has block scope (within curly braces), cannot be re-declared but can be re-assigned. - const: has block scope, cannot be re-declared or re-assigned.
What are functions in JavaScript, and how are they defined?
Explanation: Functions are reusable blocks of code that perform specific tasks. They are defined using the function keyword followed by the function name, parameters (optional), and the function body enclosed in curly braces.
What are control flow statements in JavaScript, and provide an example of each.
Explanation: Control flow statements control the flow of execution in a program. Examples include: - if statements: execute code based on a condition. - switch statements: execute different code blocks based on a matching case. - for loops: repeat code execution a certain number of times. - while loops: repeat code execution as long as a condition is true.
The Event Loop (2 questions):
What is the role of the event loop in JavaScript?
Explanation: The event loop is a core mechanism in JavaScript that manages asynchronous operations and ensures efficient execution. It continuously checks the call stack and message queue, processing events in a non-blocking manner.
Explain how the event loop handles asynchronous operations like
setTimeout.
The event loop in JavaScript manages asynchronous operations like setTimeout by utilizing callback queues. When a setTimeout is encountered, it schedules the callback after the specified time. The event loop continuously checks the call stack and processes the callback, ensuring non-blocking execution. Example:
console.log("Start");
setTimeout(function () {
console.log("Inside setTimeout callback");
}, 2000);
console.log("End");
In this example, "Inside setTimeout callback" is logged after a 2-second delay, demonstrating the event loop's handling of asynchronous operations.
JavaScript OOP:
What are the key concepts of Object-Oriented Programming (OOP) in JavaScript?
Explanation: Object-Oriented Programming in JavaScript revolves around the following key concepts:
1. Objects:
- Meaning: Objects are instances of classes and can encapsulate data and behavior.
- Example:
```javascript
let car = {
brand: 'Toyota',
model: 'Camry',
year: 2022,
start: function() {
console.log('Engine started!');
}
};
console.log(car.brand); // Output: Toyota
car.start(); // Output: Engine started!
```
2. Classes:
- Meaning: Classes are blueprints for creating objects. They define the properties and methods an object should have.
- Example:
```javascript
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
start() {
console.log('Engine started!');
}
}
let myCar = new Car('Toyota', 'Camry', 2022);
console.log(myCar.brand); // Output: Toyota
myCar.start(); // Output: Engine started!
```
3. Inheritance:
- Meaning: Inheritance allows a class to inherit properties and methods from another class.
- Example:
```javascript
class ElectricCar extends Car {
constructor(brand, model, year, batteryCapacity) {
super(brand, model, year);
this.batteryCapacity = batteryCapacity;
}
charge() {
console.log('Charging...');
}
}
let myElectricCar = new ElectricCar('Tesla', 'Model S', 2022, '100 kWh');
console.log(myElectricCar.brand); // Output: Tesla
myElectricCar.start(); // Output: Engine started!
myElectricCar.charge(); // Output: Charging...
```
4. Encapsulation:
- Meaning: Encapsulation is the bundling of data and methods that operate on the data within a single unit, i.e., a class.
- Example:
```javascript
class BankAccount {
constructor(accountNumber, balance) {
this.accountNumber = accountNumber;
this._balance = balance; // Using underscore convention to indicate private property
}
get balance() {
return this._balance;
}
deposit(amount) {
this._balance += amount;
}
withdraw(amount) {
if (amount <= this._balance) {
this._balance -= amount;
} else {
console.log('Insufficient funds.');
}
}
}
let myAccount = new BankAccount('123456789', 1000);
console.log(myAccount.balance); // Output: 1000
myAccount.withdraw(500); // Balance is now 500
```
5. Polymorphism:
- Meaning: Polymorphism allows objects of different types to be treated as objects of a common type.
- Example:
```javascript
class Shape {
area() {
// To be overridden by subclasses
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let circle = new Circle(5);
let rectangle = new Rectangle(4, 6);
console.log(circle.area()); // Output: 78.54 (approximately)
console.log(rectangle.area()); // Output: 24
```
These examples illustrate the application of Object-Oriented Programming principles in JavaScript. OOP provides a way to structure code in a more modular and organized manner, enhancing code reuse and maintainability.