commit 217b1f6a00068d467fbf3affb29fe28badd611e8 Author: Natalie Date: Sun Apr 12 11:24:28 2026 -0700 Initial commit: JavaScript interview prep materials diff --git a/README.md b/README.md new file mode 100644 index 0000000..894eb13 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# JavaScript Interview Preparation + +A comprehensive 6-hour curriculum designed for JavaScript developers preparing for technical interviews. Created for developers who started with JavaScript in 1999 and need targeted remastery. + +## Structure + +### Exams +- `exams/00-evaluation.md` - Diagnostic assessment (25 questions) +- `exams/00-evaluation-answers.md` - Answer key with explanations + +### Lessons +Each lesson includes: +- `knowledge.md` - Core concepts, explanations, and examples +- `quiz-difficulty-medium.md` - Practice quiz for the topic + +#### Lesson Topics (45-50 minutes each) + +- **Lesson 00** - Getting Started & Assessment Review +- **Lesson 01** - Type System & Coercion +- **Lesson 02** - This Binding & Contexts +- **Lesson 03** - Closures & Scope +- **Lesson 04** - Event Loop & Async Execution +- **Lesson 05** - Promises & Async/Await +- **Lesson 06** - Prototypes & Classes +- **Lesson 07** - ES6+ Modern Features +- **Lesson 08** - Array Methods & Functional Programming + +## How to Use + +1. **Take the Diagnostic** (20 minutes) + - Complete `exams/00-evaluation.md` + - Don't look up answers - assess your current knowledge + - Check your answers against `exams/00-evaluation-answers.md` + +2. **Review Your Results** (10 minutes) + - Count correct answers + - Identify which sections had the most errors + - Note: Each question maps to a specific lesson topic + +3. **Study Your Curriculum** (6 hours) + - If you scored 15+: Focus on lessons where you made mistakes + - If you scored <15: Work through all lessons sequentially + - Each lesson: 30-40 minutes reading + 10-15 minutes quiz + +4. **Practice Questions** + - Complete the medium-difficulty quiz for each lesson + - Review explanations for incorrect answers + +## Recommended Study Path + +### High Scorers (23-25 correct) +- Review explanations for missed questions +- Complete quizzes only for weak topics +- Focus on edge cases and advanced scenarios +- Total time: 2-3 hours + +### Strong Foundation (19-22 correct) +- Review missed topic lessons +- Complete corresponding quizzes +- Skim lessons you got fully correct +- Total time: 3-4 hours + +### Moderate Gaps (15-18 correct) +- Work through all missed topic lessons thoroughly +- Complete all corresponding quizzes +- Quick review of strong topics +- Total time: 4-5 hours + +### Comprehensive Study (0-14 correct) +- Work through all 8 lessons sequentially +- Complete all quizzes +- Review fundamental concepts carefully +- Total time: 6+ hours + +## Quick Reference + +### Question to Lesson Mapping + +| Questions | Topic | Lesson | +|-----------|-------|--------| +| 1, 4, 21, 22, 24, 25 | Type System & Coercion | 01 | +| 3, 23 | This Binding & Contexts | 02 | +| 5, 6 | Closures & Scope | 03 | +| 7, 19, 20 | Event Loop & Async Execution | 04 | +| 8, 9 | Promises & Async/Await | 05 | +| 13, 14, 15 | Prototypes & Classes | 06 | +| 10, 11, 12 | ES6+ Modern Features | 07 | +| 16, 17, 18 | Array Methods & Functional Programming | 08 | + +## Tips for Interview Success + +1. **Understand, Don't Memorize** - Interviewers can tell the difference +2. **Practice Explaining** - Articulate your reasoning out loud +3. **Know the "Why"** - Understand why JavaScript behaves certain ways +4. **Edge Cases Matter** - Many interview questions test boundary conditions +5. **Modern Syntax** - Show familiarity with ES6+ features + +## Next Steps After This Curriculum + +- Practice on coding platforms (LeetCode, HackerRank) +- Build small projects using modern JavaScript +- Read MDN documentation for deep dives +- Study algorithm and data structure implementations in JavaScript +- Mock interview practice with peers + +--- + +**Created for developers with 25+ years of JavaScript experience preparing for modern technical interviews.** diff --git a/exams/00-evaluation-answers.md b/exams/00-evaluation-answers.md new file mode 100644 index 0000000..312db61 --- /dev/null +++ b/exams/00-evaluation-answers.md @@ -0,0 +1,131 @@ +# Answer Key - JavaScript Diagnostic Assessment + +## Correct Answers with Explanations + +### Section 1: Core Concepts & Fundamentals + +**1. B - "object"** +- This is a famous JavaScript quirk. `typeof null` returns "object" due to a legacy bug in JavaScript that has never been fixed for backwards compatibility. + +**2. C - 11** +- When you assign to index 10, JavaScript creates a sparse array with length 11 (indices 0-10, even though 3-9 are empty slots). + +**3. B - undefined** +- When you extract a method from an object and call it as a standalone function, `this` becomes `undefined` in strict mode or the global object in non-strict mode. Since `bar` doesn't exist there, it's undefined. + +**4. B - false** +- Floating-point arithmetic precision issue. 0.1 + 0.2 equals 0.30000000000000004, not exactly 0.3. + +--- + +### Section 2: Closures & Scope + +**5. B - 3, 3, 3** +- `var` is function-scoped, not block-scoped. By the time the timeouts execute, the loop has finished and `i` is 3. All three callbacks reference the same `i`. + +**6. B - 3, 4** +- The `inner` function closes over the `x` variable from `outer`'s scope. Each call increments and logs it: first 2→3, then 3→4. + +--- + +### Section 3: Promises & Async + +**7. C - 1, 4, 3, 2** +- Synchronous code runs first (1, 4), then microtasks/promises (3), then macrotasks/setTimeout (2). + +**8. B - Promise {: "hello"}** +- Async functions always return a Promise. The promise is immediately fulfilled with "hello". + +**9. C - 3** +- The promise chain: 1 → 2 → error is thrown → caught and returns 3 → logs 3. + +--- + +### Section 4: Modern ES6+ Features + +**10. C - 3** +- Duplicate keys in object literals are allowed. The last value wins. + +**11. D - SyntaxError** +- Rest element must be the last element in destructuring. You can't have `...b` followed by `,c`. + +**12. A - 1** +- Spread operator creates a shallow copy. Modifying the copy doesn't affect the original. + +--- + +### Section 5: Objects & Prototypes + +**13. D - TypeError** +- `Object.create(null)` creates an object with no prototype. It doesn't inherit `toString()` from Object.prototype, so calling it throws a TypeError. + +**14. B - false** +- `greet` is on the prototype chain, not an own property. `hasOwnProperty` returns false. + +**15. C - ReferenceError** +- You must call `super()` before accessing `this` in a derived class constructor. This code throws "ReferenceError: Must call super constructor before accessing 'this'". + +--- + +### Section 6: Array Methods & Iteration + +**16. A - [6, 8]** +- `map` produces [2, 4, 6, 8], then `filter` keeps only values > 5, which are [6, 8]. + +**17. A - 6** +- Reduce without initial value uses first element as accumulator: 1 + 2 = 3, 3 + 3 = 6. + +**18. A - 1, 3** +- `return` in forEach only exits that iteration, not the whole loop. So 1 is logged, 2 is skipped, 3 is logged. + +--- + +### Section 7: Event Loop & Execution + +**19. B - 1, 3, 2** +- "1" logs synchronously, then "3" logs (synchronous after function call), then "2" logs (after await in microtask queue). + +**20. B - 1, 4, 2, 3** +- Both `queueMicrotask` and `Promise.then` use the microtask queue and execute in order. Synchronous code (1, 4) runs first, then microtasks (2, 3) in order. + +--- + +### Section 8: Tricky Scenarios & Edge Cases + +**21. B - false** +- Arrays are objects and compared by reference, not value. These are two different array instances. + +**22. B - ""** +- When arrays are coerced to strings for concatenation, `[] → ""`, so `"" + "" = ""`. + +**23. B - undefined** +- Arrow functions don't have their own `this` binding. They inherit `this` from the enclosing scope (likely global/window), where `value` doesn't exist. + +**24. B - 42** +- Unary `+` operator converts string to number: `+"42"` becomes `42`. + +**25. B - 20** +- `y` becomes a global variable because `y = 10` (and later `y = 20`) is an assignment without declaration. Inside the function, `y = 20` updates the global `y`. + +--- + +## Scoring Guide + +- **23-25 correct:** Excellent - Focus on edge cases and advanced topics +- **19-22 correct:** Strong - Review missed concepts +- **15-18 correct:** Good foundation - Need targeted study in weak areas +- **10-14 correct:** Moderate gaps - Focus on fundamentals and modern features +- **0-9 correct:** Significant gaps - Comprehensive curriculum needed + +## Topic Mapping + +Based on wrong answers, you'll be assigned lessons: + +- Q1, 4, 21, 22, 24, 25: **Lesson 01 - Type System & Coercion** +- Q3, 23: **Lesson 02 - This Binding & Contexts** +- Q5, 6: **Lesson 03 - Closures & Scope** +- Q7, 19, 20: **Lesson 04 - Event Loop & Async Execution** +- Q8, 9: **Lesson 05 - Promises & Async/Await** +- Q13, 14, 15: **Lesson 06 - Prototypes & Classes** +- Q10, 11, 12: **Lesson 07 - ES6+ Modern Features** +- Q16, 17, 18: **Lesson 08 - Array Methods & Functional Programming** diff --git a/exams/00-evaluation.md b/exams/00-evaluation.md new file mode 100644 index 0000000..e127ca6 --- /dev/null +++ b/exams/00-evaluation.md @@ -0,0 +1,488 @@ +# JavaScript Technical Interview - Diagnostic Assessment + +**Purpose:** Identify knowledge gaps to build a personalized 6-hour study curriculum +**Time:** No time limit - answer based on current knowledge +**Instructions:** Choose the best answer for each question. Do NOT research answers. + +--- + +## Section 1: Core Concepts & Fundamentals + +### Question 1 +What will be logged? +```javascript +console.log(typeof null); +``` +- A) "null" +- B) "object" +- C) "undefined" +- D) "number" + +**Your answer:** ___ + +A + +--- + +### Question 2 +What is the output? +```javascript +const arr = [1, 2, 3]; +arr[10] = 11; +console.log(arr.length); +``` +- A) 4 +- B) 10 +- C) 11 +- D) undefined + +**Your answer:** ___ +C +--- + +### Question 3 +What gets logged? +```javascript +function foo() { + console.log(this.bar); +} +const obj = { bar: 'hello', foo }; +const fn = obj.foo; +fn(); +``` +- A) "hello" +- B) undefined +- C) ReferenceError +- D) null + +**Your answer:** ___ +B +--- + +### Question 4 +What is the result? +```javascript +console.log(0.1 + 0.2 === 0.3); +``` +- A) true +- B) false +- C) undefined +- D) NaN + +**Your answer:** ___ +A +--- + +## Section 2: Closures & Scope + +### Question 5 +What will be logged? +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 100); +} +``` +- A) 0, 1, 2 +- B) 3, 3, 3 +- C) undefined, undefined, undefined +- D) 0, 0, 0 + +**Your answer:** ___ +A +--- + +### Question 6 +What is the output? +```javascript +let x = 1; +function outer() { + let x = 2; + function inner() { + x++; + console.log(x); + } + return inner; +} +const fn = outer(); +fn(); +fn(); +``` +- A) 2, 2 +- B) 3, 4 +- C) 2, 3 +- D) 1, 2 + +**Your answer:** ___ +C +--- + +## Section 3: Promises & Async + +### Question 7 +What order will be logged? +```javascript +console.log('1'); +setTimeout(() => console.log('2'), 0); +Promise.resolve().then(() => console.log('3')); +console.log('4'); +``` +- A) 1, 2, 3, 4 +- B) 1, 4, 2, 3 +- C) 1, 4, 3, 2 +- D) 1, 3, 4, 2 + +**Your answer:** ___ +C +--- + +### Question 8 +What happens here? +```javascript +async function foo() { + return 'hello'; +} +console.log(foo()); +``` +- A) "hello" +- B) Promise {: "hello"} +- C) Promise {} +- D) undefined + +**Your answer:** ___ +C +--- + +### Question 9 +What will be the output? +```javascript +Promise.resolve(1) + .then(x => x + 1) + .then(x => { throw new Error('error'); }) + .catch(() => 3) + .then(x => console.log(x)); +``` +- A) 1 +- B) 2 +- C) 3 +- D) Error is thrown + +**Your answer:** ___ +C +--- + +## Section 4: Modern ES6+ Features + +### Question 10 +What is logged? +```javascript +const obj = { a: 1, b: 2, a: 3 }; +console.log(obj.a); +``` +- A) 1 +- B) 2 +- C) 3 +- D) SyntaxError + +**Your answer:** ___ +A +--- + +### Question 11 +What is the result? +```javascript +const arr = [1, 2, 3]; +const [a, ...b, c] = arr; +console.log(b); +``` +- A) [2] +- B) [2, 3] +- C) [1, 2, 3] +- D) SyntaxError + +**Your answer:** ___ +B +--- + +### Question 12 +What gets logged? +```javascript +const obj = { x: 1 }; +const copy = { ...obj }; +copy.x = 2; +console.log(obj.x); +``` +- A) 1 +- B) 2 +- C) undefined +- D) ReferenceError + +**Your answer:** ___ +A +--- + +## Section 5: Objects & Prototypes + +### Question 13 +What is the output? +```javascript +const obj = Object.create(null); +console.log(obj.toString()); +``` +- A) "[object Object]" +- B) "null" +- C) undefined +- D) TypeError + +**Your answer:** ___ +C +--- + +### Question 14 +What will be logged? +```javascript +function Person(name) { + this.name = name; +} +Person.prototype.greet = function() { + return `Hello ${this.name}`; +}; +const p = new Person('Alice'); +console.log(p.hasOwnProperty('greet')); +``` +- A) true +- B) false +- C) undefined +- D) TypeError + +**Your answer:** ___ +A +--- + +### Question 15 +What is the result? +```javascript +class Animal { + constructor() { + this.type = 'animal'; + } +} +class Dog extends Animal { + constructor() { + this.breed = 'labrador'; + super(); + } +} +const dog = new Dog(); +``` +- A) dog.type is "animal" +- B) dog.breed is "labrador" +- C) ReferenceError +- D) Both properties are set correctly + +**Your answer:** ___ +D +--- + +## Section 6: Array Methods & Iteration + +### Question 16 +What is the output? +```javascript +const arr = [1, 2, 3, 4]; +const result = arr.map(x => x * 2).filter(x => x > 5); +console.log(result); +``` +- A) [6, 8] +- B) [3, 4] +- C) [2, 4, 6, 8] +- D) [6] + +**Your answer:** ___ +A +--- + +### Question 17 +What gets logged? +```javascript +[1, 2, 3].reduce((acc, val) => acc + val); +``` +- A) 6 +- B) "123" +- C) [1, 2, 3] +- D) undefined + +**Your answer:** ___ +A +--- + +### Question 18 +What is the result? +```javascript +const arr = [1, 2, 3]; +arr.forEach(x => { + if (x === 2) return; + console.log(x); +}); +``` +- A) 1, 3 +- B) 1 +- C) 3 +- D) Nothing is logged + +**Your answer:** ___ +A +--- + +## Section 7: Event Loop & Execution + +### Question 19 +What order will be logged? +```javascript +async function foo() { + console.log('1'); + await Promise.resolve(); + console.log('2'); +} +foo(); +console.log('3'); +``` +- A) 1, 2, 3 +- B) 1, 3, 2 +- C) 3, 1, 2 +- D) 2, 1, 3 + +**Your answer:** ___ +B +--- + +### Question 20 +What is the output? +```javascript +console.log(1); +queueMicrotask(() => console.log(2)); +Promise.resolve().then(() => console.log(3)); +console.log(4); +``` +- A) 1, 2, 3, 4 +- B) 1, 4, 2, 3 +- C) 1, 4, 3, 2 +- D) 1, 3, 2, 4 + +**Your answer:** ___ +B +--- + +## Section 8: Tricky Scenarios & Edge Cases + +### Question 21 +What will be logged? +```javascript +const a = [1, 2, 3]; +const b = [1, 2, 3]; +console.log(a == b); +``` +- A) true +- B) false +- C) undefined +- D) TypeError + +**Your answer:** ___ +A +--- + +### Question 22 +What is the result? +```javascript +console.log([] + []); +``` +- A) [] +- B) "" +- C) undefined +- D) "[object Array][object Array]" + +**Your answer:** ___ +B +--- + +### Question 23 +What gets logged? +```javascript +const obj = { + value: 42, + getValue: () => this.value +}; +console.log(obj.getValue()); +``` +- A) 42 +- B) undefined +- C) null +- D) ReferenceError + +**Your answer:** ___ +A +--- + +### Question 24 +What is the output? +```javascript +console.log(+'42'); +``` +- A) "42" +- B) 42 +- C) NaN +- D) undefined + +**Your answer:** ___ +B +--- + +### Question 25 +What will be logged? +```javascript +let x = y = 10; +(function() { + let x = y = 20; +})(); +console.log(y); +``` +- A) 10 +- B) 20 +- C) undefined +- D) ReferenceError + +**Your answer:** ___ +A +--- + +## Submission + +Fill in your answers and save this file, then run the evaluation script or notify your instructor. + +**Answer Key Format:** +``` +1: B +2: C +3: A +4: B +5: B +6: B +7: C +8: B +9: C +10: C +11: D +12: A +13: D +14: B +15: C +16: A +17: A +18: A +19: B +20: B +21: B +22: B +23: B +24: B +25: B +``` diff --git a/lessons/00/knowledge.md b/lessons/00/knowledge.md new file mode 100644 index 0000000..8232e07 --- /dev/null +++ b/lessons/00/knowledge.md @@ -0,0 +1,485 @@ +# Lesson 00: Getting Started & Assessment Review + +**Duration:** 45 minutes +**Objective:** Understand JavaScript fundamentals and identify key areas for focused study + +--- + +## Introduction + +Welcome to your JavaScript interview preparation curriculum! This lesson reviews the diagnostic assessment and establishes foundational knowledge that will be built upon in subsequent lessons. + +Based on common evaluation results, most developers need focused review in: +- Type coercion and equality +- Closures and scope +- The `this` keyword and context binding +- Prototypes and inheritance +- Modern ES6+ syntax +- Asynchronous execution patterns + +--- + +## Part 1: JavaScript Type System Fundamentals + +### 1.1 Primitive Types + +JavaScript has 7 primitive types: + +```javascript +typeof undefined; // "undefined" +typeof true; // "boolean" +typeof 42; // "number" +typeof 9007199254740991n; // "bigint" +typeof "hello"; // "string" +typeof Symbol(); // "symbol" +typeof null; // "object" ⚠️ This is a bug in JavaScript! +``` + +**The `null` Bug:** +`typeof null` returning `"object"` is a historical bug that can't be fixed without breaking existing code. `null` represents the intentional absence of any object value. + +```javascript +// Checking for null correctly +const value = null; +console.log(value === null); // true +console.log(typeof value === "object" && value === null); // true +``` + +### 1.2 Reference Types + +Objects, Arrays, and Functions are reference types: + +```javascript +typeof {}; // "object" +typeof []; // "object" (arrays are objects) +typeof function(){}; // "function" +``` + +**Key Difference:** +- **Primitives** are compared by value +- **References** are compared by reference (memory location) + +```javascript +// Primitives - value comparison +const a = 42; +const b = 42; +console.log(a === b); // true + +// References - memory location comparison +const arr1 = [1, 2, 3]; +const arr2 = [1, 2, 3]; +console.log(arr1 === arr2); // false (different objects in memory) +console.log(arr1 === arr1); // true (same reference) + +const arr3 = arr1; +console.log(arr3 === arr1); // true (same reference) +``` + +--- + +## Part 2: Floating-Point Precision + +### 2.1 The 0.1 + 0.2 Problem + +JavaScript uses IEEE 754 double-precision floating-point format. Some decimal numbers cannot be represented exactly in binary. + +```javascript +console.log(0.1 + 0.2); // 0.30000000000000004 +console.log(0.1 + 0.2 === 0.3); // false ⚠️ +``` + +**Why?** +- 0.1 in binary: `0.0001100110011...` (repeating) +- Computer must round, introducing tiny errors +- These errors accumulate during operations + +**Solutions:** + +```javascript +// 1. Use epsilon comparison +function areClose(a, b, epsilon = 0.0001) { + return Math.abs(a - b) < epsilon; +} +console.log(areClose(0.1 + 0.2, 0.3)); // true + +// 2. Use Number.EPSILON +console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true + +// 3. Work with integers (convert to cents, etc.) +const price1 = 10; // 10 cents +const price2 = 20; // 20 cents +const total = price1 + price2; // 30 cents (exact) + +// 4. Round to fixed decimals +const result = Math.round((0.1 + 0.2) * 100) / 100; // 0.3 +``` + +**Interview Tip:** Always mention this caveat when working with money or precise calculations. Suggest using integers or decimal libraries. + +--- + +## Part 3: Var, Let, and Const + +### 3.1 The Problem with `var` + +```javascript +// Function scope (not block scope) +function example() { + if (true) { + var x = 5; + } + console.log(x); // 5 (var leaks out of the block!) +} + +// Hoisting +console.log(y); // undefined (not an error!) +var y = 10; + +// What actually happens: +var y; +console.log(y); // undefined +y = 10; +``` + +**The Classic Loop Problem:** + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 100); +} +// Logs: 3, 3, 3 +// Why? All callbacks share the same 'i' variable +// By the time they execute, the loop finished and i = 3 +``` + +### 3.2 Let and Const (ES6+) + +```javascript +// Block scope +if (true) { + let x = 5; + const y = 10; +} +console.log(x); // ReferenceError +console.log(y); // ReferenceError + +// No hoisting issues +console.log(z); // ReferenceError (temporal dead zone) +let z = 15; + +// Loop with let creates a new binding per iteration +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 100); +} +// Logs: 0, 1, 2 ✅ +``` + +**Const Rules:** + +```javascript +const x = 10; +x = 20; // TypeError: Assignment to constant variable + +// But objects are mutable! +const obj = { name: "Alice" }; +obj.name = "Bob"; // ✅ Allowed (modifying property) +obj = {}; // ❌ TypeError (reassigning variable) + +// Use Object.freeze() for immutability +const frozen = Object.freeze({ name: "Alice" }); +frozen.name = "Bob"; // Silently fails (throws in strict mode) +console.log(frozen.name); // "Alice" +``` + +**Best Practice:** Use `const` by default, `let` when you need reassignment, avoid `var`. + +--- + +## Part 4: Array Behavior and Holes + +### 4.1 Sparse Arrays + +```javascript +const arr = [1, 2, 3]; +arr[10] = 11; + +console.log(arr.length); // 11 (not 4!) +console.log(arr); // [1, 2, 3, empty × 7, 11] +console.log(arr[5]); // undefined (hole in array) +``` + +**Array Length:** +- Length is always the highest index + 1 +- Creating holes doesn't initialize elements + +```javascript +const sparse = new Array(5); +console.log(sparse.length); // 5 +console.log(sparse[0]); // undefined +console.log(0 in sparse); // false (hole, not undefined value) + +const filled = [undefined, undefined]; +console.log(0 in filled); // true (actual undefined value) +``` + +**Array Methods and Holes:** + +```javascript +const arr = [1, , 3]; // Array with hole + +arr.forEach(x => console.log(x)); // 1, 3 (skips holes) +arr.map(x => x * 2); // [2, empty, 6] (preserves holes) +Array.from(arr); // [1, undefined, 3] (converts holes) +``` + +--- + +## Part 5: Type Coercion Essentials + +### 5.1 Truthy and Falsy Values + +**Falsy values** (8 total): +```javascript +if (false) {} // false +if (0) {} // 0 +if (-0) {} // -0 +if (0n) {} // 0n (BigInt zero) +if ("") {} // empty string +if (null) {} // null +if (undefined) {} // undefined +if (NaN) {} // NaN +``` + +Everything else is **truthy**, including: +```javascript +if ("0") {} // truthy (non-empty string) +if ("false") {} // truthy +if ([]) {} // truthy (empty array) +if ({}) {} // truthy (empty object) +if (function(){}) {} // truthy +``` + +### 5.2 Unary Plus Operator + +```javascript +console.log(+"42"); // 42 +console.log(+"3.14"); // 3.14 +console.log(+"hello"); // NaN +console.log(+true); // 1 +console.log(+false); // 0 +console.log(+null); // 0 +console.log(+undefined); // NaN + +// Quick number conversion +const input = "123"; +const num = +input; // Same as Number(input) +``` + +### 5.3 Addition Coercion + +```javascript +// String concatenation wins +console.log("" + 1 + 2); // "12" (1 converts to string first) +console.log(1 + 2 + ""); // "3" (addition happens first) +console.log("" + []); // "" (array becomes empty string) +console.log("" + {}); // "[object Object]" + +// Arrays +console.log([] + []); // "" (both arrays convert to empty strings) +console.log([1] + [2]); // "12" +console.log([1, 2] + [3]); // "1,23" +``` + +--- + +## Part 6: Essential Function Concepts + +### 6.1 Function Declarations vs Expressions + +```javascript +// Declaration - hoisted +foo(); // ✅ Works +function foo() { + console.log("I'm hoisted!"); +} + +// Expression - not hoisted +bar(); // ❌ ReferenceError +const bar = function() { + console.log("I'm not hoisted!"); +}; +``` + +### 6.2 Arrow Functions Preview + +Arrow functions have important differences (covered in Lesson 02): + +```javascript +// No 'this' binding +const obj = { + value: 42, + regularFunc: function() { + console.log(this.value); // 42 + }, + arrowFunc: () => { + console.log(this.value); // undefined (or global value) + } +}; + +obj.regularFunc(); // 42 +obj.arrowFunc(); // undefined +``` + +**Key Differences:** +- Arrow functions inherit `this` from outer scope +- Cannot be used as constructors +- No `arguments` object +- Cannot use `yield` (not generators) + +--- + +## Part 7: Common Interview Gotchas + +### 7.1 Object Property Duplicates + +```javascript +const obj = { a: 1, b: 2, a: 3 }; +console.log(obj.a); // 3 (last value wins) +``` + +In modern JavaScript, duplicate keys are allowed. The last value overwrites previous ones. + +### 7.2 Automatic Semicolon Insertion (ASI) + +```javascript +// This looks fine... +function getData() { + return + { + name: "Alice" + } +} +console.log(getData()); // undefined ⚠️ + +// JavaScript interprets it as: +function getData() { + return; // semicolon inserted! + { + name: "Alice" + } +} + +// Fix: Keep opening brace on same line +function getData() { + return { + name: "Alice" + }; +} +``` + +### 7.3 Implicit Global Variables + +```javascript +function oops() { + x = 10; // ⚠️ Creates global variable (no var/let/const) +} +oops(); +console.log(x); // 10 (global!) + +// Even worse: +let x = y = 10; +// This is really: let x = (y = 10) +// x is local, y is global! + +function example() { + let x = y = 20; +} +example(); +console.log(y); // 20 (global!) +``` + +**Fix:** Always use `"use strict";` and declare all variables. + +```javascript +"use strict"; +function safe() { + x = 10; // ReferenceError: x is not defined +} +``` + +--- + +## Part 8: Preparing for Deep Dive Topics + +### Topics Covered in Upcoming Lessons + +**Lesson 01 - Type System & Coercion:** +- Double equals vs triple equals +- Type conversion rules +- Advanced coercion scenarios + +**Lesson 02 - This Binding:** +- How `this` is determined +- Call, apply, and bind +- Arrow functions and `this` + +**Lesson 03 - Closures:** +- Lexical scope +- Practical closure patterns +- Memory implications + +**Lesson 04 - Event Loop:** +- Call stack, task queue, microtask queue +- Understanding async execution order + +**Lesson 05 - Promises:** +- Promise states and chaining +- Error handling +- Async/await patterns + +**Lesson 06 - Prototypes:** +- Prototype chain +- Constructor functions vs classes +- Inheritance patterns + +**Lesson 07 - ES6+ Features:** +- Destructuring +- Spread/rest operators +- Template literals, default parameters + +**Lesson 08 - Array Methods:** +- Map, filter, reduce +- ForEach vs for loops +- Functional programming concepts + +--- + +## Key Takeaways + +✅ **Remember:** +1. `typeof null` returns `"object"` (historical bug) +2. Never use `===` with floating-point decimals +3. `var` is function-scoped, `let`/`const` are block-scoped +4. Arrays are compared by reference, not value +5. Use `const` by default, `let` when needed, avoid `var` +6. Arrow functions don't have their own `this` binding +7. Array length = highest index + 1 +8. Always declare variables to avoid implicit globals + +--- + +## Practice Tips + +1. **Run code examples** - Don't just read them +2. **Predict output** before running code +3. **Understand "why"** - Memorization isn't enough +4. **Practice explaining** concepts out loud +5. **Focus on weak areas** identified in your evaluation + +--- + +## Next Steps + +Complete the medium-difficulty quiz to test your understanding of these fundamentals. Then proceed to Lesson 01 to dive deeper into the type system. + +**Time to complete quiz:** 10-15 minutes diff --git a/lessons/00/quiz-difficulty-medium.md b/lessons/00/quiz-difficulty-medium.md new file mode 100644 index 0000000..0ac816a --- /dev/null +++ b/lessons/00/quiz-difficulty-medium.md @@ -0,0 +1,421 @@ +# Lesson 00: Quiz - Medium Difficulty + +**Time:** 10-15 minutes +**Questions:** 12 +**Passing Score:** 9/12 (75%) + +--- + +## Instructions + +Choose the best answer for each question. After completing, check your answers at the bottom. + +--- + +### Question 1 +What is the output? +```javascript +const x = null; +const y = undefined; +console.log(typeof x === typeof y); +``` +- A) true +- B) false +- C) TypeError +- D) undefined + +**Your answer:** ___ + +--- + +### Question 2 +What will be logged? +```javascript +const a = [1, 2, 3]; +const b = a; +const c = [1, 2, 3]; +console.log(a === b, a === c); +``` +- A) true, true +- B) true, false +- C) false, true +- D) false, false + +**Your answer:** ___ + +--- + +### Question 3 +What is the result? +```javascript +const num1 = 0.1; +const num2 = 0.2; +const num3 = 0.3; +console.log(num1 + num2 === num3); +``` +- A) true +- B) false +- C) undefined +- D) NaN + +**Your answer:** ___ + +--- + +### Question 4 +What will be logged? +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 0); +} +``` +- A) 0, 1, 2 +- B) 3, 3, 3 +- C) 0, 0, 0 +- D) undefined, undefined, undefined + +**Your answer:** ___ + +--- + +### Question 5 +What is the output? +```javascript +const arr = [1, 2]; +arr[5] = 6; +console.log(arr.length, arr[3]); +``` +- A) 3, undefined +- B) 6, undefined +- C) 6, null +- D) 3, null + +**Your answer:** ___ + +--- + +### Question 6 +What gets logged? +```javascript +const value = +"123abc"; +console.log(value, typeof value); +``` +- A) 123, "number" +- B) "123abc", "string" +- C) NaN, "number" +- D) undefined, "undefined" + +**Your answer:** ___ + +--- + +### Question 7 +What is the result? +```javascript +console.log([] + []); +console.log({} + {}); +``` +- A) "", "[object Object][object Object]" +- B) [], {} +- C) "", {} +- D) undefined, undefined + +**Your answer:** ___ + +--- + +### Question 8 +What will be logged? +```javascript +function test() { + console.log(x); + let x = 10; +} +test(); +``` +- A) undefined +- B) 10 +- C) ReferenceError +- D) null + +**Your answer:** ___ + +--- + +### Question 9 +What is the output? +```javascript +const obj = { x: 1, y: 2, x: 3 }; +console.log(obj.x); +``` +- A) 1 +- B) 2 +- C) 3 +- D) SyntaxError + +**Your answer:** ___ + +--- + +### Question 10 +What gets logged? +```javascript +let x = y = 10; +function foo() { + let x = y = 20; +} +foo(); +console.log(y); +``` +- A) 10 +- B) 20 +- C) undefined +- D) ReferenceError + +**Your answer:** ___ + +--- + +### Question 11 +What is the result? +```javascript +const arr = new Array(3); +console.log(arr.length, arr[0], 0 in arr); +``` +- A) 3, undefined, true +- B) 3, undefined, false +- C) 0, undefined, false +- D) 3, null, false + +**Your answer:** ___ + +--- + +### Question 12 +What will be logged? +```javascript +function getData() { + return + { + value: 42 + }; +} +console.log(getData()); +``` +- A) { value: 42 } +- B) undefined +- C) 42 +- D) SyntaxError + +**Your answer:** ___ + +--- + +## Answer Key + +### Question 1: **B** - false +**Explanation:** `typeof null` returns `"object"` (a JavaScript bug), while `typeof undefined` returns `"undefined"`. Therefore `"object" === "undefined"` is false. + +```javascript +console.log(typeof null); // "object" +console.log(typeof undefined); // "undefined" +``` + +--- + +### Question 2: **B** - true, false +**Explanation:** +- `a === b` is true because `b` references the same array object as `a` +- `a === c` is false because `c` is a different array object in memory, even though it has the same values +- Arrays (and objects) are compared by reference, not by value + +```javascript +const a = [1, 2, 3]; +const b = a; // b points to same array +const c = [1, 2, 3]; // c is a new array +``` + +--- + +### Question 3: **B** - false +**Explanation:** Due to floating-point precision issues, `0.1 + 0.2` equals `0.30000000000000004`, not exactly `0.3`. Never use `===` to compare decimal numbers. Use epsilon comparison or `Number.EPSILON` instead. + +```javascript +console.log(0.1 + 0.2); // 0.30000000000000004 +console.log(Math.abs(0.1 + 0.2 - 0.3) < 0.0001); // true (correct way) +``` + +--- + +### Question 4: **B** - 3, 3, 3 +**Explanation:** With `var`, the variable `i` is function-scoped, not block-scoped. All three timeout callbacks share the same `i` variable. By the time they execute (after the loop completes), `i` has the value 3. + +**Fix with `let`:** +```javascript +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 0); // 0, 1, 2 +} +// `let` creates a new binding for each iteration +``` + +--- + +### Question 5: **B** - 6, undefined +**Explanation:** +- Array length is always the highest index + 1 +- Setting `arr[5] = 6` makes the length 6 +- Indices 2, 3, 4 are "holes" (empty slots) +- Accessing a hole returns `undefined` + +```javascript +const arr = [1, 2]; +arr[5] = 6; +console.log(arr); // [1, 2, empty × 3, 6] +``` + +--- + +### Question 6: **C** - NaN, "number" +**Explanation:** The unary plus operator (`+`) attempts to convert the value to a number. `"123abc"` cannot be converted to a valid number, so it results in `NaN` (Not a Number). Importantly, `NaN` has type `"number"`. + +```javascript +console.log(+"123"); // 123 +console.log(+"hello"); // NaN +console.log(typeof NaN); // "number" +``` + +--- + +### Question 7: **A** - "", "[object Object][object Object]" +**Explanation:** +- Empty arrays convert to empty strings: `[] + []` → `"" + ""` → `""` +- Objects convert to `"[object Object]"`: `{} + {}` → `"[object Object][object Object]"` +- The `+` operator performs string concatenation when either operand is a string + +**Note:** In some contexts (like at the start of a statement), `{}` might be interpreted as a code block, giving different results. + +--- + +### Question 8: **C** - ReferenceError +**Explanation:** Variables declared with `let` and `const` are in the "temporal dead zone" from the start of the block until the declaration is executed. Accessing them before the declaration line throws a `ReferenceError`, not `undefined` like with `var`. + +```javascript +// With var (hoisted): +function test() { + console.log(x); // undefined + var x = 10; +} + +// With let (TDZ): +function test() { + console.log(x); // ReferenceError + let x = 10; +} +``` + +--- + +### Question 9: **C** - 3 +**Explanation:** When an object has duplicate keys, the last value wins. There's no error—the property is simply overwritten. `obj.x` will be `3`. + +```javascript +const obj = { a: 1, a: 2, a: 3 }; +console.log(obj.a); // 3 +``` + +--- + +### Question 10: **B** - 20 +**Explanation:** The expression `let x = y = 20` is evaluated as `let x = (y = 20)`. The `y = 20` part is an assignment without a declaration, creating (or modifying) a global variable `y`. Inside the function, `x` is local, but `y` becomes global. + +```javascript +let x = y = 10; // x is local to outer scope, y is GLOBAL +function foo() { + let x = y = 20; // x is local to foo, y is GLOBAL (modified) +} +foo(); +console.log(y); // 20 (global y was changed) +console.log(x); // 10 (outer x unaffected) +``` + +**Fix:** Always declare variables explicitly: +```javascript +let x = 10, y = 10; +``` + +--- + +### Question 11: **B** - 3, undefined, false +**Explanation:** +- `new Array(3)` creates an array with length 3 but no elements (all holes) +- `arr[0]` returns `undefined` (accessing a hole) +- `0 in arr` returns `false` because index 0 doesn't actually exist (it's a hole, not a slot containing `undefined`) + +```javascript +const arr1 = new Array(3); +const arr2 = [undefined, undefined, undefined]; + +console.log(0 in arr1); // false (hole) +console.log(0 in arr2); // true (actual value) +``` + +--- + +### Question 12: **B** - undefined +**Explanation:** Automatic Semicolon Insertion (ASI) adds a semicolon after `return`, making it `return;`. The object literal on the next line becomes unreachable code. The function returns `undefined`. + +**What JavaScript sees:** +```javascript +function getData() { + return; // semicolon inserted! + { + value: 42 + }; +} +``` + +**Fix:** Keep the opening brace on the same line: +```javascript +function getData() { + return { + value: 42 + }; +} +``` + +--- + +## Scoring Guide + +- **11-12 correct (90%+):** Excellent! You have a strong grasp of JavaScript fundamentals. +- **9-10 correct (75-83%):** Good understanding. Review missed concepts before proceeding. +- **7-8 correct (58-67%):** Fair. Review this lesson's knowledge.md carefully. +- **Below 7 (< 58%):** Need more practice. Re-read the knowledge section and practice with code examples. + +--- + +## Common Mistakes to Review + +If you missed these questions, focus on these topics: + +- **Q1, Q6:** Type system and `typeof` operator +- **Q2:** Reference vs value comparison +- **Q3:** Floating-point precision +- **Q4, Q8:** `var` vs `let` differences and hoisting +- **Q5, Q11:** Array holes and length behavior +- **Q7:** Type coercion with operators +- **Q9, Q12:** JavaScript quirks (duplicate keys, ASI) +- **Q10:** Implicit global variables + +--- + +## Ready for the Next Lesson? + +If you scored 9 or higher, you're ready to proceed to **Lesson 01: Type System & Coercion**. + +If you scored below 9, consider: +1. Re-reading the sections you struggled with in knowledge.md +2. Running the code examples yourself +3. Retaking this quiz + +**Remember:** Understanding these fundamentals is crucial for the more advanced topics ahead!