JavaScript - Intermediate Flashcards

1
Q

Function declaration

A
  • It defines a named function using the function keyword, followed by the function name and its body.
  • Function declarations are hoisted, meaning they are accessible throughout the entire scope in which they are defined.

For example:

 function myFunction() {
   // function body
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Function expression

A
  • It assigns a function to a variable or a constant.
  • Function expressions are not hoisted and can only be accessed after the assignment.

For example:

const myFunction = function() {
  // function body
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Concept of scope and how it works in JavaScript

A
  • JavaScript uses Lexical scope (also known as static scope). Lexical scope means that the scope is determined by it’s location in the source code and isn’t affected by the way functions are called.
  • Before ES6 JavaScript used functional scope which means that wherever a variable or function is defined within a function block or it’s sub blocks that variable/function is hoisted and thus available from anywhere within the function block.
  • After the introduction of let and const in ES6 which provided a way to use block scope (instead of functional scope) limiting the scope of the variable to the block in which it is defined rather than hoisting it to the top of the function.
  • function expressions scope is determined by whether or not var or let/const are used and follow the above rules accordingly.
  • traditional functions are hoisted to the top of the code block that they are defined in and accessible within that code block and sub blocks.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Different ways to create objects in JavaScript

A
  1. Object literals
  2. Constructor function
  3. Object.create()
  4. Class Syntax
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Object literal code example

A

For example:

 const myObject = {
   key1: value1,
   key2: value2,
   // ...
 };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Constructor function code example

A

For example:

function MyObject(key1, key2) {
  this.key1 = key1;
  this.key2 = key2;
}

const myObject = new MyObject(value1, value2);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Object.create() code example

A

For example:

const proto = {
    key1: 'no value',
    2: 'no value'
}

const myObject = Object.create(proto);
myObject.key1 = value1;
myObject.key2 = value2;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

ES6+ Class Syntax code example

A

For example:

class MyObject {
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }
}

const myObject = new MyObject(value1, value2);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

“this” keyword behavior in regular functions

A
  • In regular functions, the value of this is determined by how the function is called.
  • It usually refers to the object on which the function is invoked,
  • or it can be explicitly set using call(), apply(), or bind().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

“this” keyword behavior in arrow functions

A

Arrow functions do not bind their own this value.

Therefore if this is used in an arrow function, it will not refer to the parent scope, rather it will refer to the lexical or ancestral scope of the arrow function.

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

Methods available for iterating over an object’s properties

A
  1. for … in
  2. Object.keys()
  3. Object.values()
  4. Object.entries()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

for … in code example

A

Example:

const aPerson = {
  name: "Brad Jones",
  age: 44,
  gender: "male",
  ethnicity: "white",
  citizenship: "USA",
};

for (const key in aPerson) {
  if (Object.hasOwnProperty.call(aPerson, key)) {
    const element = aPerson[key];
    console.log(element);
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Object.keys() code example

A

const keys = Object.keys(object);
keys.forEach((key) => {
const value = object[key];
// Use key and value
});

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

Object.values() code example

A

const values = Object.values(object);
values.forEach((value) => {
// Use value
});

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

Object.entries() code example

A

For example:

const entries = Object.entries(object);
entries.forEach(([key, value]) => {
  // Use key and value
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does the envent loop enable asynchronous behavior?

A
  1. When an asynchronous task (e.g., network request, setTimeout) is encountered, it is offloaded to the browser’s Web API.
  2. The event loop continues executing other tasks while waiting for the completion of the asynchronous task.
  3. Once the asynchronous task completes, a callback is pushed into the event queue.
  4. The event loop constantly checks the event queue and moves callbacks to the call stack when it’s empty, allowing their execution to continue.
  5. This mechanism enables JavaScript to perform tasks asynchronously, avoiding blocking the main thread and providing responsiveness to user interactions.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you handle asynchronous errors using Promises?

A

Promises have a .catch() method to handle errors that occur during asynchronous operations.

For Example:

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

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

How do you handle asynchronous errors using async/await?

A

Async functions can use try/catch blocks to handle errors.

For Example:

async function myFunction() {
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
19
Q

How do you handle asynchronous errors using Callbacks?

A

Callback functions can check for errors as the first argument passed to the callback.

For Example:

asyncFunction((error, result) => {
if (error) {
// Handle error
} else {
// Handle success
}
});

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

null

A

null is an assignment value that represents the intentional absence of any object value.

It is a primitive value that signifies the absence of a value.

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

undefined

A
  • undefined is a primitive value variables have before they are assigned a value.
  • It also represents the value returned by functions that do not explicitly return anything.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Promise

A
  • Promises are objects that representing the eventual completion or failure of an asynchronous operation, and their resulting value.
  • Promises have three states:
    1. pending,
    2. fulfilled,
    3. or rejected.
  • They are initially in the pending state, then transition to either fulfilled (resolved) with a value or rejected with a reason (error).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

async/await

A
  • The async keyword is used to declare an asynchronous function.
  • Within an async function, you can use the await keyword to pause the execution and wait for a promise to resolve or reject.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How does async/await simplify working with asynchronous code?

A
  • Using await eliminates the need for explicit promise chaining
  • and allows you to write code that appears to be synchronous, making it easier to understand and maintain.
25
Q

Different ways to shallow copy an array in JavaScript

A
  1. Array.from(),
  2. Spread syntax […array],
  3. array.slice()
26
Q

Different ways to shallow copy an object in JavaScript

A
  1. Object.assign({}, object),
  2. Spread syntax {…object}
27
Q

Shallow copy

A
  • Shallow copies create a new array/object,
  • but if the original array/object contains nested objects, the references to the nested objects are still shared between the original and copied array/object.
28
Q

Different ways to deep copy an array or object in JavaScript

A
  • Lodash _.cloneDeep()
  • JSON.parse(JSON.stringify(array/object))
29
Q

Deep copy

A
  • Deep copies create completely independent copies of the array/object, including all nested objects.
  • However, be aware that JSON.stringify() has limitations and cannot handle certain data types like functions or circular references.
30
Q

Modules in JavaScript and how they help organize code

A

Modules in JavaScript provide a way to encapsulate code into separate files, making it easier to organize and maintain large codebases.

31
Q

Strict mode rules that are enforced

A
  1. Disallows the use of undeclared variables.
  2. Prevents assigning values to undeclared variables.
  3. Throws errors for duplicate parameter names in function declarations.
  4. Forbids deleting variables, functions, or function arguments.
  5. Disallows octal literals and makes parsing stricter.
  6. Restricts the use of eval() to evaluate strings as code.
  7. Prevents the use of the this value in the global scope.
32
Q

Higher-order functions in JavaScript

A

Higher-order functions are functions that:
1. can take other functions as arguments
2. or return functions as their results.

33
Q

Concept of currying in JavaScript

A

Currying allows for partial function application, where you can fix some arguments and obtain a new function that takes the remaining arguments.

For Example:

function multiply(a) {
  return function(b) {
    return a * b;
  };
}

const multiplyByTwo = multiply(2);
console.log(multiplyByTwo(4)); // Output: 8
34
Q

Generators

A
  • Generators are a special type of function in JavaScript that can be paused and resumed during their execution.
  • They are defined using the function* syntax.
  • generators can be paused with yield and resumed later with next().
  • When a generator function is called, it returns an iterator object that can be used to control the generator’s execution.
  • Each call to next() on the iterator:
    1. advances the generator to the next yield statement,
    2. returning an object with the yielded value and a done property indicating if the generator has finished.
35
Q

Variable hoisting

A

Variables declared with var are hoisted to the top of their scope

Variables declared with let and const are also hoisted, but they are not accessible before the declaration due to the temporal dead zone.

36
Q

Functional hoisting

A

Standard Function declarations are fully hoisted and can be accessed before their actual declaration in the code.

Function expressions, including arrow functions, are not hoisted like function declarations.

37
Q

Closure

A
  • A closure allows an inner function to access variables from its outer (enclosing) scope even after the outer function has finished executing.
  • Closures are useful for creating private variables and encapsulating data.

For Example:

function createCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}

const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2

NOTE: In this example, the inner function has access to the count variable even after createCounter() has finished executing. Each time counter() is called, it increments and logs the count.

38
Q

Best practices for exception handling

A
  1. Catch specific exceptions rather than using a generic catch-all block.
  2. Properly handle errors by logging or displaying useful error messages to users.
  3. Avoid swallowing exceptions by ensuring that the catch block does not ignore or suppress the error.
  4. Use finally block to specify code that should always be executed, regardless of whether an exception was thrown or not.
39
Q

Methods for manipulating arrays in JavaScript

A
  1. push()
  2. pop()
  3. shift()
  4. unshift()
  5. slice()
  6. splice()
  7. concat()
  8. reverse()
  9. sort()
  10. filter()
  11. map()
40
Q

push()

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

pop()

A
  • Removes the last element from an array
  • and returns that element.
42
Q

shift()

A
  • Removes the first element from an array and
  • returns that element (shifting all other elements down by one.)
43
Q

unshift()

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

slice()

A
  • Returns a new array
  • containing a portion of the original array (based on the start and end indices)
45
Q

splice()

A
  • Changes the contents of an array
  • by:
    1. removing,
    2. replacing,
    3. or adding elements at a specific position.
46
Q

concat()

A
  • Combines two or more arrays
  • and returns a new array.
47
Q

reverse()

A
  • Reverses the order of the elements in an array.
48
Q

sort()

A
  • Sorts the elements of an array in place
  • and returns the sorted array.
49
Q

filter()

A
  • **Creates a new array **
  • with all elements that pass a test provided by a callback function.
50
Q

map()

A
  • Creates a new array
  • with the results of calling a provided function on every element in the array.
51
Q

Debouncing

A
  • Debouncing limits the frequency at which a function is called. (It ensures that the function is executed only after a certain period of inactivity.)

Example use case: Autosave feature in a text editor.

52
Q

Throttling

A
  • Throttling limits the rate at which a function is called

Example: Limiting the rate of API requests

53
Q

How do you create a cookie using JavaScript

A

example:

document.cookie = "a string value"
54
Q

How do you read a cookie

A

example:
const cookiesString = document.cookie;

This will return a string delimited by semicolon for each cookie name=value pair.

55
Q

How do you delete a cookie

A

set its expiration date to a past date.

example:

 expires=Thu, 29 Jun 2023 19:51:13 GMT
56
Q

Object destructuring

A
  • It provides a convenient syntax to extract specific properties from an object into individual variables.

For example:

const person = { name: "John", age: 30, city: "New York" };
const { name, age } = person;
57
Q

Implementing inheritance in JavaScript using prototypes

A
  • The prototype is an object
  • that is associated with a constructor function
  • and serves as the blueprint for creating new objects.

For Example:

function Person(name) {
  this.name = name;
} 
 
Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name);
};

function Student(name, grade) {
    Person.call(this, name);
    this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

Student.prototype.sayGrade = function() {
    console.log("I am in grade " + this.grade);
};

const john = new Student("John", 10);
john.sayHello(); // Output: "Hello, my name is John"
john.sayGrade(); // Output: "I am in grade 10"
58
Q

Purpose of the “event.preventDefault()”

A
  • It stops the event from performing its default action, such as submitting a form or following a link.
59
Q

preventDefault() use cases

A
  1. Form Submission
  2. Link Clicks
  3. Key Presses