0% found this document useful (0 votes)
3 views42 pages

Javascript

The document is a comprehensive guide to JavaScript, covering topics from ES6+ fundamentals to advanced concepts like closures, promises, and async/await. It includes practical examples, best practices, and modern features, aiming to help developers master JavaScript for building better applications. The guide is structured with chapters and sections that facilitate learning for both beginners and advanced users.

Uploaded by

auriol429
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views42 pages

Javascript

The document is a comprehensive guide to JavaScript, covering topics from ES6+ fundamentals to advanced concepts like closures, promises, and async/await. It includes practical examples, best practices, and modern features, aiming to help developers master JavaScript for building better applications. The guide is structured with chapters and sections that facilitate learning for both beginners and advanced users.

Uploaded by

auriol429
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript:

The Complete Guide


From ES6+ Fundamentals to Advanced Mastery

==================================================
| JAVASCRIPT GUIDE |
| ES6+ • Closures • Promises • Async/Await |
| DOM Manipulation • Modern JS |
==================================================

Powered by Dark Code

Dark Code Team


Master JavaScript, Build Better Apps
JavaScript Complete Guide

Version 2.0 • 2026• ES6 - ES2025

“JavaScript is the duct tape of the internet. Learn it well, and you can build
anything.”

— Charlie Campbell

2
Contents

1 Introduction to Modern JavaScript 5


1.1 Why JavaScript? The Language of the Web . . . . . . . . . . . . . . . . . . 5
1.1.1 The Evolution of JavaScript . . . . . . . . . . . . . . . . . . . . . . . 5
1.1.2 Your First Modern JavaScript Program . . . . . . . . . . . . . . . . . 5
1.2 Setting Up Your Development Environment . . . . . . . . . . . . . . . . . . 6

2 ES6+ Fundamentals: The Modern Foundation 7


2.1 let, const, and Block Scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Arrow Functions: The Concise Syntax . . . . . . . . . . . . . . . . . . . . . 8
2.3 Template Literals: Enhanced Strings . . . . . . . . . . . . . . . . . . . . . . 9
2.4 Destructuring Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 Spread and Rest Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3 Closures and Scope 12


3.1 Understanding Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2 Closure Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.3 IIFE (Immediately Invoked Function Expression) . . . . . . . . . . . . . . . 15

4 Promises: Managing Async Operations 17


4.1 Understanding Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.2 Promise Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.3 Promise Combinators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

5 Async/Await: The Modern Way 21


5.1 Async/Await Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2 Advanced Async Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

6 DOM Manipulation Mastery 25


6.1 Selecting Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3
CONTENTS JavaScript Complete Guide

6.2 Manipulating Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


6.3 Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

7 Practical Project: Todo Application 29

8 Best Practices and Modern Features 34


8.1 Code Quality Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
8.2 Modern JavaScript Features (ES2020-ES2025) . . . . . . . . . . . . . . . . . 35
8.3 Performance Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

A JavaScript Quick Reference 39


A.1 Common Patterns Cheatsheet . . . . . . . . . . . . . . . . . . . . . . . . . . 39
A.2 Array Methods Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
A.3 Promise Methods Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
A.4 Console Methods for Debugging . . . . . . . . . . . . . . . . . . . . . . . . . 40

4
1 Introduction to Modern JavaScript

1.1 Why JavaScript? The Language of the Web


JavaScript has evolved from a simple browser scripting language to the most popular pro-
gramming language in the world. As of 2026, JavaScript runs on every major platform, from
browsers to servers, mobile devices to embedded systems.

Important
JavaScript is no longer just a frontend language. With [Link], Deno, and Bun, you
can build full-stack applications using a single language!

1.1.1 The Evolution of JavaScript


JavaScript’s journey from its creation in 1995 to today is remarkable:

• 1995: Brendan Eich creates JavaScript in 10 days

• 1997: ECMAScript 1 standardization

• 2009: ES5 released with strict mode and JSON support

• 2015: ES6 (ECMAScript 2015) - The biggest update ever!

• 2016-2025: Annual updates adding modern features

1.1.2 Your First Modern JavaScript Program

1 // Using modern syntax


2 const greeting = ( name = " World ") = > {
3 return ‘ Hello , $ { name }! Welcome to Modern JavaScript ! ‘;
4 };
5

5
CHAPTER 1. INTRODUCTION TO MODERN JAVASCRIPT
JavaScript Complete Guide

6 // Arrow functions with implicit return


7 const double = x = > x * 2;
8

9 // Template literals for multi - line strings


10 const message = ‘
11 =================================
12 JavaScript Complete Guide
13 From Beginner to Advanced
14 Powered by Dark Code
15 =================================
16 ‘;
17

18 console . log ( greeting (" Developer ") ) ;


19 console . log ( double (21) ) ;
20 console . log ( message ) ;

Listing 1.1: Hello

Console Output
Hello, Developer! Welcome to Modern JavaScript! 42
================================= JavaScript Complete
Guide From Beginner to Advanced Powered by Dark Code
=================================

1.2 Setting Up Your Development Environment


Pro Tip
Use VS Code with these extensions for the best JavaScript experience:

• ESLint - Catch errors instantly

• Prettier - Format code automatically

• JavaScript (ES6) code snippets

• [Link] - Live code execution

6
2 ES6+ Fundamentals: The Modern
Foundation

2.1 let, const, and Block Scoping


One of the most significant improvements in ES6 was the introduction of let and const,
which provide block-level scoping.
1 // var : function - scoped , can be redeclared
2 var oldWay = "I ’ m old ";
3 var oldWay = "I ’ m still here "; // No error
4

5 // let : block - scoped , can be reassigned


6 let modern = "I ’ m modern ";
7 modern = "I ’ ve changed "; // OK
8 // let modern = " Error !"; // Cannot redeclare
9

10 // const : block - scoped , cannot be reassigned


11 const constant = " I never change ";
12 // constant = " Error !"; // Cannot reassign
13

14 // Block scoping in action


15 if ( true ) {
16 let blockScoped = " Only in this block ";
17 var functionScoped = " Available outside ";
18 }
19 console . log ( functionScoped ) ; // Works
20 // console . log ( blockScoped ) ; // ReferenceError
21

22 // Real - world example : Loop scoping


23 for ( let i = 0; i < 3; i ++) {
24 setTimeout (() = > console . log ( ‘ let : $ { i } ‘) , 100) ;
25 }
26 // Output : let : 0 , let : 1 , let : 2

7
CHAPTER 2. ES6+ FUNDAMENTALS: THE MODERN FOUNDATION
JavaScript Complete Guide

27

28 for ( var i = 0; i < 3; i ++) {


29 setTimeout (() = > console . log ( ‘ var : $ { i } ‘) , 100) ;
30 }
31 // Output : var : 3 , var : 3 , var : 3 ( closure issue !)

Listing 2.1: Understanding Variable Declarations

Important
Always prefer const by default. Use let only when you know the variable needs to
be reassigned. Never use var in modern JavaScript!

2.2 Arrow Functions: The Concise Syntax


Arrow functions provide a shorter syntax and lexically bind the this value.
1 // Traditional function
2 function add (a , b ) {
3 return a + b ;
4 }
5

6 // Arrow function variations


7 const add1 = (a , b ) = > a + b ; // Implicit return
8 const add2 = a = > a * 2; // Single parameter : no parentheses
9 const add3 = () = > 42; // No parameters : empty parentheses
10 const add4 = (a , b ) = > { // Block body : explicit return
11 const result = a + b ;
12 return result ;
13 };
14

15 // Lexical ’ this ’ binding - The game changer !


16 const obj = {
17 name : " Modern JS " ,
18 traditional : function () {
19 setTimeout ( function () {
20 console . log ( this . name ) ; // undefined ( wrong this !)
21 } , 100) ;
22 },
23 arrow : function () {
24 setTimeout (() = > {
25 console . log ( this . name ) ; // " Modern JS " ( correct !)
26 } , 100) ;

8
CHAPTER 2. ES6+ FUNDAMENTALS: THE MODERN FOUNDATION
JavaScript Complete Guide

27 }
28 };
29

30 obj . traditional () ; // undefined


31 obj . arrow () ; // " Modern JS "
32

33 // When NOT to use arrow functions


34 const calculator = {
35 value : 0 ,
36 // Don ’ t use arrow for methods needing ’ this ’
37 add : ( x ) = > { this . value += x ; } , // Won ’ t work !
38 // Use traditional function for methods
39 subtract ( x ) { this . value -= x ; } // Works !
40 };

Listing 2.2: Arrow Functions Deep Dive

2.3 Template Literals: Enhanced Strings


Template literals revolutionize string handling in JavaScript.
1 const name = " Dark Code ";
2 const year = 2026;
3 const rating = 4.9;
4

5 // String interpolation
6 const message = ‘ Welcome to $ { name } ( est . $ { year }) with $ { rating } star
rating ! ‘;
7 console . log ( message ) ;
8

9 // Multi - line strings without hacks


10 const html = ‘
11 < div class =" card " >
12 <h2 > $ { name } </ h2 >
13 <p > Year : $ { year } </p >
14 <p > Rating : $ { ’* ’. repeat ( Math . floor ( rating ) ) } </p >
15 </ div >
16 ‘;
17

18 // Tagged templates ( advanced )


19 function highlight ( strings , ... values ) {
20 return strings . reduce (( result , str , i ) = > {
21 return result + str + ( values [ i ] ? ‘[ $ { values [ i ]}] ‘ : ’ ’) ;

9
CHAPTER 2. ES6+ FUNDAMENTALS: THE MODERN FOUNDATION
JavaScript Complete Guide

22 } , ’ ’) ;
23 }
24

25 const language = " JavaScript ";


26 const version = " ES6 ";
27 const tagged = highlight ‘ Learning $ { language } $ { version } is fun ! ‘;
28 // " Learning [ JavaScript ] [ ES6 ] is fun !"

Listing 2.3: Template Literals Mastery

2.4 Destructuring Assignment


Destructuring allows you to extract values from objects and arrays easily.
1 // Array destructuring
2 const numbers = [1 , 2 , 3 , 4 , 5];
3 const [ first , second , ... rest ] = numbers ;
4 console . log ( first ) ; // 1
5 console . log ( second ) ; // 2
6 console . log ( rest ) ; // [3 , 4 , 5]
7

8 // Swapping variables
9 let a = 5 , b = 10;
10 [a , b ] = [b , a ];
11 console . log (a , b ) ; // 10 , 5
12

13 // Object destructuring
14 const user = {
15 name : " John " ,
16 age : 30 ,
17 address : {
18 city : " New York " ,
19 zip : "10001"
20 }
21 };
22

23 const { name , age } = user ;


24 const { address : { city } } = user ;
25 console . log ( name , age , city ) ; // John 30 New York
26

27 // Default values
28 const { country = " USA " } = user ;
29 console . log ( country ) ; // USA

10
CHAPTER 2. ES6+ FUNDAMENTALS: THE MODERN FOUNDATION
JavaScript Complete Guide

30

31 // Renaming
32 const { name : userName } = user ;
33 console . log ( userName ) ; // John

Listing 2.4: Destructuring Patterns

2.5 Spread and Rest Operators


The spread (...) and rest (...) operators are incredibly versatile.
1 // Spread operator with arrays
2 const arr1 = [1 , 2 , 3];
3 const arr2 = [4 , 5 , 6];
4 const combined = [... arr1 , ... arr2 ]; // [1 ,2 ,3 ,4 ,5 ,6]
5 const copy = [... arr1 ]; // Shallow copy
6

7 // Spread with objects


8 const obj1 = { a : 1 , b : 2 };
9 const obj2 = { c : 3 , d : 4 };
10 const merged = { ... obj1 , ... obj2 }; // { a :1 , b :2 , c :3 , d :4 }
11

12 // Rest parameters ( function arguments )


13 function sum (... numbers ) {
14 return numbers . reduce (( acc , n ) = > acc + n , 0) ;
15 }
16 console . log ( sum (1 , 2 , 3 , 4) ) ; // 10
17

18 // Rest in destructuring
19 const [ firstNum , secondNum , ... remaining ] = [10 , 20 , 30 , 40 , 50];
20 console . log ( firstNum , secondNum , remaining ) ; // 10 20 [30 ,40 ,50]

Listing 2.5: Spread and Rest Operators

11
3 Closures and Scope

3.1 Understanding Closures


A closure is a function that remembers its lexical scope even when the function is executed
outside that scope.
1 // Basic closure example
2 function outerFunction ( outerVariable ) {
3 return function innerFunction ( innerVariable ) {
4 console . log ( ‘ Outer : $ { outerVariable } ‘) ;
5 console . log ( ‘ Inner : $ { innerVariable } ‘) ;
6 };
7 }
8

9 const newFunction = outerFunction (" outside ") ;


10 newFunction (" inside ") ;
11 // Output : Outer : outside
12 // Inner : inside
13

14 // Practical example : Counter


15 function createCounter () {
16 let count = 0;
17 return {
18 increment : function () { count ++; } ,
19 decrement : function () { count - -; } ,
20 getCount : function () { return count ; }
21 };
22 }
23

24 const counter = createCounter () ;


25 counter . increment () ;
26 counter . increment () ;
27 console . log ( counter . getCount () ) ; // 2
28 counter . decrement () ;

12
CHAPTER 3. CLOSURES AND SCOPE JavaScript Complete Guide

29 console . log ( counter . getCount () ) ; // 1


30

31 // Private variables using closure


32 function cre ateBa nkAcco unt ( initialBalance ) {
33 let balance = initialBalance ;
34

35 return {
36 deposit ( amount ) {
37 if ( amount > 0) {
38 balance += amount ;
39 return ‘ Deposited $ { amount }. New balance : $ { balance } ‘;
40 }
41 },
42 withdraw ( amount ) {
43 if ( amount <= balance ) {
44 balance -= amount ;
45 return ‘ Withdrew $ { amount }. New balance : $ { balance } ‘;
46 }
47 return " Insufficient funds !";
48 },
49 getBalance () {
50 return balance ;
51 }
52 };
53 }
54

55 const myAccount = cre ateBa nkAcco unt (100) ;


56 console . log ( myAccount . deposit (50) ) ; // Deposited 50. New balance : 150
57 console . log ( myAccount . withdraw (30) ) ; // Withdrew 30. New balance : 120
58 console . log ( myAccount . balance ) ; // undefined ( private !)

Listing 3.1: Closure Fundamentals

3.2 Closure Use Cases


1 // Function factories
2 function multiplyBy ( factor ) {
3 return function ( number ) {
4 return number * factor ;
5 };
6 }
7

13
CHAPTER 3. CLOSURES AND SCOPE JavaScript Complete Guide

8 const double = multiplyBy (2) ;


9 const triple = multiplyBy (3) ;
10 console . log ( double (5) ) ; // 10
11 console . log ( triple (5) ) ; // 15
12

13 // Event handlers with preserved state


14 function c r e a t e B u t t o n C l i c k H a n d l e r ( message ) {
15 return function () {
16 console . log ( ‘ Button clicked : $ { message } ‘) ;
17 };
18 }
19

20 const button = document . querySelector ( ’# myButton ’) ;


21 button . addEventListener ( ’ click ’ , c r e a t e B u t t o n C l i c k H a n d l e r ( ’ Hello ! ’) ) ;
22

23 // Once function ( runs only once )


24 function once ( fn ) {
25 let hasRun = false ;
26 let result ;
27 return function (... args ) {
28 if (! hasRun ) {
29 result = fn (... args ) ;
30 hasRun = true ;
31 }
32 return result ;
33 };
34 }
35

36 const initialize = once (() = > {


37 console . log (" Initializing ...") ;
38 return { status : " ready " };
39 }) ;
40

41 console . log ( initialize () ) ; // Initializing ... { status : " ready " }


42 console . log ( initialize () ) ; // { status : " ready " } ( no second log )
43

44 // Memoization with closures


45 function memoize ( fn ) {
46 const cache = {};
47 return function (... args ) {
48 const key = JSON . stringify ( args ) ;
49 if ( cache [ key ] === undefined ) {
50 cache [ key ] = fn (... args ) ;

14
CHAPTER 3. CLOSURES AND SCOPE JavaScript Complete Guide

51 }
52 return cache [ key ];
53 };
54 }
55

56 const exp ensive Funct ion = ( n ) = > {


57 console . log ( ‘ Computing $ { n }... ‘) ;
58 return n * n ;
59 };
60

61 const memoized = memoize ( ex pensiv eFunct ion ) ;


62 console . log ( memoized (5) ) ; // Computing 5... 25
63 console . log ( memoized (5) ) ; // 25 ( from cache , no log )

Listing 3.2: Practical Closure Patterns

3.3 IIFE (Immediately Invoked Function Expression)


1 // Basic IIFE
2 ( function () {
3 console . log (" IIFE runs immediately !") ;
4 }) () ;
5

6 // IIFE with parameters


7 ( function ( name ) {
8 console . log ( ‘ Hello , $ { name }! ‘) ;
9 }) (" John ") ;
10

11 // Module pattern using IIFE


12 const module = ( function () {
13 // Private variables
14 let privateVar = "I ’ m private ";
15

16 // Private function
17 function privateMethod () {
18 console . log ( privateVar ) ;
19 }
20

21 // Public API
22 return {
23 publicMethod : function () {
24 privateMethod () ;

15
CHAPTER 3. CLOSURES AND SCOPE JavaScript Complete Guide

25 },
26 setPrivateVar : function ( value ) {
27 privateVar = value ;
28 }
29 };
30 }) () ;
31

32 module . publicMethod () ; // I ’ m private


33 module . setPrivateVar (" New value ") ;
34 module . publicMethod () ; // New value
35 console . log ( module . privateVar ) ; // undefined
36

37 // Arrow function IIFE


38 (() = > {
39 console . log (" Arrow IIFE !") ;
40 }) () ;
41

42 // Async IIFE
43 ( async () = > {
44 const data = await fetch ( ’/ api / data ’) ;
45 console . log ( data ) ;
46 }) () ;

Listing 3.3: IIFE Patterns

Pro Tip
Closures are powerful but can cause memory leaks if not used carefully. Variables in
closures stay in memory as long as the closure exists. Clean up references when no
longer needed!

16
4 Promises: Managing Async Opera-
tions

4.1 Understanding Promises


A Promise represents a value that may not be available yet.
1 // Promise states : pending -> fulfilled OR rejected
2

3 // Creating Promises
4 const myPromise = new Promise (( resolve , reject ) = > {
5 // Async operation
6 const success = true ;
7

8 if ( success ) {
9 resolve (" Operation successful !") ;
10 } else {
11 reject ( new Error (" Operation failed !") ) ;
12 }
13 }) ;
14

15 // Promise methods
16 myPromise
17 . then ( result = > {
18 console . log (" Success :" , result ) ;
19 return result . toUpperCase () ;
20 })
21 . then ( upperResult = > {
22 console . log (" Transformed :" , upperResult ) ;
23 })
24 . catch ( error = > {
25 console . error (" Error :" , error . message ) ;
26 })
27 . finally (() = > {

17
CHAPTER 4. PROMISES: MANAGING ASYNC OPERATIONS
JavaScript Complete Guide

28 console . log (" This always runs ") ;


29 }) ;
30

31 // Promise . resolve () and Promise . reject ()


32 const resolvedPromise = Promise . resolve (42) ;
33 const rejectedPromise = Promise . reject ( new Error (" Boom !") ) ;
34

35 // Real - world : Fetch API ( returns a Promise )


36 fetch ( ’ https :// api . github . com / users / darkcode ’)
37 . then ( response = > {
38 if (! response . ok ) {
39 throw new Error ( ‘ HTTP error ! status : $ { response . status } ‘) ;
40 }
41 return response . json () ;
42 })
43 . then ( data = > {
44 console . log (" User :" , data . login ) ;
45 console . log (" Repos :" , data . public_repos ) ;
46 })
47 . catch ( error = > {
48 console . error (" Fetch failed :" , error ) ;
49 }) ;

Listing 4.1: Promise States and Methods

4.2 Promise Chaining


Promises can be chained to handle sequential asynchronous operations.
1 // Sequential async operations
2 function getUser ( id ) {
3 return fetch ( ‘/ api / users / $ { id } ‘) . then ( r = > r . json () ) ;
4 }
5

6 function getPosts ( userId ) {


7 return fetch ( ‘/ api / posts ? userId = $ { userId } ‘) . then ( r = > r . json () ) ;
8 }
9

10 function getComments ( postId ) {


11 return fetch ( ‘/ api / comments ? postId = $ { postId } ‘) . then ( r = > r . json () ) ;
12 }
13

14 // Chaining promises

18
CHAPTER 4. PROMISES: MANAGING ASYNC OPERATIONS
JavaScript Complete Guide

15 getUser (1)
16 . then ( user = > {
17 console . log (" User :" , user . name ) ;
18 return getPosts ( user . id ) ;
19 })
20 . then ( posts = > {
21 console . log ( ‘ Found $ { posts . length } posts ‘) ;
22 return getComments ( posts [0]. id ) ;
23 })
24 . then ( comments = > {
25 console . log ( ‘ Found $ { comments . length } comments ‘) ;
26 })
27 . catch ( error = > {
28 console . error (" Something went wrong :" , error ) ;
29 }) ;

Listing 4.2: Promise Chaining

4.3 Promise Combinators


JavaScript provides powerful methods for working with multiple promises.
1 // Promise . all - Wait for all promises to resolve
2 const promise1 = Promise . resolve (3) ;
3 const promise2 = 42;
4 const promise3 = new Promise (( resolve ) = > {
5 setTimeout ( resolve , 100 , ’foo ’) ;
6 }) ;
7

8 Promise . all ([ promise1 , promise2 , promise3 ]) . then (( values ) = > {


9 console . log ( values ) ; // [3 , 42 , " foo "]
10 }) ;
11

12 // Promise . allSettled - Wait for all to complete ( resolve or reject )


13 Promise . allSettled ([
14 Promise . resolve (1) ,
15 Promise . reject ( new Error (" Failed ") ) ,
16 Promise . resolve (3)
17 ]) . then ( results = > {
18 results . forEach ( result = > {
19 if ( result . status === ’ fulfilled ’) {
20 console . log ( ’ Success : ’ , result . value ) ;
21 } else {

19
CHAPTER 4. PROMISES: MANAGING ASYNC OPERATIONS
JavaScript Complete Guide

22 console . log ( ’ Error : ’ , result . reason ) ;


23 }
24 }) ;
25 }) ;
26

27 // Promise . race - Returns first promise that settles


28 const timeout = new Promise (( _ , reject ) = >
29 setTimeout (() = > reject ( new Error (" Timeout !") ) , 5000)
30 );
31 const data = fetch ( ’/ api / data ’) . then ( r = > r . json () ) ;
32 Promise . race ([ data , timeout ])
33 . then ( result = > console . log (" Data loaded :" , result ) )
34 . catch ( error = > console . error (" Timeout or error :" , error ) ) ;
35

36 // Promise . any - Returns first fulfilled promise ( ignores rejections )


37 const p1 = Promise . reject (" Error 1") ;
38 const p2 = Promise . resolve (" Success !") ;
39 const p3 = Promise . resolve (" Another success ") ;
40

41 Promise . any ([ p1 , p2 , p3 ])
42 . then ( value = > console . log ( value ) ) // " Success !"
43 . catch ( error = > console . log (" All promises rejected ") ) ;

Listing 4.3: [Link]

20
5 Async/Await: The Modern Way

5.1 Async/Await Syntax


Async/await makes asynchronous code look synchronous.

1 // Basic async function


2 async function fetchUser ( id ) {
3 try {
4 const response = await fetch ( ‘/ api / users / $ { id } ‘) ;
5 const user = await response . json () ;
6 return user ;
7 } catch ( error ) {
8 console . error (" Failed to fetch user :" , error ) ;
9 throw error ;
10 }
11 }
12

13 // Using async / await


14 async function displayUserInfo ( id ) {
15 try {
16 const user = await fetchUser ( id ) ;
17 console . log ( ‘ User : $ { user . name } ‘) ;
18 console . log ( ‘ Email : $ { user . email } ‘) ;
19 } catch ( error ) {
20 console . log (" Could not load user info ") ;
21 }
22 }
23

24 // Sequential vs Parallel execution


25 async function sequential () {
26 const user = await fetchUser (1) ;
27 const posts = await fetchPosts ( user . id ) ;
28 return posts ;
29 }

21
CHAPTER 5. ASYNC/AWAIT: THE MODERN WAY JavaScript Complete Guide

30

31 async function parallel () {


32 const [ user , posts ] = await Promise . all ([
33 fetchUser (1) ,
34 fetchPosts (1)
35 ]) ;
36 return { user , posts };
37 }
38

39 // Error handling patterns


40 async function robustFetch ( url ) {
41 try {
42 const response = await fetch ( url ) ;
43 if (! response . ok ) {
44 throw new Error ( ‘ HTTP $ { response . status }: $ { response .
statusText } ‘) ;
45 }
46 return await response . json () ;
47 } catch ( error ) {
48 if ( error . name === ’ TypeError ’) {
49 console . error ( ’ Network error - check your connection ’) ;
50 } else {
51 console . error ( ’ Fetch error : ’ , error . message ) ;
52 }
53 return null ;
54 }
55 }
56

57 // Async / Await with loops


58 async function processItems ( items ) {
59 for ( const item of items ) {
60 await processItem ( item ) ; // Sequential
61 }
62 }
63

64 async function p r o c e s s I t e m s P a r a l l e l ( items ) {


65 const promises = items . map ( item = > processItem ( item ) ) ;
66 await Promise . all ( promises ) ; // Parallel
67 }

Listing 5.1: Async/Await Syntax and Patterns

22
CHAPTER 5. ASYNC/AWAIT: THE MODERN WAY JavaScript Complete Guide

5.2 Advanced Async Patterns

1 // Retry logic with async / await


2 async function fetchWithRetry ( url , maxRetries = 3 , delay = 1000) {
3 for ( let i = 0; i < maxRetries ; i ++) {
4 try {
5 const response = await fetch ( url ) ;
6 if ( response . ok ) {
7 return await response . json () ;
8 }
9 } catch ( error ) {
10 if ( i === maxRetries - 1) throw error ;
11 await new Promise ( resolve = > setTimeout ( resolve , delay * Math .
pow (2 , i ) ) ) ;
12 }
13 }
14 }
15

16 // Timeout with async / await


17 function timeout ( ms ) {
18 return new Promise (( _ , reject ) = >
19 setTimeout (() = > reject ( new Error ( ‘ Timeout after $ { ms } ms ‘) ) , ms )
20 );
21 }
22

23 async function fetchWithTimeout ( url , ms = 5000) {


24 const controller = new AbortController () ;
25 const timeoutId = setTimeout (() = > controller . abort () , ms ) ;
26

27 try {
28 const response = await fetch ( url , { signal : controller . signal }) ;
29 clearTimeout ( timeoutId ) ;
30 return await response . json () ;
31 } catch ( error ) {
32 clearTimeout ( timeoutId ) ;
33 throw error ;
34 }
35 }
36

37 // Debounce with async / await


38 function debounce ( fn , delay ) {
39 let timeoutId ;
40 return function (... args ) {

23
CHAPTER 5. ASYNC/AWAIT: THE MODERN WAY JavaScript Complete Guide

41 clearTimeout ( timeoutId ) ;
42 return new Promise (( resolve ) = > {
43 timeoutId = setTimeout ( async () = > {
44 const result = await fn (... args ) ;
45 resolve ( result ) ;
46 } , delay ) ;
47 }) ;
48 };
49 }
50

51 // Throttle with async / await


52 function throttle ( fn , limit ) {
53 let inThrottle ;
54 return function (... args ) {
55 if (! inThrottle ) {
56 fn (... args ) ;
57 inThrottle = true ;
58 setTimeout (() = > inThrottle = false , limit ) ;
59 }
60 };
61 }

Listing 5.2: Advanced Async Patterns

Pro Tip
Always use try/catch with async/await for proper error handling. For concurrent
operations, use [Link]() but remember: if one promise fails, all fail. Use
[Link]() when you need all results regardless of failures.

24
6 DOM Manipulation Mastery

6.1 Selecting Elements


Modern DOM selection methods are powerful and flexible.

1 // Modern selection methods


2 // By ID
3 const header = document . getElementById ( ’ main - header ’) ;
4 const header2 = document . querySelector ( ’# main - header ’) ;
5

6 // By class
7 const items = document . g e t E l e m e n t s B y C l a s s N a m e ( ’ item ’) ;
8 const items2 = document . querySelectorAll ( ’. item ’) ;
9

10 // By tag
11 const divs = document . g e t E le m e n t s B y T a g N a m e ( ’ div ’) ;
12 const divs2 = document . querySelectorAll ( ’ div ’) ;
13

14 // CSS Selectors ( most powerful )


15 const firstButton = document . querySelector ( ’. container button : first - child
’) ;
16 const allInputs = document . querySelectorAll ( ’ input [ type =" text "] ’) ;
17 const form = document . querySelector ( ’# contact - form ’) ;
18

19 // Collection iteration
20 document . querySelectorAll ( ’. card ’) . forEach ( card = > {
21 console . log ( card . textContent ) ;
22 }) ;
23

24 // Closest ( find parent )


25 const clickedElement = event . target . closest ( ’. card ’) ;
26

27 // Matches ( check if element matches selector )


28 if ( element . matches ( ’. active ’) ) {

25
CHAPTER 6. DOM MANIPULATION MASTERY JavaScript Complete Guide

29 console . log ( ’ Element is active ’) ;


30 }

Listing 6.1: DOM Selection Methods

6.2 Manipulating Elements


Change content, attributes, and styles dynamically.
1 // Content manipulation
2 const element = document . querySelector ( ’. content ’) ;
3

4 // Text content
5 element . textContent = ’ New text ’;
6 element . innerText = ’ Also new text ’;
7

8 // HTML content
9 element . innerHTML = ’< strong > Bold text </ strong > ’;
10 element . ins er tA dj ac en tH TM L ( ’ beforeend ’ , ’< span > Added </ span > ’) ;
11

12 // Attributes
13 element . setAttribute ( ’ data - id ’ , ’123 ’) ;
14 const id = element . getAttribute ( ’ data - id ’) ;
15 element . removeAttribute ( ’ disabled ’) ;
16

17 // Class manipulation ( modern )


18 element . classList . add ( ’ new - class ’) ;
19 element . classList . remove ( ’ old - class ’) ;
20 element . classList . toggle ( ’ active ’) ;
21 element . classList . contains ( ’ highlight ’) ;
22

23 // Style manipulation
24 element . style . color = ’red ’;
25 element . style . backgroundColor = ’# f0f0f0 ’;
26

27 // Creating elements
28 const newDiv = document . createElement ( ’ div ’) ;
29 newDiv . className = ’ alert alert - success ’;
30 newDiv . textContent = ’ Operation successful ! ’;
31

32 // Adding to DOM
33 document . body . appendChild ( newDiv ) ;
34 container . prepend ( newDiv ) ; // Add to beginning

26
CHAPTER 6. DOM MANIPULATION MASTERY JavaScript Complete Guide

35 container . append ( newDiv ) ; // Add to end


36

37 // Removing elements
38 element . remove () ; // Modern way

Listing 6.2: Element Manipulation

6.3 Event Handling


Master browser events and user interactions.
1 // Basic event handling
2 const button = document . querySelector ( ’# submit - btn ’) ;
3

4 button . addEventListener ( ’ click ’ , function ( event ) {


5 console . log ( ’ Button clicked ! ’) ;
6 console . log ( ’ Event type : ’ , event . type ) ;
7 console . log ( ’ Target : ’ , event . target ) ;
8 }) ;
9

10 // Event object properties


11 document . addEventListener ( ’ click ’ , ( e ) = > {
12 console . log ( ‘ Clicked at ( $ { e . clientX } , $ { e . clientY }) ‘) ;
13 console . log ( ’ Alt key : ’ , e . altKey ) ;
14 console . log ( ’ Ctrl key : ’ , e . ctrlKey ) ;
15 }) ;
16

17 // Common events
18 element . addEventListener ( ’ mouseenter ’ , () = > console . log ( ’ Mouse entered ’) )
;
19 element . addEventListener ( ’ mouseleave ’ , () = > console . log ( ’ Mouse left ’) ) ;
20 element . addEventListener ( ’ dblclick ’ , () = > console . log ( ’ Double click ’) ) ;
21

22 // Keyboard events
23 document . addEventListener ( ’ keydown ’ , ( e ) = > {
24 console . log ( ‘ Key pressed : $ { e . key } ‘) ;
25 if ( e . key === ’ Enter ’ && e . ctrlKey ) {
26 console . log ( ’ Ctrl + Enter pressed ’) ;
27 }
28 }) ;
29

30 // Form events
31 const form = document . querySelector ( ’ form ’) ;

27
CHAPTER 6. DOM MANIPULATION MASTERY JavaScript Complete Guide

32 form . addEventListener ( ’ submit ’ , ( e ) = > {


33 e . preventDefault () ; // Stop page reload
34 const formData = new FormData ( form ) ;
35 console . log ( ’ Form submitted : ’ , Object . fromEntries ( formData ) ) ;
36 }) ;
37

38 const input = document . querySelector ( ’ input ’) ;


39 input . addEventListener ( ’ input ’ , ( e ) = > {
40 console . log ( ’ Current value : ’ , e . target . value ) ;
41 }) ;
42

43 // Event delegation
44 document . querySelector ( ’. todo - list ’) . addEventListener ( ’ click ’ , ( e ) = > {
45 if ( e . target . matches ( ’. delete - btn ’) ) {
46 console . log ( ’ Delete todo ’) ;
47 e . target . closest ( ’. todo ’) . remove () ;
48 }
49 }) ;
50

51 // Removing event listeners


52 function handleClick () { console . log ( ’ Clicked ’) ; }
53 button . addEventListener ( ’ click ’ , handleClick ) ;
54 button . r em o v eE v e nt L i st e n er ( ’ click ’ , handleClick ) ;
55

56 // One - time events


57 button . addEventListener ( ’ click ’ , () = > {
58 console . log ( ’ This runs only once ’) ;
59 } , { once : true }) ;

Listing 6.3: Event Listeners

Important
Event delegation is crucial for dynamic content! Instead of attaching listeners to each
element, attach one listener to a parent and use [Link] to check what was
clicked. This works for elements added after page load.

28
7 Practical Project: Todo Application

Mini Project

Complete Project: Modern Todo App


Build a full-featured todo application with:

• Add, edit, delete todos

• Mark todos as complete

• Filter todos (All, Active, Completed)

• Local storage persistence

• Search functionality

1 // Complete Todo Application


2 class TodoApp {
3 constructor () {
4 this . todos = [];
5 this . filter = ’all ’;
6 this . loadFromStorage () ;
7 this . initElements () ;
8 this . attachEvents () ;
9 this . render () ;
10 }
11

12 initElements () {
13 this . todoForm = document . querySelector ( ’# todo - form ’) ;
14 this . todoInput = document . querySelector ( ’# todo - input ’) ;
15 this . todoList = document . querySelector ( ’# todo - list ’) ;
16 this . filterBtns = document . querySelectorAll ( ’. filter - btn ’) ;
17 this . searchInput = document . querySelector ( ’# search - input ’) ;
18 this . stats = document . querySelector ( ’# stats ’) ;

29
CHAPTER 7. PRACTICAL PROJECT: TODO APPLICATION
JavaScript Complete Guide

19 }
20

21 attachEvents () {
22 this . todoForm . addEventListener ( ’ submit ’ , ( e ) = > {
23 e . preventDefault () ;
24 this . addTodo () ;
25 }) ;
26

27 this . todoList . addEventListener ( ’ click ’ , ( e ) = > {


28 const todoItem = e . target . closest ( ’. todo - item ’) ;
29 if (! todoItem ) return ;
30

31 if ( e . target . matches ( ’. delete - btn ’) ) {


32 this . deleteTodo ( todoItem . dataset . id ) ;
33 }
34 if ( e . target . matches ( ’. edit - btn ’) ) {
35 this . editTodo ( todoItem . dataset . id ) ;
36 }
37 if ( e . target . matches ( ’. complete - checkbox ’) ) {
38 this . toggleComplete ( todoItem . dataset . id ) ;
39 }
40 }) ;
41

42 this . filterBtns . forEach ( btn = > {


43 btn . addEventListener ( ’ click ’ , () = > {
44 this . filter = btn . dataset . filter ;
45 this . u pd a t eF i l te r B ut t o ns () ;
46 this . render () ;
47 }) ;
48 }) ;
49

50 this . searchInput . addEventListener ( ’ input ’ , () = > {


51 this . render () ;
52 }) ;
53 }
54

55 addTodo () {
56 const text = this . todoInput . value . trim () ;
57 if (! text ) return ;
58

59 const todo = {
60 id : Date . now () . toString () ,
61 text ,

30
CHAPTER 7. PRACTICAL PROJECT: TODO APPLICATION
JavaScript Complete Guide

62 completed : false ,
63 createdAt : new Date () . toISOString ()
64 };
65

66 this . todos . push ( todo ) ;


67 this . saveToStorage () ;
68 this . todoInput . value = ’ ’;
69 this . render () ;
70 }
71

72 deleteTodo ( id ) {
73 this . todos = this . todos . filter ( todo = > todo . id !== id ) ;
74 this . saveToStorage () ;
75 this . render () ;
76 }
77

78 editTodo ( id ) {
79 const todo = this . todos . find ( t = > t . id === id ) ;
80 const newText = prompt ( ’ Edit todo : ’ , todo . text ) ;
81 if ( newText && newText . trim () ) {
82 todo . text = newText . trim () ;
83 this . saveToStorage () ;
84 this . render () ;
85 }
86 }
87

88 toggleComplete ( id ) {
89 const todo = this . todos . find ( t = > t . id === id ) ;
90 todo . completed = ! todo . completed ;
91 this . saveToStorage () ;
92 this . render () ;
93 }
94

95 getFilteredTodos () {
96 let filtered = this . todos ;
97

98 if ( this . filter === ’ active ’) {


99 filtered = filtered . filter ( t = > ! t . completed ) ;
100 } else if ( this . filter === ’ completed ’) {
101 filtered = filtered . filter ( t = > t . completed ) ;
102 }
103

104 const searchTerm = this . searchInput . value . toLowerCase () ;

31
CHAPTER 7. PRACTICAL PROJECT: TODO APPLICATION
JavaScript Complete Guide

105 if ( searchTerm ) {
106 filtered = filtered . filter ( t = >
107 t . text . toLowerCase () . includes ( searchTerm )
108 );
109 }
110

111 return filtered ;


112 }
113

114 render () {
115 const filteredTodos = this . getFilteredTodos () ;
116

117 if ( filteredTodos . length === 0) {


118 this . todoList . innerHTML = ’<p > No todos found . Add one above ! </
p > ’;
119 } else {
120 this . todoList . innerHTML = filteredTodos . map ( todo = > ‘
121 < div class =" todo - item $ { todo . completed ? ’ completed ’ :
’ ’}"
122 data - id =" $ { todo . id }" >
123 < input type =" checkbox "
124 class =" complete - checkbox "
125 $ { todo . completed ? ’ checked ’ : ’ ’} >
126 < span class =" todo - text " > $ { this . escapeHtml ( todo . text )
} </ span >
127 < div class =" todo - actions " >
128 < button class =" edit - btn " > Edit </ button >
129 < button class =" delete - btn " > Delete </ button >
130 </ div >
131 </ div >
132 ‘) . join ( ’ ’) ;
133 }
134

135 this . updateStats () ;


136 }
137

138 updateStats () {
139 const total = this . todos . length ;
140 const completed = this . todos . filter ( t = > t . completed ) . length ;
141 const active = total - completed ;
142

143 this . stats . innerHTML = ‘


144 Total : $ { total } | Completed : $ { completed } | Active : $ { active }

32
CHAPTER 7. PRACTICAL PROJECT: TODO APPLICATION
JavaScript Complete Guide

145 ‘;
146 }
147

148 up d a te F i l te r B ut t o ns () {
149 this . filterBtns . forEach ( btn = > {
150 if ( btn . dataset . filter === this . filter ) {
151 btn . classList . add ( ’ active ’) ;
152 } else {
153 btn . classList . remove ( ’ active ’) ;
154 }
155 }) ;
156 }
157

158 saveToStorage () {
159 localStorage . setItem ( ’ todos ’ , JSON . stringify ( this . todos ) ) ;
160 }
161

162 loadFromStorage () {
163 const stored = localStorage . getItem ( ’ todos ’) ;
164 if ( stored ) {
165 this . todos = JSON . parse ( stored ) ;
166 }
167 }
168

169 escapeHtml ( text ) {


170 const div = document . createElement ( ’ div ’) ;
171 div . textContent = text ;
172 return div . innerHTML ;
173 }
174 }
175

176 // Initialize app when DOM is ready


177 document . addEventListener ( ’ DOMContentLoaded ’ , () = > {
178 window . app = new TodoApp () ;
179 }) ;

Listing 7.1: Todo App Implementation

33
8 Best Practices and Modern Features

8.1 Code Quality Patterns


1 // 1. Use const / let appropriately
2 // Good
3 const API_URL = ’ https :// api . example . com ’;
4 let counter = 0;
5

6 // Bad
7 var apiUrl = ’ https :// api . example . com ’; // Never use var
8

9 // 2. Use destructuring for objects / arrays


10 // Good
11 const { name , age } = user ;
12 const [ first , second ] = items ;
13

14 // 3. Use default parameters


15 // Good
16 function greet ( name = ’ Guest ’) {
17 return ‘ Hello , $ { name } ‘;
18 }
19

20 // 4. Use template literals


21 // Good
22 const message = ‘ Hello , $ { name }! You have $ { count } messages . ‘;
23

24 // 5. Use arrow functions for callbacks


25 // Good
26 [1 , 2 , 3]. map ( x = > x * 2) ;
27

28 // 6. Use spread for copies


29 // Good
30 const newArray = [... oldArray ];
31 const newObject = { ... oldObject };

34
CHAPTER 8. BEST PRACTICES AND MODERN FEATURES
JavaScript Complete Guide

32

33 // 7. Use optional chaining


34 // Good
35 const city = user ?. address ?. city ?? ’ Unknown ’;
36

37 // 8. Use nullish coalescing


38 // Good
39 const value = input ?? ’ default ’;
40

41 // 9. Use Array methods instead of loops


42 // Good
43 const doubled = numbers . map ( n = > n * 2) ;
44 const evens = numbers . filter ( n = > n % 2 === 0) ;
45 const sum = numbers . reduce (( acc , n ) = > acc + n , 0) ;

Listing 8.1: Modern JavaScript Best Practices

8.2 Modern JavaScript Features (ES2020-ES2025)


1 // Optional Chaining ( ES2020 )
2 const user = { profile : { name : " John " } };
3 console . log ( user ?. profile ?. name ) ; // " John "
4 console . log ( user ?. address ?. city ) ; // undefined
5

6 // Nullish Coalescing ( ES2020 )


7 const value = null ?? ’ default ’; // ’ default ’
8 const zero = 0 ?? ’ default ’; // 0
9

10 // Promise . allSettled ( ES2020 )


11 const results = await Promise . allSettled ([
12 fetch ( ’/ api1 ’) ,
13 fetch ( ’/ api2 ’)
14 ]) ;
15

16 // globalThis ( ES2020 )
17 console . log ( globalThis === window ) ; // true in browsers
18

19 // Logical Assignment Operators ( ES2021 )


20 let x = null ;
21 x ||= ’ default ’; // x = ’ default ’
22

23 // Numeric Separators ( ES2021 )

35
CHAPTER 8. BEST PRACTICES AND MODERN FEATURES
JavaScript Complete Guide

24 const billion = 1 _000_000_000 ;


25 const bytes = 0 xFF_FF_FF_FF ;
26

27 // String replaceAll ( ES2021 )


28 const text = ’a + b + c +d ’;
29 console . log ( text . replaceAll ( ’+ ’ , ’ - ’) ) ; // ’a -b -c -d ’
30

31 // Error Cause ( ES2022 )


32 try {
33 await fetch ( ’ invalid - url ’) ;
34 } catch ( error ) {
35 throw new Error ( ’ Failed to fetch ’ , { cause : error }) ;
36 }
37

38 // Top - level await ( ES2022 )


39 const data = await fetch ( ’/ data . json ’) ;
40

41 // Array findLast and findLastIndex ( ES2023 )


42 const numbers = [1 , 2 , 3 , 4 , 5];
43 const lastEven = numbers . findLast ( n = > n % 2 === 0) ; // 4
44

45 // Array toReversed , toSorted , toSpliced ( ES2023 - non - mutating )


46 const original = [3 , 1 , 2];
47 const reversed = original . toReversed () ; // [2 , 1 , 3]
48 console . log ( original ) ; // [3 , 1 , 2] ( unchanged )
49

50 // GroupBy ( ES2024 )
51 const people = [
52 { name : ’ Alice ’ , age : 25 } ,
53 { name : ’Bob ’ , age : 30 } ,
54 { name : ’ Charlie ’ , age : 25 }
55 ];
56 const grouped = Object . groupBy ( people , p = > p . age ) ;
57 // { 25: [ Alice , Charlie ] , 30: [ Bob ] }

Listing 8.2: Latest JavaScript Features

8.3 Performance Tips


1 // 1. Debounce for input events
2 function debounce ( fn , delay ) {
3 let timeoutId ;

36
CHAPTER 8. BEST PRACTICES AND MODERN FEATURES
JavaScript Complete Guide

4 return function (... args ) {


5 clearTimeout ( timeoutId ) ;
6 timeoutId = setTimeout (() = > fn (... args ) , delay ) ;
7 };
8 }
9

10 const searchHandler = debounce (( query ) = > {


11 console . log ( ’ Searching for : ’ , query ) ;
12 } , 300) ;
13

14 // 2. Throttle for scroll / resize events


15 function throttle ( fn , limit ) {
16 let inThrottle ;
17 return function (... args ) {
18 if (! inThrottle ) {
19 fn (... args ) ;
20 inThrottle = true ;
21 setTimeout (() = > inThrottle = false , limit ) ;
22 }
23 };
24 }
25

26 window . addEventListener ( ’ scroll ’ , throttle (() = > {


27 console . log ( ’ Scroll position : ’ , window . scrollY ) ;
28 } , 100) ) ;
29

30 // 3. Use r e q u e s t A n i m a t i o n Fr a m e for animations


31 function animate () {
32 // Animation logic here
33 r e q u e s t A n i m a t i o n F r a m e ( animate ) ;
34 }
35 r e q u e s t A n i m a t i o n F r a m e ( animate ) ;
36

37 // 4. Avoid layout thrashing


38 // Bad
39 for ( let i = 0; i < elements . length ; i ++) {
40 elements [ i ]. style . width = elements [ i ]. offsetWidth + 10 + ’px ’;
41 }
42

43 // Good
44 const widths = elements . map ( el = > el . offsetWidth ) ;
45 for ( let i = 0; i < elements . length ; i ++) {
46 elements [ i ]. style . width = widths [ i ] + 10 + ’px ’;

37
CHAPTER 8. BEST PRACTICES AND MODERN FEATURES
JavaScript Complete Guide

47 }
48

49 // 5. Use WeakMap for private data without memory leaks


50 const privateData = new WeakMap () ;
51

52 class PrivateExample {
53 constructor ( value ) {
54 privateData . set ( this , { secret : value }) ;
55 }
56

57 getSecret () {
58 return privateData . get ( this ) . secret ;
59 }
60 }

Listing 8.3: Performance Optimization

38
A JavaScript Quick Reference

A.1 Common Patterns Cheatsheet

Pattern Code Example


Array iteration [Link](item => [Link](item))
Array map const doubled = [Link](n => n * 2)
Array filter const evens = [Link](n => n % 2 === 0)
Array reduce const sum = [Link]((a,b) => a + b, 0)
Array find const found = [Link](item => [Link] === 5)
Array some const hasEven = [Link](n => n % 2 === 0)
Array every const allEven = [Link](n => n % 2 === 0)
Object iteration [Link](obj).forEach(([k,v]) =>
[Link](k,v))
Async/Await const data = await fetch(url).then(r =>
[Link]())
Promise all const [a,b] = await [Link]([p1, p2])
Event delegation [Link](’click’, e =>
[Link](’.btn’))
Local storage [Link](’key’,
[Link](value))
Session storage [Link](’key’, value)
Template literal ‘Hello $name¡
Destructuring const {name, age} = user
Spread operator const combined = [...arr1, ...arr2]
Optional chaining const city = user?.address?.city
Nullish coalescing const val = input ?? ’default’

39
APPENDIX A. JAVASCRIPT QUICK REFERENCE JavaScript Complete Guide

A.2 Array Methods Summary

Method Description
map() Creates new array by applying function to each element
filter() Creates new array with elements that pass the test
reduce() Reduces array to single value (accumulator pattern)
forEach() Executes function for each element (no return)
find() Returns first element that passes the test
findIndex() Returns index of first element that passes the test
some() Returns true if any element passes the test
every() Returns true if all elements pass the test
sort() Sorts array in-place (default: string order)
includes() Checks if array contains a value
flat() Flattens nested arrays (depth parameter)
flatMap() Map then flatten (depth 1)

A.3 Promise Methods Summary

Method Description
[Link]() Waits for all promises to resolve (fails fast)
Waits for all promises to settle (never fails)
[Link]()
[Link]() Returns first promise that settles
[Link]() Returns first fulfilled promise
[Link]() Creates resolved promise with value
[Link]() Creates rejected promise with error

A.4 Console Methods for Debugging

Method Description
[Link]() Standard log output
[Link]() Output error message (red styling)
[Link]() Output warning message (yellow styling)

40
APPENDIX A. JAVASCRIPT QUICK REFERENCE JavaScript Complete Guide

[Link]() Display data as table


[Link]() / Measure execution time
timeEnd()
[Link]() Group console messages
/ groupEnd()
[Link]() Print stack trace
[Link]()
— Assert condition
and log if false

41
APPENDIX A. JAVASCRIPT QUICK REFERENCE JavaScript Complete Guide

*
Thank You for Choosing Dark Code!
You’ve Completed the JavaScript Complete Guide
Mastered ES6+, Closures, Promises, Async/Await and DOM

Keep Building, Keep Learning, Keep Coding!

©2026 Dark Code - All


Rights Reserved
Version 2.0 - Comprehensive JavaScript Resource

42

You might also like