JavaScript - Intermediate Flashcards

1
Q

function declaration

A

In JavaScript, a function declaration is a statement that defines a named function.

It consists of the function keyword, followed by the function name, a list of parameters, and the function body enclosed in curly braces.

Function declarations are hoisted, meaning they can be called before they are defined in the code.

for example:

function add(a, b) {
return a + b;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

function expression

A

involves assigning a function to a variable or a constant.

It can be either anonymous or named.

Function expressions are not hoisted and must be defined before they are called.

For example:

// Function Expression (anonymous)
const multiply = function(a, b) {
return a * b;
};

// Function Expression (named)
const divide = function divide(a, b) {
return a / b;
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain the concept of scope and how it works in JavaScript?

A

Scope in JavaScript defines the visibility and accessibility of variables, functions, and objects in some particular part of the code during runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the different types of scope in JavaScript?

A

Function Scope

Global Scope

Local Scope

Block Scope

Lexical Scope

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Function Scope

A

Each function creates its own scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Global Scope

A

Variables declared outside of any function are considered global and can be accessed from anywhere in the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Local Scope

A

Variables declared within a function are considered local and can only be accessed within that function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the scope chain?

A

JavaScript follows a hierarchical structure called the scope chain.

When a variable is accessed, the JavaScript engine searches for the variable in the current scope.

If it doesn’t find the variable, it moves up the scope chain until it either finds the variable or reaches the global scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Block Scope

A

ES6 introduced block scope with the let and const keywords, allowing variables to be scoped to a specific block of code, such as within loops or conditional statements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does the “this” keyword behave in arrow functions compared to regular functions?

A

In arrow functions, the value of this is lexically scoped.

In other words, the this value in an arrow function is based on the surrounding scope where the arrow function is defined, rather than how it is called.

Arrow functions do not have their own this value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Lexical Scope

A

retains the value of the enclosing context

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When is it good to use arrow functions?

A

Arrow functions are especially useful when dealing with callbacks or when you need to preserve the value of this from the enclosing scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the different methods available for iterating over an object’s properties?

A

For … in

Object.keys()

Object.values()

Object.entries()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

For … in

A

It iterates over all enumerable properties of an object, including inherited ones.

for (let key in object) {
if (object.hasOwnProperty(key)) {
console.log(key, object[key]);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Object.keys()

A

t returns an array containing the enumerable properties of an object.

const keys = Object.keys(object);
keys.forEach(key => {
console.log(key, object[key]);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Object.values()

A

It returns an array containing the values of enumerable properties of an object.

const values = Object.values(object);
values.forEach(value => {
console.log(value);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Object.entries()

A

It returns an array containing the enumerable properties of an object as [key, value] pairs.

const entries = Object.entries(object);
entries.forEach(([key, value]) => {
console.log(key, value);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Explain the concept of the event loop in JavaScript and how it enables asynchronous behavior.

A

The event loop is a mechanism in JavaScript that allows the runtime environment to handle multiple events and tasks asynchronously.

It enables non-blocking behavior, preventing long-running operations from blocking the execution of other code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the implications of the single threaded nature of JavaScript when it comes to handling asynchronous operations such as AJAX calls?

A

When an asynchronous operation is initiated, it is offloaded to the browser’s APIs or other external mechanisms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does the event loop work?

A

The event loop continuously checks the call stack (the place where function calls are tracked) and the task queue (a queue of asynchronous tasks) for any pending tasks.

When the call stack is empty, the event loop picks the next task from the queue and pushes it onto the call stack, allowing it to be executed.

This process of checking the call stack, handling tasks, and pushing them onto the call stack is repeated indefinitely, allowing JavaScript to process multiple tasks and maintain responsive behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What’s the difference in error handling between Promises and async/await?

A

Promises use .catch()

asyncFunction()
.then(result => {
// Handle success
})
.catch(error => {
// Handle error
});

async/await wraps the awaiting function in a try and handles errors in the catch

try {
const result = await asyncFunction();
// Handle success
} catch (error) {
// Handle error
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are async/await and how do they simplify working with asynchronous code in JavaScript?

A

Async/await is a syntax introduced in ES2017 (ES8) that simplifies asynchronous programming in JavaScript.

It is built on top of promises and provides a more synchronous-like way to write and handle asynchronous code

Async/await allows you to write asynchronous code in a more sequential and readable manner, similar to synchronous code.

It avoids the need for explicit promise chaining using .then() and provides a natural error-handling mechanism using try…catch.

for example:

async function fetchData() {
try {
const response = await fetch(‘https://api.example.com/data’);
const data = await response.json();
return data;
} catch (error) {
console.log(‘Error:’, error);
}
}

fetchData();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does the await keyword do?

A

The await keyword waits for the promises to resolve before moving to the next line, resulting in cleaner and more understandable code for handling asynchronous operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are the different ways to copy an array or object in JavaScript?

A

Shallow copy with spread operator (…)

Shallow copy with Object.assign()

Deep copy with JSON.parse() and JSON.stringify()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Shallow copy with spread operator (…)

A

This method creates a new array or object and copies the enumerable properties or elements from the source to the new one.

It performs a shallow copy, meaning nested objects or arrays are still referenced.

const newArray = […oldArray];
const newObject = { …oldObject };

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Shallow copy with Object.assign()

A

Similar to the spread operator, Object.assign() creates a new object or array and copies the enumerable properties or elements from the source.

It also performs a shallow copy.

const newArray = Object.assign([], oldArray);
const newObject = Object.assign({}, oldObject);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Deep copy with JSON.parse() and JSON.stringify()

A

This method converts the array or object to a JSON string and then parses it back into a new array or object.

It creates a deep copy, meaning all nested objects or arrays are also copied.

const newArray = JSON.parse(JSON.stringify(oldArray));
const newObject = JSON.parse(JSON.stringify(oldObject));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Explain the concept of modules in JavaScript and how they help organize code?

A

Modules in JavaScript are a way to organize code into reusable and self-contained units.

They allow you to break down a large codebase into smaller, manageable pieces, each with its own functionality and scope.

Modules promote encapsulation, preventing the pollution of the global scope and reducing naming conflicts.

They enable code reusability, as modules can be imported and used in different parts of the application.

Modules also provide better maintainability and easier code navigation, as the codebase is divided into smaller and focused units.

29
Q

What do JavaScript modules typically consist of?

A

Export

Import

30
Q

What is a JS module Export?

A

The code or values that are exposed from the module to be used by other parts of the program.

These can be functions, objects, or variables.

31
Q

What is a JS module Import?

A

The mechanism used to bring exported values from other modules into the current module, making them available for use.

32
Q

How can modules be implemented?

A

Modules can be implemented using the CommonJS format (used in Node.js) or the ES modules format (used in modern JavaScript environments).

ES modules use the import and export keywords,

while CommonJS modules use require() and module.exports.

33
Q

What behavior does strict mode enforce?

A

Variables must be declared before use.

Assigning values to undeclared variables throws an error.

Assigning values to read-only properties or non-writable global variables throws an error.

Deleting variables, functions, or function arguments is not allowed.

Octal literals (e.g., 0123) are not allowed.

Duplicates in object literals are not allowed.

this inside functions is undefined in non-method functions.

The eval() function has its scope limited to the local scope.

The with statement is not allowed.

34
Q

What are higher-order functions in JavaScript?

A

Higher-order functions are functions that can take other functions as arguments or return functions as results.

They are a fundamental concept in functional programming and enable powerful functional composition and abstraction.

35
Q

What is an examples of a Higher Order Function in JavaScript?

A

map()

reduce()

forEach()

36
Q

Explain the concept of currying in JavaScript

A

Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument.

It allows you to partially apply a function by fixing some of its arguments, creating a new function that takes the remaining arguments.

Currying allows for more flexibility in function composition and enables the creation of specialized functions based on a common base function.

function add(x) {
return function(y) {
return x + y;
};
}

const addTwo = add(2);
console.log(addTwo(3)); // Output: 5

37
Q

What are generators in JavaScript and how do they differ from regular functions?

A

Generators are a special type of function in JavaScript that can be paused and resumed.

They are defined using the function* syntax and use the yield keyword to pause the function execution and return a value.

Generators are different from regular functions in that they can be exited and re-entered multiple times, preserving their internal state.

function* generateSequence() {
yield 1;
yield 2;
yield 3;
}

const generator = generateSequence();
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3

In the example above, the generateSequence function is a generator that yields a sequence of values.

Each time the generator.next() method is called, the generator resumes execution until it encounters a yield statement, which produces the value.

The generator can be paused and resumed to retrieve the next value.

38
Q

How does hoisting work with variables and functions in JavaScript?

A

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed.

This means that you can use variables and functions before they are declared in the code.

However, it’s important to note that only the declarations are hoisted, not the initializations or assignments.

Variables declared with var are hoisted and initialized with the value undefined, while function declarations are fully hoisted.

39
Q

Which JS functions return a new array?

A

map()

filter()

slice()

concat()

flat()

40
Q

Which JS functions modify an existing array?

A

push()

pop()

shift()

unshift()

splice()

sort()

reverse()

41
Q

What is the difference between “var”, “let”, and “const” in terms of scoping and hoisting?

A

var - has function scope and is hoisted to the top of its scope.

It can be redeclared and reassigned.

let and const - have block scope and are hoisted to the top of their block. They are not hoisted before their declaration and can’t be redeclared in the same scope.

let allows reassignment of the variable’s value.

const is a constant variable that can’t be reassigned after it has been assigned a value.

42
Q

What are the different methods available for manipulating arrays in JavaScript?

A

push()

pop()

shift()

unshift()

slice()

splice()

concat()

join()

indexOf()

includes()

forEach()

map()

filter()

reduce()

43
Q

push()

A

Adds one or more elements to the end of an array and returns the new length.

44
Q

pop()

A

Removes the last element from an array and returns that element.

45
Q

shift()

A

Removes the first element from an array and returns that element.

46
Q

unshift()

A

Adds one or more elements to the beginning of an array and returns the new length.

47
Q

slice()

A

Returns a new array containing a portion of the original array.

48
Q

splice()

A

Changes the content of an array by removing, replacing, or adding elements.

49
Q

concat()

A

: Returns a new array by concatenating two or more arrays.

50
Q

join()

A

Joins all elements of an array into a string.

51
Q

indexOf()

A

Returns the first index at which a specified element is found in an array.

52
Q

includes()

A

Checks if an array contains a specified element and returns a boolean.

53
Q

forEach()

A

Executes a provided function once for each array element.

54
Q

map()

A

Creates a new array by applying a function to each element of an array.

55
Q

filter()

A

Creates a new array with elements that pass a certain condition.

56
Q

reduce()

A

Applies a function to an accumulator and each element in the array to reduce it to a single value.

57
Q

debouncing

A

involves delaying the execution of a function and repeatedly resetting the delay timer whenever the function is called multiple times within a specified timeframe.

It ensures that the function is executed only after a certain period of inactivity.

58
Q

throttling

A

involves limiting the rate at which a function is executed.

It ensures that the function is executed at fixed intervals, ignoring any subsequent function calls that occur within the throttling interval.

59
Q

When would you decide to use debouncing or throttling?

A

They help improve performance and prevent unnecessary or excessive function invocations, especially in scenarios where events can occur rapidly or frequently.

They can be used to reduce resource consumption and improve the responsiveness of user interfaces.

60
Q

What’s an example of when to use debouncing?

A

It can be useful when handling user input in search fields, where you want to delay the search until the user pauses typing.

61
Q

What’s an example of when to use throttling?

A

It can be useful for functions tied to scrolling events, where you want to limit the rate at which the function is called to avoid overwhelming the system.

62
Q

What are the different ways to handle asynchronous flow control in JavaScript?

A

Callbacks

Promises

Async/await

Generators

63
Q

Callbacks

A

Functions are passed as arguments and called once the operation completes.

However, callback-based code can become difficult to manage when handling multiple asynchronous operations or dealing with error handling and control flow.

64
Q

Promises

A

Promises provide a more structured approach to handle asynchronous operations.

They represent a value that may not be available yet, allowing chaining of asynchronous operations and providing better error handling with the catch method. Promises can be resolved (fulfilled) or rejected, and the result can be accessed using the then method.

65
Q

How do you create and manipulate cookies using JavaScript?

A

To create or update a cookie, you can assign a string value to the document.cookie property in the format name=value.

You can also specify additional attributes such as expiration date, path, and domain.

document.cookie = ‘username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;’;

It’s important to note that the document.cookie property provides a simple interface for basic cookie operations. For more advanced cookie management, such as handling secure and HttpOnly cookies, it’s recommended to use specialized libraries or server-side implementations.

66
Q

Explain the concept of object destructuring in JavaScript?

A

Object destructuring is a JavaScript feature that allows you to extract properties from objects and bind them to variables.

It provides a concise way to access and use object properties.

For Example:

const person = { name: ‘John Doe’, age: 30, city: ‘New York’ };

// Destructuring assignment
const { name, age, city } = person;

console.log(name); // Output: John Doe
console.log(age); // Output: 30
console.log(city); // Output: New York

67
Q

How do you use destructuring to assign default values to variables?

A

const { name, age, city = ‘Unknown’ } = person;

console.log(city); // Output: Unknown

68
Q

what is IIFE?

A

IIFE stands for Immediately Invoked Function Expression. It is a JavaScript design pattern used to create a function that is executed immediately after it is defined.

Here’s an example of an IIFE:

(function() {
// Code enclosed within the IIFE
var message = ‘Hello, IIFE!’;
console.log(message);
})();

69
Q

Describe the functional scope of an IIFE?

A

The have their own function scope, which means any variables declared within the IIFE are not accessible from the outside.

This helps avoid polluting the global scope and prevents naming conflicts with other code.