JavaScript Crash Course Flashcards

1
Q

What are the JS primitive types?

A

Number
BigInt
Boolean
String
Symbol
Null
Undefined

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

What are the most common uses for the Math object in everyday JavaScript development?

A
  1. Rounding Numbers:
    • Math.round(): Rounds numbers to the nearest integer.
  2. Rounding Down or Up:
    • Math.floor(): Rounds a number downward to the nearest integer.
    • Math.ceil(): Rounds a number upward to the nearest integer.
  3. Generating Random Numbers:
    • Math.random(): Generates a random number between 0
      (inclusive) and 1 (exclusive).
  4. Finding Maximum or Minimum:
    • Math.max(): Returns the largest of given numbers.
    • Math.min(): Returns the smallest of given numbers.
  5. Absolute Value:
    • Math.abs(): Returns the absolute (non-negative) value of a
      number.
  6. Exponentiation:
    • Math.pow(): Returns the base raised to the power of the exponent.
  7. Square Root:
    • Math.sqrt(): Returns the square root of a number.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is parseInt() in JavaScript, and how is it used?

A

It is used to parse a string and return an integer.
Note the string must begin with the number or have leading space. If it begins with a non numeric character it will return NaN.

parseFloat works the same way except it ignores the first ‘.’, so that it may return a floating number.

parseInt("23.5px") // 23
parseFloat("23.5px") // 23.5

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

What is the alert() function in JavaScript and how is it used?

A

The alert() function in JavaScript is used to display a popup alert with a specified message. For example, using alert("Hello, World!"); will show a popup with the message “Hello, World!”.

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

What is the console.log() function in JavaScript and how is it used?

A

The console.log() function in JavaScript is used to output a message to the web console. For instance, if you use console.log("This is a log message.");, it will print “This is a log message.” in the web console.

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

What is the .push() method in JavaScript and how is it used?

A

The .push() method in JavaScript adds one or more elements to the end of an array. For example, if you have an array fruits and you use fruits.push("apple"), “apple” will be added to the end of the fruits array.

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

What is the .pop() method in JavaScript and how is it used?

A

The .pop() method in JavaScript removes the last element from an array. If you have an array fruits with the last element as “apple”, using fruits.pop() will remove “apple” from the array

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

What is the .shift()method in JavaScript and how is it used?

A

The .shift() method in JavaScript removes the first element from an array. For instance, if “apple” is the first element in the fruits array, using fruits.shift() will remove “apple” from the array.

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

What is the .unshift() method in JavaScript and how is it used?

A

The .unshift() method in JavaScript adds one or more elements to the beginning of an array. For example, using fruits.unshift("apple") will add “apple” to the beginning of the fruits array.

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

What is the .map() method in JavaScript and how is it used?

A

The .map() method in JavaScript creates a new array by calling a function on every array element. For instance, if you want to double every number in an array numbers, you can use
numbers.map(x => x * 2)

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

What is the .filter() method in JavaScript and how is it used?

A

The .filter() method in JavaScript creates a new array with every element that passes a test. For example, to get only numbers less than 10 from an array numbers, you can use
const arr = [10, 13, 8, 6, 9]; const newArr = arr.filter((e) => { return e < 10; }) returns: [8, 6, 9]

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

What is the .every() method in JavaScript and how is it used?

A

The .every() method returns a boolean that indicates if all the elements in an array pass a certain test. For example:
const arr = [1, 2, 5, 125, 6] const allPass = arr.every((e) => { return e < 100; } returns false because there is a value that is 100 or more in the array.

note: the .some() method will check if any value passes

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

What is the .reduce() method in JavaScript and how is it used?

A

The .reduce() method in JavaScript reduces an array to a single value. For instance, to sum all numbers in an array numbers, you can use `numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
})’

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

What is the .forEach() method in JavaScript and how is it used?

A

The .forEach() method in JavaScript calls a function once for each array element. For example, to log every element in an array fruits, you can use fruits.forEach(fruit => console.log(fruit))

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

What is the .find() method in JavaScript and how is it used?

A

The .find() method in JavaScript returns the value of the first array element that passes a test.
const arr = [10, 13, 8, 6, 9]; const newArr = arr.find((e) => { return e < 10; }) returns: 8

note: findIndex() will return the index of the found value instead of the value itself.

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

What is the .trim() method in JavaScript and how is it used?

A

The .trim() method removes whitespace from both ends of a string. For example, " apple ".trim() would return “apple”.

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

What is the .sort() method in JavaScript and how is it used?

A

The .sort() method in JavaScript sorts the elements of an array. For example, to sort an array fruits in alphabetical order, you can use fruits.sort().

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

What is the .charAt() method in JavaScript and how is it used?

A

The .charAt() method returns the character at a specified index in a string. For example, "apple".charAt(3)would return “l”.

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

What is the .indexOf() method in JavaScript and how is it used?

A

The .indexOf() method returns the position of the first occurrence of a substring in a string. For instance, "apple".indexOf("p") would return 1.

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

What is the .slice() method in JavaScript and how is it used?

A

The .slice() method extracts a part of a string and returns a new string. For example, "apple".slice(1, 4) would return “ppl”.

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

What is the .split() method in JavaScript and how is it used?

A

The .split() method splits a string into an array of substrings based on a specified delimiter. For instance, "apple,orange".split(",") would return [“apple”, “orange”].

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

What is the .replace() method in JavaScript and how is it used?

A

The .replace() method replaces a specified value with another value in a string. For instance, "apple".replace("a", "o") would return “opple”.

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

What is the .toUpperCase() method in JavaScript and how is it used?

A

The .toUpperCase() method converts a string to uppercase letters. For example, "apple".toUpperCase() would return “APPLE”.

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

What is the .toLowerCase()method in JavaScript and how is it used?

A

The .toLowerCase() method converts a string to lowercase letters. For instance, "APPLE".toLowerCase() would return “apple”.

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

What is the .substr() method in JavaScript and how is it used?

A

The .substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. For example, "apple".substr(1, 3) would return “ppl”.

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

What is the .concat() method in JavaScript and how is it used?

A

The .concat() method is used to join two or more strings. For instance, "apple".concat(" pie") would return “apple pie”.

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

What is the .startsWith() method in JavaScript and how is it used?

A

The .startsWith() method determines whether a string begins with the characters of a specified string. For example, "apple".startsWith("app") would return true.

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

What is the .endsWith() method in JavaScript and how is it used?

A

The .endsWith() method determines whether a string ends with the characters of a specified string. For example, "apple".endsWith("le") would return true.

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

What is the .includes() method in JavaScript and how is it used?

A

The .includes() method determines whether one string may be found within another string. For instance, "apple".includes("pp") would return true.

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

What is the .repeat() method in JavaScript and how is it used?

A

The .repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called. For example, "apple".repeat(2) would return “appleapple”.

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

What is the .search() method in JavaScript and how is it used?

A

The .search() method executes a search for a match between a regular expression and this string. It returns the index of the match, or -1 if not found. For instance, "apple pie".search(/pie/) would return 6.

32
Q

What is the .match() method in JavaScript and how is it used?

A

The .match() method retrieves the result of matching a string against a regular expression. For example, "apple pie and cherry pie".match(/pie/g) would return [“pie”, “pie”].

33
Q

What is the .padStart() method in JavaScript and how is it used?

A

The .padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. For instance, "7".padStart(3, "0") would return “007”.

34
Q

What is the .padEnd() method in JavaScript and how is it used?

A

The .padEnd() method pads the current string with a given string (multiple times, if needed) until the resulting string reaches the given length. For example, "apple".padEnd(8, "!") would return “apple!!!”.

35
Q

What is the JSON.stringify() method in JavaScript and how is it used?

A

The JSON.stringify() method converts a JavaScript object or value to a JSON string. It’s commonly used when sending data to a server or when saving data in a string format. For example, given the object const obj = {
name: “John”, age: 30,
};
JSON.stringify(obj) would return ‘{“name”:”John”,”age”:30}’.

36
Q

What is a ternary operator in JavaScript and how is it used?

A

The ternary operator is a shorthand way of writing an if-else statement. It’s composed of three parts: a condition, a result for a true condition, and a result for a false condition. The syntax is: condition ? valueIfTrue : valueIfFalse. For example, let result = (age >= 18) ? "Adult" : "Minor"; assigns “Adult” to result if age is 18 or more, and “Minor” otherwise.

37
Q

What are console.time() and console.timeEnd() in JavaScript and how are they used together?

A

console.time() and console.timeEnd() are methods used to measure the time taken for a particular block of code to execute. console.time(label) starts a timer with a specified label, and console.timeEnd(label) stops the timer with the same label, logging the elapsed time to the console.

38
Q

How to instantiate an array with 5 0s?

A

const arr = new Array(5).fill(0);
console.log(arr); // [0, 0, 0, 0, 0]

39
Q

Describe the splice() method in JavaScript and provide examples of its usage.

A

The splice()method changes the contents of an array by removing, replacing, or adding elements. It modifies the original array and returns an array containing the deleted elements.

Syntax:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Examples:

Removing elements:
Given the array [‘apple’, ‘banana’, ‘cherry’, ‘date’], using splice(1, 2) removes ‘banana’ and ‘cherry’, resulting in the array [‘apple’, ‘date’].

Adding elements:
Given the array [1, 2, 4, 5], using splice(2, 0, 3) inserts the number 3 at index 2, resulting in the array [1, 2, 3, 4, 5].

Replacing elements:
Given the array [‘red’, ‘green’, ‘blue’], using splice(1, 1, ‘yellow’) replaces ‘green’ with ‘yellow’, resulting in the array [‘red’, ‘yellow’, ‘blue’].

Removing elements from the end:
Given the array [‘cat’, ‘dog’, ‘elephant’, ‘fox’], using splice(-2, 2) removes ‘elephant’ and ‘fox’, resulting in the array [‘cat’, ‘dog’].

Adding and removing elements:
Given the array [‘a’, ‘c’, ‘d’, ‘e’], using splice(1, 2, ‘b’) removes ‘c’ and ‘d’, then inserts ‘b’ at index 1, resulting in the array [‘a’, ‘b’, ‘e’].

Note: The splice() method modifies the original array.

40
Q

Describe the join() method in JavaScript.

A

The join() method in JavaScript is used to join the elements of an array into a string. The elements are separated by a specified separator (defaults to a comma).

Syntax:
array.join([separator])

Examples:

[‘a’, ‘b’, ‘c’].join() results in the string ‘a,b,c’.
[‘a’, ‘b’, ‘c’].join(‘ - ‘) results in the string ‘a - b - c’.

41
Q

Describe the reverse() method in JavaScript.

A

The reverse() method in JavaScript is used to reverse the order of the elements in an array. It modifies the original array and returns a reference to the same array after it has been reversed.

42
Q

Describe the for…of loop in JavaScript.

A

Syntax:
for (const value of iterable) {
// execute code for each value
}

note: for in will iterate over the key instead of the value like for of.

43
Q

Callback Functions in JavaScript

A

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function. Callbacks can be used in various contexts in JavaScript, and their execution timing can differ based on the context.

Immediate Execution: Methods like forEach, map, and filter execute the callback immediately for each element in the array.

Example: arr.forEach(function(item) { console.log(item); });
Deferred Execution: Callbacks in asynchronous operations, such as event listeners or timers, are executed later.

Event Listener: button.addEventListener(‘click’, function() { console.log(‘Clicked!’); });
Timer: setTimeout(function() { console.log(‘2 seconds passed!’); }, 2000);
The primary purpose of callbacks is to allow for flexibility and reusability in code, as well as handling asynchronous operations.

44
Q

What is the purpose of an object?

A

To store key value pairs

45
Q

What is the shorthand for declaring and object based on variables that already exist?

A

const firstName = ‘Jeremy’
const lastName= ‘Krans’
const obj = {
firstName,
lastName,
}

obj.firstName would return 'jeremy'

46
Q

What is an object constructor in JavaScript and how is it defined?

A

An object constructor in JavaScript is a blueprint for creating multiple objects with the same properties and methods. It’s essentially a function that sets up new objects.

Example:
`function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.drive = function() {
console.log(this.model + “ is driving!”);
};
}

const myCar = new Car(“Toyota”, “Camry”, 2020);
myCar.drive(); // Outputs: “Camry is driving!”`

47
Q

Difference between hasOwnProperty and in when checking properties in an object.

A

hasOwnProperty:

Checks if the object itself has the specified property as its own property.

Example: obj.hasOwnProperty('name') returns true only if name is a direct property of obj.

in:

Checks if the object has the specified property either as its own or somewhere in its prototype chain.

Example: 'name' in obj returns true if name is a property of obj or any of its prototypes. toString would return true for example.

In short, hasOwnProperty is stricter, checking only the object itself, while in checks the entire prototype chain.

48
Q

What is the syntax for a function inside an object?

A

const obj = {
name: ‘Jeremy’,
sayHello() { console.log('hello " + name) },
}

49
Q

How does object inheritance work with JavaScript?

A

const obj1 = {
name: ‘jeremy’,
}

const obj2 = {
\_\_proto\_\_: obj1
}

50
Q

What is destructuring assignment syntax?

A

Array:
const arr = [5, 20, 30, 40, 60];
const [a, b, ...rest] = arr;

console.log(a);
// Output: 10

console.log(b);
// Output: 20

console.log(rest);
// Output: Array [30, 40, 50]

Object:

const obj = {
name: ‘Emerson’,
age: 2,
}

const {name, age} = obj;

console.log(name, age);
// Output: Emerson 2

51
Q

Spread Syntax in JavaScript:

A

Definition: Allows an iterable (like an array) to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
Syntax: …iterable

Merging Array:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

Function arguments:
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

Cloning arrays:
const original = [1, 2, 3];
const copy = [...original]; // Creates a shallow copy of the original array.

52
Q

Describe the nullish coalescing operator (??) and give an example:

A

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

let name = “Jack”;

const name1 = name ?? 'default value';

console.log(name1); // result: Jack

// if name was null or undefined: result: default value

53
Q

Optional Chaining in JavaScript

A

const user = {
profile: {
name: ‘John’,
address: {
city: ‘New York’
}
}
};

to safely access city you can use:

const city = user?.profile?.address?.city; // Returns ‘New York’

If any part of the chain is null or undefined, it will return undefined without throwing an error.

54
Q

Using .classList with javascript

A

The .classList property provides methods to manipulate the class list of an element. It’s a more versatile and readable alternative to using .className.

Methods include:

add: Adds a class to an element.
Example: element.classList.add(‘active’);

remove: Removes a class from an element.
Example: element.classList.remove(‘active’)`;

toggle: Toggles a class on an element. If the class exists, it’s removed; if it doesn’t, it’s added.
Example: element.classList.toggle(‘active’);

contains: Checks if an element has a specific class.
Example:
if (element.classList.contains(‘active’)) {
// Do something
}

replace:Replaces an old class with a new one.
Example: element.classList.replace(‘oldClass’, ‘newClass’);

Using .classList makes it easier to work with individual classes without affecting other classes on the same element.

55
Q

What are querySelector and querySelectorAll in JavaScript?

A

querySelector: A method that returns the first element within the document that matches the specified selector or group of selectors. If no matches are found, it returns null.

Syntax: element.querySelector(selectors)
Example: document.querySelector('.myClass') returns the first element with the class myClass.
querySelectorAll: A method that returns a NodeList representing a list of elements in the document that match the specified group of selectors. The NodeList is a static (not live) collection.

Syntax: element.querySelectorAll(selectors)
Example: document.querySelectorAll('.myClass') returns all elements with the class myClass.

Note: While querySelector returns a single element, querySelectorAll returns a NodeList, even if only one match is found.

56
Q

Using addEventListener in JavaScript and common events.

A

Add an event listener:
element.addEventListener('eventName', callbackFunction);
Attaches an event handler to the specified element.
Common Events:

Click:
element.addEventListener('click', function() { /* ... */ });
Fired when the element is clicked.

Mouseover:
element.addEventListener('mouseover', function() { /* ... */ });
Fired when the mouse pointer enters the element.

Mouseout:
element.addEventListener('mouseout', function() { /* ... */ });
Fired when the mouse pointer leaves the element.

Change:
element.addEventListener('change', function() { /* ... */ });
Used mainly on input elements, it fires when the value changes.

Submit:
element.addEventListener('submit', function() { /* ... */ });
Fired when a form is submitted.

Keydown:
element.addEventListener('keydown', function() { /* ... */ });
Fired when a key is pressed down.

Keyup:
element.addEventListener('keyup', function() { /* ... */ });
Fired when a key is released.

Note: Always remember to remove event listeners when they’re no longer needed to prevent memory leaks, especially when using anonymous functions.

57
Q

What is a Promise in JavaScript?

A

A Promise is a JavaScript object representing the eventual completion or failure of an asynchronous operation. It has three states:

  1. Pending: Initial state; neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully.
  3. Rejected: The operation failed.
    A Promise is said to be “settled” if it’s either fulfilled or rejected.

You can attach callbacks to a Promise using its .then() method for fulfillment and .catch() method for rejection.

Example:
const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Data fetched successfully!'); // or // reject('Error fetching data.'); }, 2000); });

promise.then(data => console.log(data)).catch(error => console.error(error));

58
Q

What is async/await in JavaScript?

A

async/await is syntactic sugar built on top of Promises, introduced in ES2017, to make asynchronous code look and behave more like synchronous code.

An async function always returns a promise.
The await keyword can only be used inside an async function and makes JavaScript wait until that promise settles and returns its result.
Example:

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

fetchData();

In the example, the fetchData function is marked as async, and inside it, the await keyword makes the function execution wait for fetch to complete before moving on to the next line.

59
Q

Fetch API in JavaScript: Working with the server

A

The fetch API provides a modern way to make network requests in JavaScript. It returns a Promise that resolves with the Response object representing the response to the request.

Basic Usage:
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

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

Key Points:

The fetch function starts a request and returns a Promise.
To extract the JSON body content from the response, use response.json().
Always handle potential network errors and rejections by chaining .catch() or using a try/catch block with async/await.
The fetch API can be customized with options like method (GET, POST, etc.), headers, body content, and more.

60
Q

setInterval and setTimeout in JavaScript

A

Both setInterval and setTimeout are built-in JavaScript functions that allow you to execute code after a specified period of time, but they work in slightly different ways.

setTimeout:

Executes a function or specified piece of code once after a specified number of milliseconds.
Returns a timeout ID that can be used with clearTimeout() to cancel the timeout.

const timerId = setTimeout(() => { console.log('This runs after 2 seconds'); }, 2000);

// To cancel the timeout:
clearTimeout(timerId);

setInterval:

Repeatedly calls a function or executes a code snippet with a fixed time delay between each call.
Returns an interval ID that can be used with clearInterval() to cancel the repeated action.

const intervalId = setInterval(() => { console.log('This runs every 2 seconds'); }, 2000);

// To stop the interval:
clearInterval(intervalId);

Key Points:
Both functions use time in milliseconds.
Always clear intervals and timeouts if they’re no longer needed to prevent unintended behaviors and potential memory leaks.

61
Q

this keyword in javascript

A

In JavaScript, the this keyword refers to the object it belongs to. Its value can be different depending on where and how it’s used:

Global Context: Outside of any function, this refers to the global object. In browsers, it’s the window object.

console.log(this === window); // true
Inside a Function: The value of this depends on how the function is called.

Regular function call: this is the global object (or undefined in strict mode).

Method call: this is the object that the method belongs to.

Inside an Arrow Function: Arrow functions don’t have their own this. They inherit it from the enclosing function or context.

Inside an Event Handler: this refers to the element that received the event.

Constructor Function: When a function is used as a constructor (with the new keyword), this refers to the newly created instance.

Using call(), apply(), and bind(): These methods can be used to set a specific object as this for a function.

Remember, the value of this is determined at the time of the function’s invocation, making it a dynamic context rather than a static one.

62
Q

Prototypal inheritance in JavaScript

A

Prototypal inheritance allows an object to inherit properties and methods from another object’s prototype.

Example using function constructors:

// Animal constructor
function Animal(name, domesticated) {
this.name = name;
this.domesticated = domesticated;
}

// Method added to Animal’s prototype
Animal.prototype.speak = function() {
console.log(${this.name} makes a noise.);
};

// Dog constructor
function Dog(name, domesticated) {
Animal.call(this, name, domesticated); // Inherit properties
}

// Inherit methods
Dog.prototype = Object.create(Animal.prototype);

// Create a new Dog instance
const dog = new Dog(‘Rex’, true);
dog.speak(); // Output: “Rex makes a noise.”
console.log(dog.domesticated); // Output: true
Key Points:

Animal.call(this, name, domesticated); is used for property inheritance.
Dog.prototype = Object.create(Animal.prototype); is used for method inheritance.

63
Q

What are private and static fields in JavaScript classes, and how are they used?

A

Private Fields: Fields that are only accessible within the class. They are prefixed with a # symbol.

class MyClass {
#privateField = 'I am private';
}

Accessing #privateField outside the class will throw an error.

Static Fields: Fields that are shared across all instances of the class, and are also accessible on the class itself.

class MyClass {
static staticField = 'I am static';
}

Access using MyClass.staticField.

Example:

class Animal {
#type = 'Mammal';
static planet = 'Earth';

constructor(name) {
this.name = name;
}

getType() {
return this.#type;
}
}

const dog = new Animal(‘Rex’);
console.log(dog.getType()); // Output: ‘Mammal’
console.log(Animal.planet); // Output: ‘Earth’

64
Q

Curried Functions in JavaScript

A

Definition: A curried function is a function that takes multiple arguments one at a time. It returns a new function that expects the next argument until all arguments are provided.

Syntax:
function add(a) { return function(b) { return a + b; }; }

Usage with Arrow Functions:
const add = a => b => a + b;

Example 1: Basic Usage
const addFive = add(5);
const result = addFive(3); // Output: 8

Example 2: Multiple Arguments

const multiply = a => b => c => a * b * c;
const multiplyBy2 = multiply(2);
const multiplyBy2And3 = multiplyBy2(3);
const result = multiplyBy2And3(4); // Output: 24

Example 3: Using with Function Invocation
const result = add(5)(3); // Output: 8

Advantages:
Partial application of functions.
Improved code reusability and composition.

Note: Currying is particularly useful in functional programming paradigms and helps in creating more modular and maintainable code.

65
Q

Generators in JavaScript

A

Definition: A generator is a special type of function that can be paused and resumed, allowing it to yield multiple values over time. Generators are useful for tasks that require state management, like iterating over a collection one item at a time.

Syntax:

function* generatorFunction() { yield 'value1'; yield 'value2'; // ... }

Usage:

Creating a Generator Object:

const generatorObject = generatorFunction();
Iterating through Values

console.log(generatorObject.next()); // Output: { value: ‘value1’, done: false }
console.log(generatorObject.next()); // Output: { value: ‘value2’, done: false }
console.log(generatorObject.next()); // Output: { value: undefined, done: true }

Using for…of Loop

for (const value of generatorFunction()) {
console.log(value); // Output: ‘value1’, ‘value2’
}

Passing Values

function* add(a) { const b = yield a; return a + b; }

const addGenerator = add(5);
console.log(addGenerator.next()); // Output: { value: 5, done: false }
console.log(addGenerator.next(3)); // Output: { value: 8, done: true }

Advantages:

Lazy evaluation, which can lead to performance improvements.
Simplifies the use of iterators and the creation of custom iterators.
Useful for asynchronous programming patterns.
Note: Generators are often used in scenarios like lazy data streams, asynchronous programming, and managing stateful computations.

66
Q

What are JavaScript Modules and how do you use them?

A

JavaScript Modules allow you to split your code into reusable pieces that can be imported and exported from one file to another. This enhances code maintainability, reusability, and namespace management.

Syntax:

Exporting a Module

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
or
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
export { add, subtract };

Importing a Module
// app.js
import { add, subtract } from ‘./math.js’;
or
// app.js
import * as mathFunctions from ‘./math.js’;

Features:

Default Exports: You can have one default export per module.

// default.js
export default function() { console.log(‘hello’); }

// app.js
import greet from ‘./default.js’;

Dynamic Imports: You can dynamically import modules using import() function.

// Dynamic import
import('./math.js').then(module => { console.log(module.add(1, 2)); });

Static Analysis: Modules are statically analyzed, meaning tools can determine imports and exports at compile time (as opposed to runtime).

Note: Modules are always in strict mode and have their own top-level scope, not the global scope.

67
Q

What is the Event Loop in JavaScript and how do Promises and Async Functions fit into it?

A

Event Loop: The mechanism that handles executing multiple chunks of your program over time, each time invoking the JavaScript engine.

Callback Queue: A queue storing all the callbacks that are ready to be executed. Events like setTimeout, setInterval, and DOM events are placed here.

Promise Jobs Queue (Micro-task Queue): A separate queue with higher priority than the Callback Queue. It stores the .then() and .catch() callbacks of resolved or rejected Promises.

Async Functions: These functions return a Promise implicitly. When called, they release control back to the Event Loop immediately and resume when awaited Promises are resolved.

How it works:

The Event Loop constantly checks the Call Stack to see if it’s empty.
If it’s empty, it looks into the Promise Jobs Queue first. If there are any callbacks, they are run immediately.
If the Promise Jobs Queue is empty, it moves to the Callback Queue and starts executing callbacks based on their order.
Example:

`console.log(‘Start’);

setTimeout(() => {
console.log(‘Timeout’);
}, 0);

Promise.resolve().then(() => {
console.log(‘Promise’);
});

console.log(‘End’);
Output:

Start
End
Promise
Timeout`

In this example, the Promise’s .then() executes before the setTimeout because Promise Jobs Queue has higher priority.

68
Q

What are Web Workers and how do they work in JavaScript?

A

Definition: Web Workers are a simple means for web content to run scripts in background threads. They allow for long-running scripts that are not interrupted by scripts that refresh the page.

Main Thread: JavaScript is single-threaded. Web Workers run in a separate thread, allowing complex operations without blocking the UI.

Communication: Web Workers communicate with the main thread using a system of messages — both sides send their messages using the postMessage method, and respond to messages via the onmessage event handler.

Limitations: Web Workers do not have access to the DOM or the global window object. They run in a restricted environment in a separate scope.

Types: There are different types of workers like Dedicated Workers, Shared Workers, and Service Workers serving different purposes.

Example:

// main.js
const worker = new Worker('worker.js');

worker.postMessage(‘Hello, Worker’);

worker.onmessage = function(event) {
console.log(‘Received message ‘ + event.data);
}

// worker.js
self.onmessage = function(event) {
console.log(‘Received message ‘ + event.data);
self.postMessage(‘Hello, Main’);
}
Usage:

Web Workers are ideal for tasks like image manipulation, data fetching, and other tasks that require heavy computation or asynchronous operations.

69
Q

What are cookies?

A

Definition: Cookies are small pieces of data stored on the user’s computer by the web browser while browsing a website.

Purpose: Mainly used for session management, tracking user activity, and storing user preferences.

Creation: Created by the server and sent to the client’s browser, which stores it for a specified period.

Syntax:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

Reading Cookies:
var x = document.cookie;

Secure Cookies:
document.cookie = “username=John; Secure”;

HttpOnly Cookies: Cannot be accessed through client-side scripts, only sent to the server.

SameSite Attribute: Controls whether cookies are sent along with cross-site requests.

Expiration: Cookies can have an expiration date, after which they are deleted.

Limitations: Size is limited to about 4KB and a domain can only have a limited number of cookies.

Remember, cookies are subject to various security concerns like CSRF attacks, so they should be used carefully and securely.

70
Q

What is Local Storage in the Web Storage API?

A

Definition: Local Storage is a web storage solution that allows JavaScript sites and apps to store key-value pairs in a web browser with no expiration time.

Purpose: Mainly used for storing data that doesn’t require server-side rendering, like user preferences or form data.

Storage Limit: Typically up to 5-10 MB per domain, depending on the browser.

Syntax for Storing Data:
localStorage.setItem('key', 'value');

Syntax for Retrieving Data:
const value = localStorage.getItem('key');

Syntax for Removing Data:
localStorage.removeItem('key');

Syntax for Clearing All Data:
localStorage.clear();

Event: The storage event is fired when the storage area changes, except when the change is caused by the same document that originated it.

Security: Data is saved across browser sessions and is accessible from any window from the same origin, but it’s not encrypted. Therefore, sensitive information should not be stored in Local Storage.

Cross-origin: Local Storage is origin-specific, meaning data stored will only be available on the same origin.

Note: Local Storage should not be used for sensitive information as it’s vulnerable to XSS attacks. It’s a synchronous API and could potentially block the main thread. Use it for non-critical data and always validate and sanitize the data.

71
Q

What is Session Storage in the Web Storage API?

A

Definition: Session Storage is a web storage solution that allows JavaScript sites and apps to store key-value pairs in a web browser for the duration of a page session.

Purpose: Useful for storing temporary data like form inputs, or for persisting data across multiple pages during a single browsing session.

Storage Limit: Typically up to 5-10 MB per domain, depending on the browser.

Session Duration: Data is only available for the duration of the page session. If the browser or tab is closed, the data is deleted.

Syntax for Storing Data:
sessionStorage.setItem('key', 'value');

Syntax for Retrieving Data:
const value = sessionStorage.getItem('key');

Syntax for Removing Data:
sessionStorage.removeItem('key');

Syntax for Clearing All Data:
sessionStorage.clear();

Event: The storage event is fired when the storage area changes, except when the change is caused by the same document that originated it.

Security: Data is saved only for a session and is accessible from any window from the same origin, but it’s not encrypted. Therefore, sensitive information should not be stored in Session Storage.

Cross-origin: Session Storage is origin-specific, meaning data stored will only be available on the same origin.

Note: Session Storage is similar to Local Storage but has a shorter lifecycle. It’s also vulnerable to XSS attacks, so don’t store sensitive information. Always validate and sanitize the data.

72
Q

What is IndexedDB in the Web Storage API?

A

Definition: IndexedDB is a low-level, NoSQL storage solution for client-side storage of significant amounts of structured data, including files/blobs.

Purpose: Useful for applications that require a large amount of data to be stored locally, like offline applications, or for client-side storage that exceeds the limitations of Local and Session Storage.

Storage Limit: No specific limit, varies by browser and available disk space.

Data Types: Can store simple types like numbers and strings as well as complex types like blobs and objects.

Asynchronous: Operations in IndexedDB are generally asynchronous, allowing the UI to remain responsive.

Transaction-based: IndexedDB is transactional to ensure data integrity even if a request fails.

Syntax for Opening a Database:
const request = indexedDB.open(“MyDatabase”, 1);

Syntax for Creating an Object Store:
request.onupgradeneeded = function(event) { const db = event.target.result; const objectStore = db.createObjectStore("MyObjectStore", { keyPath: "id" }); };

Syntax for Adding Data:
const transaction = db.transaction(["MyObjectStore"], "readwrite"); const objectStore = transaction.objectStore("MyObjectStore"); objectStore.add({ id: 1, name: "Example" });

Syntax for Retrieving Data:
const request = objectStore.get(1);
request.onsuccess = function(event) { console.log(event.target.result); };

Event: Various events like onsuccess, onerror, and onupgradeneeded can be used to handle different scenarios.

Security: Data is origin-specific and not encrypted, so sensitive information should be handled carefully.

Cross-origin: IndexedDB is restricted to the same-origin policy, meaning it can’t be accessed by other websites.

Note: IndexedDB is more complex than Local and Session Storage but offers greater flexibility and storage capacity. Always validate and sanitize data to prevent security risks.

73
Q

JavaScript Map Class

A

Description:
The Map class in JavaScript is a collection of key-value pairs where keys can be of any type (not restricted to strings or symbols) and are ordered based on their insertion order.

Syntax:
new Map([iterable])

Methods:
set(key, value): Adds or updates an element with a key-value pair.
get(key): Retrieves the value associated with a key.
has(key): Checks if a key exists in the map.
delete(key): Removes the element with the specified key.
clear(): Removes all elements from the map.
size: A property that returns the number of key-value pairs.

Example:
// Create a new Map
const myMap = new Map();

// Adding key-value pairs
myMap.set(‘name’, ‘John’);
myMap.set(1, ‘one’);
myMap.set(true, ‘boolean’);

// Retrieve values
console.log(myMap.get(‘name’)); // Output: ‘John’

// Check existence
console.log(myMap.has(1)); // Output: true

// Delete a key-value pair
myMap.delete(‘name’);

// Size of Map
console.log(myMap.size); // Output: 2

// Iterate over Map
myMap.forEach((value, key) => {
console.log(${key}: ${value});
});

Note:
Maps are different from objects, as they allow keys of any type and maintain the insertion order.

74
Q

JavaScript Set Class

A

Description:
The Set class in JavaScript represents a collection of values where each value must be unique. The values can be of any type and are stored in the insertion order.

Syntax:
new Set([iterable])

Methods:
add(value): Adds a value to the Set.
has(value): Checks if a value exists in the Set.
delete(value): Removes a value from the Set.
clear(): Removes all values from the Set.
size: A property that returns the number of values.

Example:
// Create a new Set
const mySet = new Set();

// Add values
mySet.add(1);
mySet.add(‘hello’);
mySet.add(true);

// Check existence
console.log(mySet.has(1)); // Output: true

// Delete a value
mySet.delete(‘hello’);

// Size of Set
console.log(mySet.size); // Output: 2

// Iterate over Set
for (const value of mySet) {
console.log(value);
}

Note:
Unlike arrays, Sets automatically ensure all elements are unique. Also, unlike Maps and objects, Sets store single values rather than key-value pairs.

75
Q

Frameworks vs. Libraries

A

Library: A collection of reusable functions.
Your code calls libraries (unopinionated)

Framework: A provided structure for your code.
Frameworks call your code (opinionated)