Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save davidystephenson/f266aab1b962502e2d7b264b2653eea6 to your computer and use it in GitHub Desktop.

Select an option

Save davidystephenson/f266aab1b962502e2d7b264b2653eea6 to your computer and use it in GitHub Desktop.
# Questions
## JavaScript (Core)
### Language fundamentals
1. What is the difference between passing a primitive value and passing an object as a function argument in JavaScript? What happens in each case when you modify the parameter inside the function?
### Execution model (call stack, event loop, task queues)
1. Given this code, explain what happens to the call stack and what error you would see:
```javascript
function a() { b(); }
function b() { c(); }
function c() { a(); }
a();
```
2. Explain the order of execution and why:
```javascript
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
queueMicrotask(() => console.log('4'));
console.log('5');
```
3. If you have a `setTimeout` with 0ms delay and a `Promise.resolve().then()`, which executes first and why? What queue does each use?
### Scope, closures, hoisting
1. What will this code output?
```javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
```
2. Explain why these two counter implementations behave differently when called multiple times:
```javascript
const counter1 = (() => {
let count = 0;
return () => ++count;
})();
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter2 = makeCounter();
const counter3 = makeCounter();
```
3. What will this code output and why?
```javascript
function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();
```
### this, prototypes, inheritance
1. What will `this` be in each `setTimeout` callback, and why?
```javascript
const obj = {
name: 'MyObject',
method1: function() {
setTimeout(function() {
console.log(this.name);
}, 100);
},
method2: function() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
```
2. Explain the prototype chain in JavaScript. If you have `obj.hasOwnProperty('x')`, where does the `hasOwnProperty` method come from, and how does JavaScript find it?
3. When using ES6 classes, what is actually happening under the hood with prototypes? How does `class Child extends Parent` relate to prototypal inheritance?
### Async patterns (callbacks, promises, async/await)
1. What is the difference between these two code blocks in terms of error handling and execution flow?
```javascript
// Block A
fetch('/api/user')
.then(res => res.json())
.then(user => fetch(`/api/posts/${user.id}`))
.then(res => res.json())
.catch(err => console.error(err));
// Block B
async function getData() {
const userRes = await fetch('/api/user');
const user = await userRes.json();
const postsRes = await fetch(`/api/posts/${user.id}`);
const posts = await postsRes.json();
}
```
2. If you call `Promise.all([promise1, promise2, promise3])` and `promise2` rejects after 100ms while `promise1` and `promise3` take 500ms to resolve, when does `Promise.all` reject and what happens to `promise1` and `promise3`?
3. What is wrong with this code and what will actually happen when `processItems` is called?
```javascript
async function processItem(item) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Processed:', item);
}
async function processItems(items) {
items.forEach(async (item) => {
await processItem(item);
});
console.log('All done!');
}
processItems([1, 2, 3]);
```
### Memory management & Garbage Collector
1. In a single-page application, you attach click event listeners to dynamically created DOM elements. The elements are later removed from the DOM with `element.remove()` but you forgot to remove the event listeners. What happens to these elements in memory and why?
2. Explain how mark-and-sweep garbage collection works in JavaScript. What determines when an object is eligible for garbage collection?
### Error handling
1. In what order will the console.log statements execute, and what will each output?
```javascript
async function test() {
console.log('A');
try {
await Promise.reject('Error 1');
console.log('B');
} catch (err) {
console.log('C:', err);
throw new Error('Error 2');
} finally {
console.log('D');
}
console.log('E');
}
test().catch(err => console.log('F:', err.message));
console.log('G');
```
### ES6+ features
1. What will be logged and why?
```javascript
const obj = { x: 1, y: 2, z: 3 };
const { x, ...rest } = obj;
rest.x = 10;
console.log(obj.x);
const arr = [1, [2, 3], 4];
const [a, b] = arr;
b[0] = 99;
console.log(arr);
```
### Modules (CJS, ESM)
1. What is the fundamental difference between CommonJS (`require`/`module.exports`) and ES Modules (`import`/`export`) in terms of when they are evaluated and whether they return a copy or a live binding?
2. Given these module files, what will be outputted?
```javascript
// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import { count, increment } from './counter.js';
console.log(count);
increment();
console.log(count);
count = 5;
console.log(count);
```
## TypeScript
### Type system fundamentals
1. Does this code throw TypeScript errors? Why or why not?
```typescript
interface Point2D { x: number; y: number; }
interface Point3D { x: number; y: number; z: number; }
const point3D: Point3D = { x: 1, y: 2, z: 3 };
const point2D: Point2D = point3D;
```
### Advanced types (union, intersection, conditional)
1. Which properties are accessible on the `Person` type?
```typescript
type Admin = { role: 'admin'; permissions: string[]; id: number };
type User = { role: 'user'; id: number; email: string };
type Guest = { role: 'guest'; sessionId: string };
type Person = Admin | User | Guest;
```
2. What will the four exported types be?
```typescript
type Narrow<T, U> = T & U;
export type A = Narrow<string, 'hello'>;
export type B = Narrow<number, 42>;
export type C = Narrow<string | number, string>;
export type D = Narrow<{ x: number }, { x: 5 }>;
```
3. How do conditional types with `infer` work? What will `Beta` resolve to?
```typescript
type Alpha<T> = T extends (...args: any[]) => infer R ? R : never;
type Beta = Alpha<(x: number) => string>;
```
### Generics
1. Will this code throw type errors? Why or why not?
```typescript
function getProperty<T>(obj: T, key: string) {
return obj[key];
}
const user = { name: 'Alice', age: 30 };
const name: string = getProperty(user, 'name');
const age: number = getProperty(user, 'age');
const invalid = getProperty(user, 'email');
```
### Utility types
1. How does `Record<K, V>` differ from an index signature, and when would you use each? What is the difference between these two types?
```typescript
type A = Record<string, number>;
type B = { [key: string]: number };
```
### Type narrowing & inference
1. What is the difference between `value as T` and `value as unknown as T`? When would TypeScript allow each form of assertion, and what are the risks?
### Declaration files
1. Explain the difference between ambient declarations (using `declare`) and regular type definitions. Why can't you include implementation code in a `.d.ts` file?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment