General Flashcards

1
Q

When creating a Number object, what do passed values that can’t be converted return?

A

NaN

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

What error types does JavaScript have?

A

As well as the generic Error object JavaScript offers other error constructors tailored to specific errors.

RangeError - creates a RangeError instance that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError - creates a ReferenceError instance when trying to dereference a non-existant variable.

TypeError - creates a TypeError instance that occurs when a variable or parameter is not of a valid type.

URIError - creates a URIError instance that occurs when URI handling functions are passed malformed URIs.

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

What is a binding?

A

A binding is the combination of a name (like a) and a storage slot for its current value. Variables are bindings. So are constants, parameters, the variable created by a function declaration, and various built-in things like this.

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

What does mutable mean?

A

A mutable value is one that can be changed without creating an entirely new value. In JavaScript, objects and arrays are mutable by default, but primitive values are not — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned.

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

What types are mutable and what are not?

A

Mutable: arrays, objects.
Non-mutable: primitive values

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

What are the two types of values in JavaScript?

A

Primitive types and reference types.

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

List out the primitive types

A

Strings, numbers, null, undefined, symbols, bigInt, booleans

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

List out the reference types

A

Arrays, objects, functions

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

What is a reference type?

A

Reference Value: JavaScript provides three types of Reference values that include Array, Object, and Function. The size of a reference value is dynamic therefore It is stored on Heap. When we access a reference value, we manipulate it through reference, not through its actual value that is stored.

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

What are the two types of modules?

A

CommonJs and ECMAScript Harmony (ES6)

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

What are the two types of module exports in JavaScript?

A

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.

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

What does __proto__ signify?

A

__proto__ represents the [[Prototype]] of the object

The __proto__ getter function exposes the value of the internal [[Prototype]] of an object.

However the use of __proto__ is controversial and discouraged.

const o = {
a: 1,
b: 2,
__proto__: {
b: 3,
c: 4,
},
};

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

What is [[Prototype]]? or someObject.[[Prototype]]?

A

someObject.[[Prototype]] is used to designate the prototype of someObject.

The [[Prototype]] internal slot can be accessed and modified with the Object.getPrototypeOf() and Object.setPrototypeOf() functions respectively.

This is equivalent to the JavaScript accessor __proto__

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

How do you set obj1 to be the prototype of obj2?

A

let obj1 = {
prop1: ()=>console.log(‘prop1’)
}
let obj2 = {
prop2: ()=>console.log(‘prop2’)
}
Object.setPrototypeOf(obj2, obj1);

obj2.prop2();
obj1.prop1();

therefore
const obj2 = {
prop2: () => console.log(‘prop2’),
__proto__: {
prop1: () => console.log(‘prop1’),
}
}

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

How do you find the prototype of an object?

A

Object.getPrototypeOf(obj2);
will equal: obj1

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

How do discern between the properties of an object and its prototype?

A

Object.getOwnPropertyNames(obj2)
will return prop2

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

What is a Runtime Environment?

A

A runtime environment is where your program will be executed. It determines what global objects your program can access and it can also impact how it runs.

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

What are the two JavaScript runtime environments:

A

The runtime environment of a browser (like Chrome, or Firefox) and this is called an ‘engine’

The Node runtime environment

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

Why was node created?

A

The Node runtime environment was created for the purpose of executing JavaScript code without a browser, thus enabling programmers to create full-stack (front-end and back-end) applications using only the JavaScript language.

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

Why is the noderun-time environment different from the browser?

A

The Node runtime environment gives back-end applications access to a variety of features unavailable in a browser, such as access to the server’s file system, database, and network.

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

What is process.env? As in process.env.PWD?

A

process.env is an object containing environment variables such as process.env.PWD which contains the current working directory

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

Is Node a framework!

A

So Nodejs is not a framework (or a language) but a JavaScript runtime built on Chrome’s V8 JavaScript engine.

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

Is Node.js Single-threaded and is it Synchronous or Asynchronous?

A

Node.js is Single-threaded and Asynchronous.

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

In the browser how does the event loop operate with setTimeOut?

A

Whenever an async function is called, it is sent to a browser API. These are APIs built into the browser. Based on the command received from the call stack, the API starts its own single-threaded operation.

Therefore when a setTimeout is called, it is processed in the stack and then sent to the corresponding API which waits till the specified time to send this operation back in for processing.

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

How is node asynchronous?

A

Node can create multiple threads, but only one thread is dedicated to parsing and executing javascript code.

The other threads are started from C++ bindings called from the JS.

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

What area of the heap contains promises?

A

Micro Tasks Queue aka Job Queue

JavaScript promises and the Mutation Observer API both use the microtask queue to run their callbacks

27
Q

What are map, filter and reduced used for?

A

They modify each element of an array to return a single value or array.

28
Q

What is the difference between Undefined and Null?

A

Undefined: When you declare a variable but don’t give it a value, it’s considered undefined.

Null: Null is used when you want to explicitly say that a variable has no value. It’s like an empty container.

The key difference between them is that ‘null’ is a value you can assign to a variable, whereas ‘undefined’ usually means the variable hasn’t been given any value yet. However, it’s not a good practice to assign ‘undefined’ intentionally.

29
Q

What is the difference between “ == “ and “ === “ operators

A

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

30
Q

What are the modes in JavaScript, and why are they used?

A

JavaScript has two primary modes: “Strict Mode” and “Non-Strict Mode”. These modes affect how JavaScript code is parsed and executed.

31
Q

What is strict mode?

A

Strict is used by adding “use strict”; at the beginning of a script or a function.

  • Enforces stricter parsing and error handling.
  • Helps catch common coding mistakes and “unsafe” actions.
  • Prohibits certain syntax and variable names.
32
Q

What is ‘sloppy’ (non-strict mode)?

A

The default mode in JavaScript is used if “use strict” is not present.

  • Offers more forgiving error handling and type coercion.
  • Allows for more lenient variable and property assignments.
  • Doesn’t catch as many potential coding issues as strict mode.
33
Q

Question: What is the concept of currying in JavaScript, and how is it used?

A

Currying is a functional programming technique that involves transforming a function with multiple arguments into a sequence of functions, each taking a single argument. It allows partial application of arguments, creating new functions until all the required arguments are provided, resulting in the final value.

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

var multiplyByTwo = multiply(2);
console.log(multiplyByTwo(5)); // Output: 10

34
Q

Explain the concept of memoization in JavaScript.

A

Memoization is an optimization technique where the return value of a function is cached based on its input parameters. If the function is called again with the same parameters, instead of re-computing the result, the cached value is returned. This can significantly improve performance for functions with expensive computations.

function memoize(fn) {
const cache = {};

return function(…args) {
const key = JSON.stringify(args);

if (key in cache) {
      return cache[key];
} else {
      const result = fn(...args);
  cache[key] = result;
  return result;
}   }; }
35
Q

What is the difference between shallow copy and deep copy in JavaScript? Provide examples for each.

A

1- Shallow copy: A shallow copy creates a new object that references the original object’s properties. Modifying the properties of the new object may affect the original object.

const originalObj = { name: 'John', age: 30 };
const shallowCopy = Object.assign({}, originalObj);

shallowCopy.name = 'Jane';
console.log(originalObj.name); // Output: 'John'

```
const originalObj = { name: ‘John’, age: 30 };
const deepCopy = JSON.parse(JSON.stringify(originalObj));

deepCopy.name = ‘Jane’;
console.log(originalObj.name); // Output: ‘John’
~~~

36
Q

Explain the concept of immutability in JavaScript and why it is important. Provide an example.

A

Immutability refers to the inability of an object (or its state) to be modified after it is created. In JavaScript, primitive values (e.g., strings, numbers) are immutable, while objects and arrays are mutable. Immutability is important because it helps avoid unintended side effects, enables simpler state management, and improves performance.

37
Q

What is a generator function in JavaScript? Provide an example of its usage.

A

A generator function is a special type of function that can be paused and resumed during its execution. It is defined using the function* syntax and uses the yield keyword to yield a sequence of values.
~~~
function* countUpTo(max) {
for (let i = 1; i <= max; i++) {
yield i;
}
}

const generator = countUpTo(5);

console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3
~~~

38
Q

Explain the concept of event bubbling in JavaScript and how to stop it. Provide an example.

A

Event bubbling is a phenomenon where an event triggered on a nested element is also triggered on its parent elements in the DOM hierarchy. It follows the order from the innermost element to the outermost element. To stop event bubbling, the event.stopPropagation() method can be used.
~~~
document.getElementById(‘inner’).addEventListener(‘click’, event => {
console.log(‘Inner element clicked’);
event.stopPropagation();
});

document.getElementById(‘outer’).addEventListener(‘click’, event => {
console.log(‘Outer element clicked’);
});
~~~

39
Q

What are the differences between function declarations and function expressions in JavaScript? Provide examples for each.

A

The main difference is that function declarations are hoisted and can be called before they are defined, whereas function expressions are not hoisted and must be defined before they are called.

40
Q

Explain the concept of the “rest” parameter in JavaScript functions and provide an example of its usage.

A

The “rest” parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by three dots (…) followed by the parameter name. The rest parameter collects the remaining arguments passed to the function.
~~~
function sum(…numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Output: 15
~~~

41
Q

What is the purpose of the Object.setPrototypeOf() method in JavaScript? Provide an example.

A

The Object.setPrototypeOf() method is used to set the prototype (i.e., the internal [[Prototype]] property) of an object.

const parent = { name: 'John' };
const child = { age: 30 };

Object.setPrototypeOf(child, parent);

console.log(child.name); // Output: 'John'
42
Q

Explain the concept of the event-driven programming paradigm in JavaScript and provide an example.

A

Event-driven programming is a programming paradigm where the flow of the program is determined by events that occur, such as user actions or system events. The program responds to these events by executing corresponding event handlers or callbacks.

43
Q

What are JavaScript Promises, and how do they work? Provide an example.

A

Promises are a built-in feature in JavaScript used for handling asynchronous operations. They represent the eventual completion (or failure) of an asynchronous task and allow chaining of multiple asynchronous operations.
~~~
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = ‘Sample data’;
resolve(data);
}, 2000);
});
}

fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
~~~

44
Q

Explain the concept of the module pattern in JavaScript and provide an example.

A

The module pattern is a design pattern used to encapsulate and organize code by creating self-contained modules with private and public members. It helps in achieving modularity, encapsulation, and separation of concerns.

const counterModule = (function() {
  let count = 0;

  function increment() {
    count++;
  }

  function decrement() {
    count--;
  }

  function getCount() {
    return count;
  }

  return {
    increment,
    decrement,
    getCount
  };
})();

console.log(counterModule.getCount()); // Output: 0
counterModule.increment();
counterModule.increment();
console.log(counterModule.getCount()); // Output: 2
45
Q

What is the event loop in JavaScript, and how does it work?

A

The event loop is a fundamental mechanism in JavaScript that allows non-blocking asynchronous operations to execute efficiently. It maintains a loop that continuously checks for tasks in the event queue. When a task is found, it is pushed onto the call stack for execution. This allows JavaScript to handle asynchronous operations seamlessly and ensure smooth program flow.

46
Q

Explain the concept of closures in JavaScript and provide an example.

A

Closures are an important concept in JavaScript where a function retains access to its lexical scope even when executed outside its original scope. This allows the function to access variables and parameters that were in scope at the time of its creation.

47
Q

What are the differences between “undefined” and “null” in JavaScript?

A

In JavaScript, “undefined” is a value assigned to variables that have been declared but have not been assigned a value. It signifies the absence of any value. On the other hand, “null” is a value that represents the intentional absence of an object value. It is often used as a placeholder when a value is expected but not yet determined.

48
Q

Explain the concept of prototypal inheritance in JavaScript.

A

Prototypal inheritance is a key feature of JavaScript that allows objects to inherit properties and methods from other objects. In this inheritance model, objects can serve as prototypes for creating new objects. When a property or method is accessed on an object, JavaScript searches the object’s prototype chain until it finds the desired property or method.

var parent = {
      name: "John",
  greet: function() {
        console.log("Hello, " + this.name + "!");
  }
};

var child = Object.create(parent);
child.name = "Emily";
child.greet(); // Output: Hello, Emily!
49
Q

Explain the differences between “let,” “const,” and “var” in JavaScript.

A

“let” and “const” were introduced in ES6 (ECMAScript 2015) and provide block-scoping, meaning they are limited to the block in which they are defined. “let” allows variable reassignment, while “const” is used for variables that should not be reassigned. “var” is function-scoped and can be hoisted, but it does not have block scope.

50
Q

How does “async/await” work in JavaScript?

A

“async/await” is a syntax introduced in ES2017 (ES8) that simplifies asynchronous code execution. The “async” keyword is used to define an asynchronous function, while the “await” keyword is used to pause the execution of the function until a Promise is resolved or rejected.

51
Q

What are the different ways to create objects in JavaScript? Provide examples for each method.

A

Object literals:
~~~
const obj = { key: value };
~~~
Constructor functions:
~~~
function Person(name) {
this.name = name;
}

const person = new Person(‘John’);
~~~
Object.create():
~~~
const protoObj = {
greet: function() {
console.log(‘Hello’); }
};
const obj = Object.create(protoObj);
~~~
ES6 Classes:
~~~
class Person {
constructor(name) {
this.name = name;
}
}

const person = new Person(‘John’);
~~~

52
Q

What is the difference between call(), apply(), and bind() methods? Provide examples for each.

A

call(): Calls a function with a specified this value and arguments passed individually.
~~~
function greet(message) {
console.log(message + ‘, ‘ + this.name);
}

const person = { name: ‘John’ };
greet.call(person, ‘Hello’);
~~~
apply(): Calls a function with a specified this value and arguments passed as an array-like object.
~~~
function greet(message) {
console.log(message + ‘, ‘ + this.name);
}

const person = { name: ‘John’ };
greet.apply(person, [‘Hello’]);
~~~
bind(): Creates a new function with a specified this value and initial arguments.
~~~
function greet(message) {
console.log(message + ‘, ‘ + this.name);
}

const person = { name: ‘John’ };
const greetPerson = greet.bind(person);
greetPerson(‘Hello’);
~~~

53
Q

What are the different ways to handle errors in JavaScript? Provide examples for each method.

A
  1. Using try…catch
  2. Using throw to manually throw an error:
  3. Using finally to specify code that will always execute:
try {
  // Code that may throw an error
} catch (error) {
  // Handle the error
} finally {
  // Code that always executes
}
54
Q

Explain the concept of promises in JavaScript and provide an example of their usage.

A

Promises are objects representing the eventual completion or failure of an asynchronous operation. They allow handling asynchronous operations in a more structured and readable way.

55
Q

What is the purpose of the map() function in JavaScript? Provide an example.

A

The map() function is used to transform elements of an array and return a new array with the transformed values, without modifying the original array.

56
Q

Explain the concept of debouncing and provide an example of its usage.

A

Debouncing is a technique used to limit the rate at which a function is called, especially in scenarios where the function is triggered frequently. It delays the execution of a function until a certain amount of time has passed since the last invocation.

57
Q

What is the purpose of the reduce() function in JavaScript? Provide an example.

A

The reduce() function is used to reduce an array to a single value by applying a function to each element of the array, accumulating the result.

58
Q

Explain the concept of hoisting in JavaScript and provide an example.

A

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the creation phase, allowing them to be used before they are declared.

59
Q

What is the purpose of the Object.keys() method in JavaScript? Provide an example.

A

The Object.keys() method is used to extract all enumerable property names of an object and return them as an array.

60
Q

Explain the concept of event delegation in JavaScript and provide an example.

A

Event delegation is a technique where instead of attaching an event listener to each individual element, a single event listener is attached to a common ancestor. Events are then handled based on their target element within the ancestor.

61
Q

What is the opposite of event bubbling?

A

Event capturing

62
Q

What is the difference between event bubbling and event capturing?

A

In bubbling the inner most element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.

In capturing the outer most element’s event is handled first and then the inner: the <div> element’s click event will be handled first, then the <p> element’s click event.

63
Q

How do you deep clone an object and what errors can occur?

A

Use the new method: structuredClone.
You cannot clone an object with functions as properties