[Go to site: main page, start]

0% found this document useful (0 votes)
6 views35 pages

JavaScript Complete Reference

The document is a comprehensive JavaScript study reference based on BroCode's full course, covering 75 topics from beginner to advanced levels. It includes essential concepts such as variables, functions, OOP, DOM manipulation, asynchronous programming, and project walkthroughs. The content is structured in a way that facilitates learning through various examples and explanations of JavaScript fundamentals.

Uploaded by

joshua0clark01
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)
6 views35 pages

JavaScript Complete Reference

The document is a comprehensive JavaScript study reference based on BroCode's full course, covering 75 topics from beginner to advanced levels. It includes essential concepts such as variables, functions, OOP, DOM manipulation, asynchronous programming, and project walkthroughs. The content is structured in a way that facilitates learning through various examples and explanations of JavaScript fundamentals.

Uploaded by

joshua0clark01
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

JS

JavaScript
Complete Study Reference

Based on BroCode’s Full JavaScript Course

75 Topics ˆ From Beginner to Advanced

Topics include: Variables, Functions, OOP, DOM, Async/Await,


Fetch API, Promises, ES6+ and full project walkthroughs
JavaScript Complete Reference BroCode Course

0 1 Contents

1 JavaScript Basics (#1) 2


1.0.1 The Three Layers of Web Development . . . . . . . . . . . . . . . . . . . . . . 2
1.0.2 Setting Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.0.3 Basic Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.0.4 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Variables (#2) 2
2.0.1 Declaration and Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.0.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.0.3 Template Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.0.4 typeof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.0.5 Displaying Variables in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3 Arithmetic Operators (#3) 3


3.0.1 Augmented Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.0.2 Increment / Decrement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.0.3 Operator Precedence (PEMDAS) . . . . . . . . . . . . . . . . . . . . . . . . . . 3

4 Accepting User Input (#4) 3


4.0.1 Window Prompt (Easy Way) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4.0.2 HTML Text Box (Professional Way) . . . . . . . . . . . . . . . . . . . . . . . . 4

5 Type Conversion (#5) 4

6 Constants (#6) 4

7 Counter Program (#7) 4

8 Math Object (#8) 5


8.0.1 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
8.0.2 Common Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

9 Random Number Generator (#9) 5

10 If Statements (#10) 6
10.0.1 Nested If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
10.0.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

11 Checked Property (#11) 6

12 Ternary Operator (#12) 7

13 Switch Statements (#13) 7


13.0.1 Switch with Conditions (Grade example) . . . . . . . . . . . . . . . . . . . . . 7

1
JavaScript Complete Reference BroCode Course

14 String Methods (#14) 8

15 String Slicing (#15) 8


15.0.1 Email Parsing Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

16 Method Chaining (#16) 8

17 Logical Operators (#17) 9

18 Strict Equality (#18) 9

19 While Loops (#19) 9


19.0.1 Login Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

20 For Loops (#20) 10


20.0.1 continue and break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

21 Number Guessing Game (#21) 10

22 Functions (#22) 11

23 Variable Scope (#23) 11

24 Temperature Conversion Program (#24) 12

25 Arrays (#25) 12

26 Spread Operator (#26) 13

27 Rest Parameters (#27) 13

28 Callbacks (#30) 14

29 forEach() (#31) 14

30 map() (#32) 14

31 filter() (#33) 15

32 reduce() (#34) 15

33 Function Expressions (#35) 15

34 Arrow Functions (#36) 16

35 JavaScript Objects (#37) 16

36 The this Keyword (#38) 17

37 Constructors (#39) 17

2
JavaScript Complete Reference BroCode Course

38 Classes (#40) 17

39 Static Keyword (#41) 18

40 Inheritance (#42) 18

41 super Keyword (#43) 19

42 Getters & Setters (#44) 19

43 Destructuring (#45) 20

44 Nested Objects (#46) 20

45 Arrays of Objects (#47) 21

46 Sorting (#48) 21

47 Shuffle an Array (#49) — Fisher-Yates 21

48 Date Objects (#50) 22

49 Closures (#51) 22

50 setTimeout() (#52) 22

51 Digital Clock Program (#53) 23

52 ES6 Modules (#55) 23

53 Asynchronous Code (#56) 23

54 Error Handling (#57) 24

55 What is the DOM? (#59) 24

56 Element Selectors (#60) 24

57 DOM Navigation (#61) 25

58 Add & Change HTML (#62) 25

59 Mouse Events (#63) 25

60 Key Events (#64) 26

61 Hide / Show HTML (#65) 26

62 NodeLists (#66) 26

63 classList (#67) 27

3
JavaScript Complete Reference BroCode Course

64 Callback Hell (#70) 27

65 Promises (#71) 27

66 Async / Await (#72) 28

67 JSON Files (#73) 28

68 Fetch Data from an API (#74) 29

69 Projects Summary 29

70 Quick Reference Cheat Sheet 29


70.0.1 ES6+ Features Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
70.0.2 Array Methods Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
70.0.3 DOM Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4
JavaScript Complete Reference BroCode Course

1 1 JavaScript
Basics (#1)
JavaScript is a programming language used to create dynamic and interactive web pages. It runs
in the browser (Chrome, Safari, Edge, etc.) and can respond to user actions.
1The Three Layers of Web Development
ˆ HTML — Structure
ˆ CSS — Style/Appearance
ˆ JavaScript — Interactivity/Actions
1Setting Up
Create three files: [Link], [Link], [Link]. Link them in HTML:
< link rel = " stylesheet " href = " style . css " >
< script src = " index . js " > </ script > <! - - bottom of < body > -->

Always place your <script> tag at the bottom of the body. This ensures HTML renders before
JavaScript runs.

1Basic Output

console . log ( " Hello " ) ; // Output to browser console


console . log ( ‘I like pizza ‘) ; // Template literal ( backticks )
window . alert ( " Hello ! " ) ; // Browser popup alert

// Select element and change text


document . getElementById ( " myH1 " ) . textContent = " Hello " ;

1Comments

// Single - line comment


/* Multi - line
comment */

2 1 Variables
(#2)
A variable is a container that stores a value. It behaves as if it were the value it contains.
1Declaration and Assignment

let x ; // Declaration
x = 100; // Assignment
let y = 200; // Declaration + Assignment together

1Data Types

// Numbers
let age = 25;
let price = 10.99;

// Strings ( text )
let name = " BroCode " ;
let food = ’ pizza ’;
let greeting = ‘ Hello $ { name } ‘; // Template literal

// Booleans

5
JavaScript Complete Reference BroCode Course

let isOnline = true ;


let forSale = false ;

1Template Literals

let age = 25;


console . log ( ‘ You are $ { age } years old ‘) ; // You are 25 years old

1typeof Operator

console . log ( typeof age ) ; // " number "


console . log ( typeof name ) ; // " string "
console . log ( typeof true ) ; // " boolean "

1Displaying Variables in HTML

let fullName = " Bro Code " ;


document . getElementById ( " p1 " ) . textContent = fullName ;
document . getElementById ( " p1 " ) . textContent = ‘ Name : $ { fullName } ‘;

3 1 Arithmeti
Operators (#3)

Operator Name Example


+ Addition 5 + 3 = 8
- Subtraction 5 - 3 = 2
* Multiplication 5 * 3 = 15
/ Division 6 / 2 = 3
** Exponent 2 ** 3 = 8
% Modulus (remainder) 7 % 2 = 1

1Augmented Assignment Operators

students += 1; // same as students = students + 1


students -= 1;
students *= 2;
students /= 2;
students **= 2;
students %= 2;

1Increment / Decrement

students ++; // Increment by 1


students - -; // Decrement by 1

1Operator Precedence (PEMDAS)


Parentheses  Exponents  Multiplication/Division/Modulus  Addition/Subtraction (left to
right)
let result = 1 + 2 * 3 + 4 ** 2; // = 1 + 6 + 16 = 23

4 1 Accepting
User Input (#4)
1Window Prompt (Easy Way)

6
JavaScript Complete Reference BroCode Course

let username ;
username = window . prompt ( " What ’s your username ? " ) ;
console . log ( username ) ;

1HTML Text Box (Professional Way)

// HTML : < input id =" myText " type =" text " > < button id =" myBtn " > Submit </ button
>

const myBtn = document . getElementById ( " myBtn " ) ;


let username = " " ;

myBtn . () {


username = document . getElementById ( " myText " ) . value ;
document . getElementById ( " myH1 " ) . textContent = ‘ Hello $ { username } ‘;
};

5 1 Type
Conversion (#5)
When you accept user input it’s a string by default. Convert it before doing math.
let age = window . prompt ( " How old are you ? " ) ;
age = Number ( age ) ; // Convert to number
age += 1;
console . log ( typeof age ) ; // " number "

// Conversion functions
Number ( " 25 " ) // 25
Number ( " pizza " ) // NaN ( Not a Number )
String (25) // "25"
Boolean ( " " ) // false ( empty string )
Boolean ( " hi " ) // true ( non - empty string )
Boolean (0) // false

Key rule: An empty string converts to false. Any non-empty string converts to true. This is
useful for checking if a user typed something.

6 1 Constants
(#6)
const variables cannot be reassigned after initial assignment. Use UPPERCASE for primitive
constants (best practice).
const PI = 3.14159;
const radius = Number ( window . prompt ( " Enter radius : " ) ) ;
const circumference = 2 * PI * radius ;

// This throws an error :


PI = 420; // TypeError : Assignment to constant variable

Use const for values that should not change (PI, MAX SIZE, etc.). This prevents accidental
reassignment and makes code safer.

7 1 Counter
Program (#7)

7
JavaScript Complete Reference BroCode Course

// HTML : < label id =" countLabel " >0 </ label >
// < button id =" decreaseBtn " > decrease </ button >
// < button id =" resetBtn " > reset </ button >
// < button id =" increaseBtn " > increase </ button >

const countLabel = document . getElementById ( " countLabel " ) ;


const decreaseBtn = document . getElementById ( " decreaseBtn " ) ;
const resetBtn = document . getElementById ( " resetBtn " ) ;
const increaseBtn = document . getElementById ( " increaseBtn " ) ;
let count = 0;

increaseBtn . () {


count ++;
countLabel . textContent = count ;
};
decreaseBtn . () {
count - -;
countLabel . textContent = count ;
};
resetBtn . () {
count = 0;
countLabel . textContent = count ;
};

8 1 Math
Object (#8)
The Math object provides mathematical constants and methods.
1Properties

Math . PI // 3.14159...
Math . E // 2.71828...

1Common Methods

Math . round (3.5) // 4 rounds to nearest


Math . floor (3.9) // 3 always rounds DOWN
Math . ceil (3.1) // 4 always rounds UP
Math . trunc (3.9) // 3 removes decimal
Math . pow (2 , 10) // 1024
Math . sqrt (81) // 9
Math . abs ( -5) // 5
Math . sign ( -5) // -1 ( negative )
Math . log (10) // 2.302...

// Trigonometry ( uses radians )


Math . sin (45)
Math . cos (45)
Math . tan (45)

// Min / Max
Math . max (3 , 1 , 4 , 1 , 5) // 5
Math . min (3 , 1 , 4 , 1 , 5) // 1

9 1 Random
Number Generator (#9)

8
JavaScript Complete Reference BroCode Course

// Random decimal 0 to <1


Math . random ()

// Random integer 1 to 6 ( dice roll )


Math . floor ( Math . random () * 6) + 1

// Random integer between min and max ( inclusive )


const min = 50 , max = 100;
Math . floor ( Math . random () * ( max - min + 1) ) + min

Formula: [Link]([Link]() * (max - min + 1)) + min

10 1 If
Statements (#10)
let age = 18;

if ( age >= 18) {


console . log ( " You are old enough . " ) ;
} else if ( age < 0) {
console . log ( " Age can ’t be negative . " ) ;
} else {
console . log ( " You must be 18+. " ) ;
}

1Nested If Statements

if ( age >= 16) {


if ( hasLicense ) {
console . log ( " You can drive . " ) ;
} else {
console . log ( " You need a license . " ) ;
}
} else {
console . log ( " You must be 16+. " ) ;
}

1Comparison Operators

> Greater than


< Less than
>= Greater than or equal
<= Less than or equal
== Equal (value only)
=== Strict equal (value + type)
!= Not equal
!== Strict not equal

11 1 Checked
Property (#11)
Used to detect if a checkbox or radio button is selected.
// HTML : < input type =" checkbox " id =" myCheckbox " >
// < input type =" radio " id =" visaBtn " name =" card " >

const myCheckbox = document . getElementById ( " myCheckbox " ) ;


const visaBtn = document . getElementById ( " visaBtn " ) ;

9
JavaScript Complete Reference BroCode Course

myBtn . () {


if ( myCheckbox . checked ) {
console . log ( " You are subscribed . " ) ;
} else {
console . log ( " You are not subscribed . " ) ;
}

if ( visaBtn . checked ) {
console . log ( " Paying with Visa . " ) ;
}
};

12 1 Ternary
Operator (#12)
A shortcut for simple if/else that assigns a value based on a condition.
// condition ? valueIfTrue : valueIfFalse
let age = 21;
let message = age >= 18 ? " You ’ re an adult " : " You ’ re a minor " ;

// Boolean variable ( no need for == true )


let isStudent = true ;
let msg = isStudent ? " You are a student " : " You are not a student " ;

// Practical : purchase discount


let purchaseAmt = 125;
let discount = purchaseAmt >= 100 ? 10 : 0;
let total = purchaseAmt - ( purchaseAmt * discount / 100) ;

13 1 Switch
Statements (#13)
An efficient replacement for many else if statements.
let day = 1;

switch ( day ) {
case 1: console . log ( " Monday " ) ; break ;
case 2: console . log ( " Tuesday " ) ; break ;
case 3: console . log ( " Wednesday " ) ; break ;
// ... up to 7
default : console . log ( ‘ $ { day } is not a day ‘) ;
}

1Switch with Conditions (Grade example)

let score = 92;


let grade ;

switch ( true ) {
case score >= 90: grade = "A"; break ;
case score >= 80: grade = "B"; break ;
case score >= 70: grade = "C"; break ;
case score >= 60: grade = "D"; break ;
default : grade = "F";
}

10
JavaScript Complete Reference BroCode Course

Always add break after each case to prevent fall-through (executing subsequent cases uninten-
tionally).

14 1 String
Methods (#14)
let username = " BroCode ";

username . charAt (0) // " B " char at index 0


username . indexOf ( " o " ) // first " o " index
username . lastIndexOf ( " o " ) // last " o " index
username . length // number of characters
username . trim () // remove whitespace
username . toUpperCase () // " BROCODE "
username . toLowerCase () // " brocode "
username . repeat (3) // " B r o C o d e B r o C o d e B r o C o d e "
username . startsWith ( " " ) // true / false
username . endsWith ( " " ) // true / false
username . includes ( " Code " ) // true / false
username . replaceAll ( " -" ," " ) // replace all dashes
username . padStart (15 , " 0 " ) // pad start with zeros
username . padEnd (15 , " 0 " ) // pad end with zeros

15 1 String
Slicing (#15)
Create a substring from a portion of a string without altering the original.
const fullName = " Bro Code " ;

// slice ( start , end ) end index is EXCLUSIVE


let firstName = fullName . slice (0 , 3) ; // " Bro "
let lastName = fullName . slice (4) ; // " Code " ( to end )
let firstChar = fullName . slice (0 , 1) ; // " B "
let lastChar = fullName . slice ( -1) ; // " e " ( negative index )

// Dynamic slicing using indexOf


let firstName2 = fullName . slice (0 , fullName . indexOf ( " " ) ) ;
let lastName2 = fullName . slice ( fullName . indexOf ( " " ) + 1) ;

1Email Parsing Example

const email = " bro@gmail . com " ;


const username = email . slice (0 , email . indexOf ( " @ " ) ) ;
const extension = email . slice ( email . indexOf ( " @ " ) + 1) ;
// username = " bro " , extension = " gmail . com "

16 1 Method
Chaining (#16)
Calling multiple methods in one continuous line — like a combo in a video game.
let username = window . prompt ( " Enter username : " ) ;

// Without chaining ( many lines ) :


username = username . trim () ;
let letter = username . charAt (0) . toUpperCase () ;
let rest = username . slice (1) . toLowerCase () ;

11
JavaScript Complete Reference BroCode Course

username = letter + rest ;

// With method chaining :


username =
username . trim () . charAt (0) . toUpperCase () +
username . trim () . slice (1) . toLowerCase () ;

17 1 Logical
Operators (#17)

Operator Name Meaning


&& AND Both conditions must be true
|| OR At least one condition must be true
! NOT Flips true/false

// AND : both must be true


if ( temp > 0 && temp <= 30) {
console . log ( " Nice weather " ) ;
}

// OR : at least one true


if ( temp <= 0 || temp > 30) {
console . log ( " Bad weather " ) ;
}

// NOT : flip boolean


let isSunny = true ;
if (! isSunny ) {
console . log ( " It ’s cloudy " ) ; // won ’t run
}

18 1 Strict
Equality (#18)

Op Name Checks
== Equality Value only
=== Strict equality Value and type
!= Inequality Values differ
!== Strict inequality Value or type differ

const pi = 3.14; // number


pi == " 3.14 " // true ( ignores type )
pi === " 3.14 " // false ( different types !)
pi === 3.14 // true ( same value AND type )

// Prefer === to avoid unexpected behavior

19 1 While
Loops (#19)
Repeats code while a condition is true.
// Standard while loop
let username = " " ;
while ( username === " " || username === null ) {

12
JavaScript Complete Reference BroCode Course

username = window . prompt ( " Enter your name : " ) ;


}
console . log ( ‘ Hello $ { username } ‘) ;

// Do - while : executes at least once , checks at end


let username2 ;
do {
username2 = window . prompt ( " Enter your name : " ) ;
} while ( username2 === " " || username2 === null ) ;

1Login Example

let loggedIn = false ;


let username , password ;

while (! loggedIn ) {
username = window . prompt ( " Enter username : " ) ;
password = window . prompt ( " Enter password : " ) ;
if ( username === " myUser " && password === " myPass " ) {
loggedIn = true ;
console . log ( " You are logged in ! " ) ;
} else {
console . log ( " Invalid credentials . " ) ;
}
}

20 1 For
Loops (#20)
Repeats code a limited number of times.
// for ( init ; condition ; update )
for ( let i = 0; i <= 10; i ++) {
console . log ( i ) ; // 0 , 1 , 2 , ... , 10
}

// Count down
for ( let i = 10; i >= 1; i - -) {
console . log ( i ) ; // 10 , 9 , ... , 1
}

// Step by 2
for ( let i = 2; i <= 10; i += 2) {
console . log ( i ) ; // 2 , 4 , 6 , 8 , 10
}

1continue and break

for ( let i = 1; i <= 20; i ++) {


if ( i === 13) continue ; // skip 13
if ( i === 13) break ; // stop at 13
console . log ( i ) ;
}

21 1 Number
Guessing Game (#21)
const minNum = 1 , maxNum = 100;

13
JavaScript Complete Reference BroCode Course

const answer = Math . floor ( Math . random () * ( maxNum - minNum + 1) ) + minNum ;


let attempts = 0;
let guess ;
let running = true ;

while ( running ) {
guess = Number ( window . prompt ( ‘ Guess ( $ { minNum } - $ { maxNum }) : ‘) ) ;
if ( isNaN ( guess ) || guess < minNum || guess > maxNum ) {
window . alert ( " Invalid number . " ) ;
} else {
attempts ++;
if ( guess < answer ) window . alert ( " Too low ! " ) ;
else if ( guess > answer ) window . alert ( " Too high ! " ) ;
else {
window . alert ( ‘ Correct ! It was $ { answer }. Attempts : $ { attempts } ‘) ;
running = false ;
}
}
}

22 1 Functions
(#22)
A function is a section of reusable code. Declare once, use many times.
// Declaration
function greet ( name , age ) {
console . log ( ‘ Hello $ { name } , you are $ { age }. ‘) ;
}
greet ( " SpongeBob " , 30) ; // Call with arguments

// Return value
function add (x , y ) {
return x + y ;
}
let result = add (2 , 3) ; // 5

// Check even ( return boolean )


function isEven ( num ) {
return num % 2 === 0; // true or false
}

// Validate email
function isValidEmail ( email ) {
return email . includes ( " @ " ) ;
}

23 1 Variable
Scope (#23)
// LOCAL scope : declared inside a function
function funcOne () {
let x = 1; // only visible inside funcOne
console . log ( x ) ;
}

// GLOBAL scope : declared outside any function


let x = 3; // accessible everywhere

14
JavaScript Complete Reference BroCode Course

function funcTwo () {
let x = 2; // uses local x first ( shadows global )
console . log ( x ) ; // 2
}
funcOne () ; // 1
funcTwo () ; // 2
console . log ( x ) ; // 3 ( global )

Avoid global variables in large programs. They can cause naming conflicts and make debugging
harder.

24 1 Temperat
Conversion Program (#24)
// Formulas
// Celsius to Fahrenheit : ( C * 9/5) + 32
// Fahrenheit to Celsius : ( F - 32) * 5/9

const textbox = document . getElementById ( " textbox " ) ;


const result = document . getElementById ( " result " ) ;
const toF = document . getElementById ( " toFahrenheit " ) ;
const toC = document . getElementById ( " toCelsius " ) ;

document . getElementById ( " mySubmit " ) . () {


let temp = Number ( textbox . value ) ;
if ( toF . checked ) {
temp = ( temp * 9/5 + 32) . toFixed (1) ;
result . textContent = ‘ $ { temp } F ‘;
} else if ( toC . checked ) {
temp = (( temp - 32) * 5/9) . toFixed (1) ;
result . textContent = ‘ $ { temp } C ‘;
} else {
result . textContent = " Select a unit " ;
}
};

25 1 Arrays
(#25)
An array can store multiple values in a single variable.
let fruits = [ " apple " , " orange " , " banana " ];

// Access by index ( starts at 0)


fruits [0] // " apple "
fruits [1] // " orange "

// Change an element
fruits [0] = " coconut " ;

// Common methods
fruits . push ( " mango " ) ; // add to end
fruits . pop () ; // remove from end
fruits . unshift ( " kiwi " ) ; // add to beginning
fruits . shift () ; // remove from beginning
fruits . length ; // number of elements
fruits . indexOf ( " orange " ) ; // find index ( -1 if not found )

// Loop through

15
JavaScript Complete Reference BroCode Course

for ( let i = 0; i < fruits . length ; i ++) {


console . log ( fruits [ i ]) ;
}
// Enhanced for loop
for ( let fruit of fruits ) {
console . log ( fruit ) ;
}

fruits . sort () ; // alphabetical


fruits . reverse () ; // reverse order

26 1 Spread
Operator (#26)
The spread operator (...) unpacks elements of an array or string.
let nums = [1 , 2 , 3 , 4 , 5];

// Use with Math . max / min ( can ’t pass array directly )


Math . max (... nums ) // 5
Math . min (... nums ) // 1

// Spread string into array of characters


let letters = [... " hello " ]; // [ ’ h ’,’e ’,’l ’,’l ’,’o ’]

// Shallow copy of array


let copy = [... nums ];

// Merge arrays
let vegs = [ " carrot " , " celery " ];
let foods = [... nums , ... vegs , " eggs " , " milk " ];

27 1 Rest
Parameters (#27)
Rest parameters (...) bundle arguments into an array. The opposite of spread.
// Accept any number of arguments
function sum (... numbers ) {
let result = 0;
for ( let n of numbers ) result += n ;
return result ;
}
sum (1 , 2 , 3 , 4 , 5) ; // 15

// Get average
function getAverage (... numbers ) {
let total = 0;
for ( let n of numbers ) total += n ;
return total / numbers . length ;
}

// Combine strings
function combineStrings (... strings ) {
return strings . join ( " " ) ;
}
combineStrings ( " Mr . " , " SpongeBob " , " SquarePants " ) ;

16
JavaScript Complete Reference BroCode Course

28 1 Callbacks
(#30)
A callback is a function passed as an argument to another function.
function hello ( callback ) {
console . log ( " Hello " ) ;
callback () ; // call the callback when done
}
function goodbye () {
console . log ( " Goodbye " ) ;
}

hello ( goodbye ) ; // prints : Hello , then Goodbye

// With arguments
function sum (x , y , callback ) {
let result = x + y ;
callback ( result ) ;
}
function display ( result ) {
console . log ( result ) ;
}
sum (1 , 2 , display ) ; // 3

29 1 forEach()
(#31)
Iterate through array elements and apply a function to each.
let nums = [1 , 2 , 3 , 4 , 5];

// Using a named function


function display ( element ) {
console . log ( element ) ;
}
nums . forEach ( display ) ;

// Using arrow function ( preferred )


nums . forEach ( element = > console . log ( element ) ) ;

// Modify array elements


nums . forEach (( element , index , array ) = > {
array [ index ] = element * 2;
}) ;
// nums is now [2 , 4 , 6 , 8 , 10]

30 1 map()
(#32)
Like forEach but returns a new array. Original is preserved.
const nums = [1 , 2 , 3 , 4 , 5];

const squares = nums . map ( n = > Math . pow (n , 2) ) ;


// [1 , 4 , 9 , 16 , 25]

const cubes = nums . map ( n = > Math . pow (n , 3) ) ;


// [1 , 8 , 27 , 64 , 125]

17
JavaScript Complete Reference BroCode Course

const students = [ " SpongeBob " , " Patrick " , " Sandy " ];
const upper = students . map ( s = > s . toUpperCase () ) ;
// [" SPONGEBOB " , " PATRICK " , " SANDY "]

// Reformat dates
const dates = [ " 2024 -01 -10 " , " 2025 -02 -20 " ];
const formatted = dates . map ( d = > {
const [ year , month , day ] = d . split ( " -" ) ;
return ‘ $ { month }/ $ { day }/ $ { year } ‘;
}) ;

31 1 filter()
(#33)
Creates a new array with elements that pass a condition.
const nums = [1 , 2 , 3 , 4 , 5 , 6 , 7];

const evens = nums . filter ( n = > n % 2 === 0) ; // [2 , 4 , 6]


const odds = nums . filter ( n = > n % 2 !== 0) ; // [1 , 3 , 5 , 7]

const ages = [16 , 17 , 18 , 18 , 19 , 20 , 60];


const adults = ages . filter ( a = > a >= 18) ; // [18 , 18 , 19 , 20 , 60]
const children = ages . filter ( a = > a < 18) ; // [16 , 17]

const words = [ " apple " ," orange " ," banana " ," kiwi " ," pomegranate " ];
const short = words . filter ( w = > w . length <= 6) ; // short words
const long = words . filter ( w = > w . length > 6) ; // long words

32 1 reduce()
(#34)
Reduces array elements to a single value.
const prices = [5 , 30 , 10 , 25 , 15 , 20];

// Sum all prices


const total = prices . reduce (( acc , price ) = > acc + price ) ;
// 105

// Find maximum
const max = prices . reduce (( max , curr ) = > curr > max ? curr : max ) ;

// Find minimum
const min = prices . reduce (( min , curr ) = > curr < min ? curr : min ) ;

33 1 Function
Expressions (#35)
Assign a function to a variable or pass it as a value.
// Function expression ( stored in variable )
const hello = function () {
console . log ( " Hello " ) ;
};
hello () ;

// Passed as argument ( anonymous )

18
JavaScript Complete Reference BroCode Course

setTimeout ( function () {
console . log ( " Hello after 3 s " ) ;
} , 3000) ;

// With map / filter / reduce


const squares = [1 ,2 ,3]. map ( function ( n ) { return n * n ; }) ;

34 1 Arrow
Functions (#36)
A concise way to write function expressions.
// parameters = > code
const hello = () = > console . log ( " Hello " ) ;
hello () ;

// With parameters
const greet = name = > console . log ( ‘ Hello $ { name } ‘) ;

// Multiple parameters need parentheses


const add = (x , y ) = > x + y ;

// Multiple statements need curly braces + return


const describe = ( name , age ) = > {
console . log ( ‘ Name : $ { name } ‘) ;
console . log ( ‘ Age : $ { age } ‘) ;
};

// With map / filter / reduce


const squares = [1 ,2 ,3]. map ( n = > n ** 2) ;
const evens = [1 ,2 ,3 ,4]. filter ( n = > n % 2 === 0) ;
const total = [1 ,2 ,3]. reduce (( acc , n ) = > acc + n ) ;

35 1 JavaScript
Objects (#37)
An object is a collection of related properties (data) and methods (functions).
const person1 = {
firstName : " SpongeBob " ,
lastName : " SquarePants " ,
age : 30 ,
isEmployed : true ,
sayHello : function () {
console . log ( " Hi I ’m SpongeBob ! " ) ;
},
eat : () = > console . log ( " Eating a Krabby Patty ! " )
};

// Access properties
person1 . firstName // " SpongeBob "
person1 [ " age " ] // 30

// Call methods
person1 . sayHello () ;
person1 . eat () ;

19
JavaScript Complete Reference BroCode Course

36 1 The
this Keyword (#38)
this is a reference to the object in context.
const person1 = {
name : " SpongeBob " ,
favFood : " Krabby Patty " ,
sayHello () {
console . log ( ‘ Hi I ’m $ { this . name } ‘) ;
// this . name === person1 . name
},
eat () {
console . log ( ‘ $ { this . name } is eating $ { this . favFood } ‘) ;
}
};

const person2 = { name : " Patrick " , favFood : " Roast Beef " ,
eat : person1 . eat };
// person2 . eat () will use person2 ’s properties via ‘ this ‘

this does not work correctly inside arrow functions — arrow functions inherit this from their
enclosing scope. Use regular functions for object methods.

37 1 Construct
(#39)
A constructor is a function that creates multiple similar objects efficiently.
function Car ( make , model , year , color ) {
this . make = make ;
this . model = model ;
this . year = year ;
this . color = color ;
this . drive = function () {
console . log ( ‘ You drive the $ { this . model } ‘) ;
};
}

const car1 = new Car ( " Ford " , " Mustang " , 2024 , " red " ) ;
const car2 = new Car ( " Chevy " , " Camaro " , 2025 , " blue " ) ;
car1 . drive () ; // You drive the Mustang

38 1 Classes
(#40)
ES6 feature — a cleaner, more structured way to define objects.
class Product {
constructor ( name , price ) {
this . name = name ;
this . price = price ;
}

displayProduct () {
console . log ( ‘ $ { this . name }: $$ { this . price . toFixed (2) } ‘) ;
}

calculateTotal ( salesTax ) {

20
JavaScript Complete Reference BroCode Course

return this . price + ( this . price * salesTax ) ;


}
}

const shirt = new Product ( " Shirt " , 19.99) ;


shirt . displayProduct () ;
const total = shirt . calculateTotal (0.05) ;

39 1 Static
Keyword (#41)
static defines properties/methods that belong to the class itself, not instances.
class MathUtil {
static PI = 3.14159;
static getDiameter ( r ) { return r * 2; }
static getCircumference ( r ) { return 2 * this . PI * r ; }
}

// Access via class name , not instance


MathUtil . PI // 3.14159
MathUtil . getDiameter (10) // 20
MathUtil . getCircumference (10) // 62.83

class User {
static userCount = 0;
constructor ( username ) {
this . username = username ;
User . userCount ++; // increment class - level counter
}
}
const u1 = new User ( " SpongeBob " ) ;
const u2 = new User ( " Patrick " ) ;
User . userCount ; // 2

40 1 Inheritanc
(#42)
Allows a child class to inherit properties and methods from a parent class.
class Animal {
alive = true ;
eat () { console . log ( ‘ $ { this . name } is eating ‘) ; }
sleep () { console . log ( ‘ $ { this . name } is sleeping ‘) ; }
}

class Rabbit extends Animal {


name = " Rabbit " ;
run () { console . log ( ‘ $ { this . name } is running ‘) ; }
}

class Fish extends Animal {


name = " Fish " ;
swim () { console . log ( ‘ $ { this . name } is swimming ‘) ; }
}

class Hawk extends Animal {


name = " Hawk " ;
fly () { console . log ( ‘ $ { this . name } is flying ‘) ; }

21
JavaScript Complete Reference BroCode Course

const rabbit = new Rabbit () ;


rabbit . eat () ; // inherited from Animal
rabbit . run () ; // Rabbit ’s own method

41 1 super
Keyword (#43)
Calls the parent’s constructor or accesses parent methods.
class Animal {
constructor ( name , age ) {
this . name = name ;
this . age = age ;
}
move ( speed ) {
console . log ( ‘ $ { this . name } moves at $ { speed } mph ‘) ;
}
}

class Rabbit extends Animal {


constructor ( name , age , runSpeed ) {
super ( name , age ) ; // call parent constructor
this . runSpeed = runSpeed ;
}
run () {
console . log ( ‘ $ { this . name } can run ‘) ;
super . move ( this . runSpeed ) ; // call parent method
}
}

const r = new Rabbit ( " Bugs " , 1 , 25) ;


r . run () ;

42 1 Getters
& Setters (#44)
Getters make a property readable. Setters make a property writable with validation.
class Rectangle {
constructor ( width , height ) {
this . width = width ;
this . height = height ;
}

set width ( newW ) {


if ( newW > 0) this . _width = newW ;
else console . error ( " Width must be positive " ) ;
}
get width () { return this . _width . toFixed (1) + " cm " ; }

set height ( newH ) {


if ( newH > 0) this . _height = newH ;
else console . error ( " Height must be positive " ) ;
}
get height () { return this . _height . toFixed (1) + " cm " ; }

get area () { return ( this . _width * this . _height ) . toFixed (1) ; }

22
JavaScript Complete Reference BroCode Course

const rect = new Rectangle ( -1 , " pizza " ) ; // errors triggered


const rect2 = new Rectangle (3 , 4) ;
rect2 . width // "3.0 cm "
rect2 . area // "12.0"

43 1 Destructu
(#45)
Extract values from arrays or objects into variables conveniently.
// ARRAY destructuring
let [a , b ] = [1 , 2];
[a , b ] = [b , a ]; // swap values

let colors = [ " red " ," green " ," blue " ," black " ];
const [ first , second , ... rest ] = colors ;
// first =" red " , second =" green " , rest =[" blue " ," black "]

// OBJECT destructuring
const person = { name : " SpongeBob " , age :30 , job : " fry cook " };
const { name , age , job = " unemployed " } = person ;
// default value if property doesn ’t exist

// In function parameters
function display ({ name , age , job = " unemployed " }) {
console . log ( ‘ $ { name } , age $ { age } , job : $ { job } ‘) ;
}
display ( person ) ;

44 1 Nested
Objects (#46)
Objects can contain other objects (child objects).
const person = {
fullName : " SpongeBob " ,
age : 30 ,
hobbies : [ " karate " , " jellyfishing " , " cooking " ] ,
address : {
street : " 124 Conch St " ,
city : " Bikini Bottom " ,
country : " Int ’l Waters "
}
};

// Access nested property


person . address . street ; // "124 Conch St "
person . hobbies [0]; // " karate "

// Loop nested object properties


for ( const key in person . address ) {
console . log ( person . address [ key ]) ;
}

23
JavaScript Complete Reference BroCode Course

45 1 Arrays
of Objects (#47)
const fruits = [
{ name : " apple " , color : " red " , calories : 95 } ,
{ name : " orange " , color : " orange " , calories : 45 } ,
{ name : " banana " , color : " yellow " , calories : 105 } ,
];

fruits [0]. name ; // " apple "

// forEach , map , filter , reduce work on arrays of objects


fruits . forEach ( f = > console . log ( f . name ) ) ;

const names = fruits . map ( f = > f . name ) ;

const lowCal = fruits . filter ( f = > f . calories < 100) ;

const maxCal = fruits . reduce (( max , f ) = > f . calories > max . calories ? f :
max ) ;

46 1 Sorting
(#48)
// Sort strings ( lexicographic )
[ " banana " ," apple " ," cherry " ]. sort () ; // alphabetical

// Sort numbers ( need comparison function )


[10 , 2 , 5 , 1]. sort (( a , b ) = > a - b ) ; // ascending
[10 , 2 , 5 , 1]. sort (( a , b ) = > b - a ) ; // descending

// Sort objects by property


const people = [
{ name : " Sandy " , age : 27 } ,
{ name : " SpongeBob " , age : 30 } ,
];
people . sort (( a , b ) = > a . age - b . age ) ; // by age asc
people . sort (( a , b ) = > b . age - a . age ) ; // by age desc

// Sort objects by string property


people . sort (( a , b ) = > a . name . localeCompare ( b . name ) ) ;

47 1 Shuffle
an Array (#49) — Fisher-Yates
function shuffle ( array ) {
for ( let i = array . length - 1; i > 0; i - -) {
const random = Math . floor ( Math . random () * ( i + 1) ) ;
[ array [ i ] , array [ random ]] = [ array [ random ] , array [ i ]]; // swap
}
}

const deck = [ " A " ," 2 " ," 3 " ," 4 " ," 5 " ," 6 " ," 7 " ," 8 " ," 9 " ," 10 " ," J " ," Q " ," K " ];
shuffle ( deck ) ;

Avoid using .sort(() => [Link]() - 0.5) — it’s not uniformly random. Use the Fisher-
Yates algorithm above.

24
JavaScript Complete Reference BroCode Course

48 1 Date
Objects (#50)
const now = new Date () ; // current date / time
const d = new Date (2024 , 0 , 1 , 2 , 3 , 4) ; // Jan 1 , 2024 02:03:04
const d2 = new Date ( " 2024 -01 -02 T12 :00:00 Z " ) ;

// Getters
now . getFullYear () // e . g . 2024
now . getMonth () // 0= Jan 11= Dec
now . getDate () // day of month
now . getDay () // 0= Sun 6= Sat
now . getHours ()
now . getMinutes ()
now . getSeconds ()

// Setters
now . setFullYear (2025) ;
now . setMonth (0) ; // January

// Compare dates
new Date ( " 2024 -12 -31 " ) < new Date ( " 2025 -01 -01 " ) // true

49 1 Closures
(#51)
A closure is a function defined inside another function. The inner function has access to the outer
function’s scope. Useful for private variables and state.
function createCounter () {
let count = 0; // private variable

return {
increment () { count ++; console . log ( ‘ Count : $ { count } ‘) ; } ,
getCount () { return count ; }
};
}

const counter = createCounter () ;


counter . increment () ; // Count : 1
counter . increment () ; // Count : 2
counter . getCount () ; // 2
// count is NOT directly accessible from outside

50 1 setTimeou
(#52)
Schedules a function to run once after a delay.
// setTimeout ( callback , delayMs )
setTimeout (() = > alert ( " Hello ! " ) , 3000) ; // run after 3 s

// Cancel before it fires


const id = setTimeout (() = > alert ( " Hello " ) , 3000) ;
clearTimeout ( id ) ; // cancelled !

// setInterval : repeats every N milliseconds


const intervalId = setInterval (() = > {
console . log ( " Tick " ) ;

25
JavaScript Complete Reference BroCode Course

} , 1000) ;
clearInterval ( intervalId ) ; // stop it

51 1 Digital
Clock Program (#53)
function updateClock () {
const now = new Date () ;
let hours = now . getHours () ;
let minutes = now . getMinutes () ;
let seconds = now . getSeconds () ;
const meridiem = hours >= 12 ? " PM " : " AM " ;
hours = hours % 12 || 12;

hours = String ( hours ) . padStart (2 , " 0 " ) ;


minutes = String ( minutes ) . padStart (2 , " 0 " ) ;
seconds = String ( seconds ) . padStart (2 , " 0 " ) ;

document . getElementById ( " clock " ) . textContent =


‘ $ { hours }: $ { minutes }: $ { seconds } $ { meridiem } ‘;
}

updateClock () ; // run immediately


setInterval ( updateClock , 1000) ; // update every second

52 1 ES6
Modules (#55)
Modules allow you to split code into reusable files.
// mathUtil . js export functions
export const PI = 3.14159;
export function getCircumference ( r ) { return 2 * PI * r ; }
export function getArea ( r ) { return PI * r * r ; }

// index . js import functions


import { PI , getCircumference , getArea } from " ./ mathUtil . js " ;
console . log ( PI ) ;
console . log ( getCircumference (10) ) ;

In your HTML file, add type="module" to the script tag: <script type="module" src="[Link]">

53 1 Asynchron
Code (#56)
Synchronous code executes line by line. Asynchronous code allows operations to run without
blocking.
// Synchronous : executes in order
console . log ( " Task 1 " ) ;
console . log ( " Task 2 " ) ;
console . log ( " Task 3 " ) ;

// Asynchronous : setTimeout moves out of normal flow


setTimeout (() = > console . log ( " Task 1 " ) , 3000) ; // runs last !
console . log ( " Task 2 " ) ;
console . log ( " Task 3 " ) ;
// Output : Task 2 , Task 3 , Task 1

26
JavaScript Complete Reference BroCode Course

Asynchronous operations include: network requests, reading files, database queries, timers.

54 1 Error
Handling (#57)
try {
// dangerous code
let result = 10 / x ;
if ( isNaN ( result ) ) throw new Error ( " Not a number ! " ) ;
} catch ( error ) {
console . error ( error ) ; // handle it gracefully
} finally {
// always runs ( cleanup )
console . log ( " Done . " ) ;
}

// Custom errors
function divide (a , b ) {
if ( b === 0) throw new Error ( " Cannot divide by zero . " ) ;
if ( isNaN ( a ) || isNaN ( b ) ) throw new Error ( " Enter numbers only . " ) ;
return a / b ;
}

55 1 What
is the DOM? (#59)
The Document Object Model is a JavaScript object representing the web page. It provides an
API to interact with HTML elements.
console . log ( document ) ; // entire HTML document
document . title = " My Website " ; // change title

// Change background color


document . body . style . backgroundColor = " hsl (0 , 0% , 15%) " ;

// Select elements
document . getElementById ( " id " ) ;
document . g e t E l e m e n t s B y C l a s s N a m e ( " class " ) ;
document . g e t E l e m e n t s B y T a g N a m e ( " p " ) ;
document . querySelector ( " . class " ) ; // first match
document . querySelectorAll ( " . class " ) ; // all matches ( NodeList )

56 1 Element
Selectors (#60)

Method Returns Notes


getElementById Element or null by id attribute
getElementsByClassName HTMLCollection by class name
getElementsByTagName HTMLCollection by tag (p, h1. . . )
querySelector First match or null CSS selector
querySelectorAll NodeList CSS selector, all

const el = document . getElementById ( " myId " ) ;


const elems = document . querySelectorAll ( " . fruits " ) ; // NodeList
elems . forEach ( el = > el . style . backgroundColor = " yellow " ) ;

27
JavaScript Complete Reference BroCode Course

// Convert HTMLCollection to Array for array methods


Array . from ( document . g e t E l e m e n t s B y C l a s s N a m e ( " box " ) )
. forEach ( el = > el . style . color = " red " ) ;

57 1 DOM
Navigation (#61)
const list = document . getElementById ( " fruits " ) ;

list . fi rstEle mentCh ild // first child element


list . lastElementChild // last child element
list . nex tE le me nt Si bl in g // next sibling
list . p r e v i o u s E l e m e n t S i b l i n g // previous sibling
list . parentElement // parent element
list . children // HTMLCollection of children

// Example : highlight all children


Array . from ( list . children ) . forEach ( child = > {
child . style . backgroundColor = " yellow " ;
}) ;

58 1 Add
& Change HTML (#62)
Three steps: 1) Create element, 2) Set attributes/content, 3) Append to DOM.
// Step 1: Create
const newH1 = document . createElement ( " h1 " ) ;

// Step 2: Set properties


newH1 . textContent = " I like pizza " ;
newH1 . id = " myH1 " ;
newH1 . style . color = " tomato " ;

// Step 3: Append
document . body . append ( newH1 ) ; // last child
document . body . prepend ( newH1 ) ; // first child

// Insert before specific element


const box2 = document . getElementById ( " box2 " ) ;
document . body . insertBefore ( newH1 , box2 ) ;

// Remove element
document . body . removeChild ( newH1 ) ;
// or : newH1 . remove () ;

59 1 Mouse
Events (#63)
const box = document . getElementById ( " myBox " ) ;

// Add event listener : element . addEventListener ( event , callback )


box . addEventListener ( " click " , ( event ) = > {
event . target . style . backgroundColor = " tomato " ;
event . target . textContent = " Ouch ! " ;
}) ;

28
JavaScript Complete Reference BroCode Course

box . addEventListener ( " mouseover " , ( event ) = > {


event . target . style . backgroundColor = " yellow " ;
}) ;

box . addEventListener ( " mouseout " , ( event ) = > {


event . target . style . backgroundColor = " lightgreen " ;
}) ;

Key event types: click, mouseover, mouseout, mousedown, mouseup, dblclick

60 1 Key
Events (#64)
// Listen on document ( any key )
document . addEventListener ( " keydown " , ( event ) = > {
console . log ( ‘ Key down : $ { event . key } ‘) ;
if ( event . key . startsWith ( " Arrow " ) ) {
event . preventDefault () ; // prevent default scroll
switch ( event . key ) {
case " ArrowUp " : y -= 10; break ;
case " ArrowDown " : y += 10; break ;
case " ArrowLeft " : x -= 10; break ;
case " ArrowRight " : x += 10; break ;
}
box . style . top = ‘ $ { y } px ‘;
box . style . left = ‘ $ { x } px ‘;
}
}) ;

document . addEventListener ( " keyup " , ( event ) = > {


console . log ( ‘ Key up : $ { event . key } ‘) ;
}) ;

61 1 Hide
/ Show HTML (#65)
const img = document . getElementById ( " myImg " ) ;
const btn = document . getElementById ( " myBtn " ) ;

btn . addEventListener ( " click " , () = > {


if ( img . style . display === " none " ) {
img . style . display = " block " ;
btn . textContent = " Hide " ;
} else {
img . style . display = " none " ;
btn . textContent = " Show " ;
}
}) ;

// Use visibility to reserve space


img . style . visibility = " hidden " ; // hidden but space reserved
img . style . visibility = " visible " ;

62 1 NodeLists
(#66)
A NodeList is a static collection of elements returned by querySelectorAll.

29
JavaScript Complete Reference BroCode Course

let buttons = document . querySelectorAll ( " . myButtons " ) ;

// NodeList has forEach ( no map / filter / reduce )


buttons . forEach ( btn = > {
btn . style . backgroundColor = " blue " ;
btn . addEventListener ( " click " , ( e ) = > {
e . target . remove () ;
// re - query to update NodeList
buttons = document . querySelectorAll ( " . myButtons " ) ;
}) ;
}) ;

NodeLists are static — they don’t automatically update when the DOM changes. Re-run
querySelectorAll after DOM changes.

63 1 classList
(#67)
Interact with an element’s CSS classes dynamically.
const btn = document . getElementById ( " myBtn " ) ;

btn . classList . add ( " enabled " ) ; // add class


btn . classList . remove ( " enabled " ) ; // remove class
btn . classList . toggle ( " hover " ) ; // toggle on / off
btn . classList . replace ( " enabled " , " disabled " ) ; // replace
btn . classList . contains ( " active " ) ; // true / false

// Apply CSS class on hover


btn . addEventListener ( " mouseover " , ( e ) = > e . target . classList . add ( " hover " ) ) ;
btn . addEventListener ( " mouseout " , ( e ) = > e . target . classList . remove ( " hover "
));
btn . addEventListener ( " click " , ( e ) = > e . target . classList . replace ( " enabled " ,
" disabled " ) ) ;

64 1 Callback
Hell (#70)
Nesting too many callbacks creates pyramid-shaped unreadable code.
// Callback hell example
task1 (() = > {
task2 (() = > {
task3 (() = > {
task4 (() = > {
console . log ( " All done " ) ;
}) ;
}) ;
}) ;
}) ;
// Hard to read , maintain , and debug !

Solution: Use Promises or async/await instead.

65 1 Promises
(#71)
A Promise manages asynchronous operations. It can be pending, resolved, or rejected.

30
JavaScript Complete Reference BroCode Course

function walkDog () {
return new Promise (( resolve , reject ) = > {
setTimeout (() = > {
const dogWalked = true ;
if ( dogWalked ) resolve ( " You walked the dog ! " ) ;
else reject ( " You didn ’t walk the dog . " ) ;
} , 1500) ;
}) ;
}

// Method chaining instead of callback hell


walkDog ()
. then ( val = > { console . log ( val ) ; return cleanKitchen () ; })
. then ( val = > { console . log ( val ) ; return takeOutTrash () ; })
. then ( val = > { console . log ( val ) ; console . log ( " All done ! " ) ; })
. catch ( err = > console . error ( err ) ) ;

66 1 Async
/ Await (#72)
Write asynchronous code in a synchronous-looking style.
async function doChores () {
try {
const r1 = await walkDog () ;
console . log ( r1 ) ;
const r2 = await cleanKitchen () ;
console . log ( r2 ) ;
const r3 = await takeOutTrash () ;
console . log ( r3 ) ;
console . log ( " All chores done ! " ) ;
} catch ( error ) {
console . error ( error ) ;
}
}

doChores () ;

Key rules: await can only be used inside an async function. async functions always return a
Promise.

67 1 JSON
Files (#73)
JSON (JavaScript Object Notation) is a data interchange format — usually objects or arrays.
// JS object to JSON string
const person = { name : " SpongeBob " , age : 30 };
const jsonStr = JSON . stringify ( person ) ;
// ’{" name ":" SpongeBob " ," age ":30} ’

// JSON string to JS object


const parsed = JSON . parse ( jsonStr ) ;
parsed . name ; // " SpongeBob "

// Fetch a local JSON file


fetch ( " person . json " )
. then ( res = > res . json () )

31
JavaScript Complete Reference BroCode Course

. then ( data = > console . log ( data ) )


. catch ( err = > console . error ( err ) ) ;

68 1 Fetch
Data from an API (#74)
// Basic fetch
fetch ( " https :// api . example . com / data " )
. then ( res = > {
if (! res . ok ) throw new Error ( " Could not fetch resource . " ) ;
return res . json () ;
})
. then ( data = > console . log ( data ) )
. catch ( err = > console . error ( err ) ) ;

// With async / await


async function getData ( url ) {
try {
const response = await fetch ( url ) ;
if (! response . ok ) throw new Error ( " Could not fetch resource . " ) ;
const data = await response . json () ;
return data ;
} catch ( error ) {
console . error ( error ) ;
}
}

// Pokemon API example


async function fetchPokemon ( name ) {
const data = await getData ( ‘ https :// pokeapi . co / api / v2 / pokemon / $ { name } ‘) ;
console . log ( data . name , data . weight ) ;
document . getElementById ( " sprite " ) . src = data . sprites . front_default ;
}

69 1 Projects
Summary

Project Section Key Concepts


Counter #7 onclick, variables, DOM
Random Number #9 [Link], DOM
Num Guessing #21 while loop, conditionals
Temp Conversion #24 radio buttons, formulas
Dice Roller #28 arrays, images, for loop
Password Gen #29 functions, strings, random
Digital Clock #53 setInterval, Date, DOM
Stopwatch #54 setInterval, clearInterval
Calculator #58 eval(), error handling
Rock Paper Scis #68 classList, scoring
Image Slider #69 setInterval, classList
Weather App #75 fetch API, JSON, async

70 1 Quick
Reference Cheat Sheet
1ES6+ Features Summary

32
JavaScript Complete Reference BroCode Course

// Template literals
‘ Hello $ { name }! ‘

// Destructuring
const { a , b } = obj ;
const [x , y ] = arr ;

// Spread / Rest
fn (... arr ) ; // spread
function f (... args ) // rest

// Arrow functions
const fn = ( x ) = > x * 2;

// Classes
class Animal { constructor () {} }
class Dog extends Animal { }

// Modules
export / import

// Promises / async - await


async function f () { await promise ; }

// Optional chaining
obj ?. property ?. nested

// Nullish coalescing
value ?? " default "

1Array Methods Summary

Method Returns
forEach nothing — side effects only
map new array (transformed)
filter new array (filtered)
reduce single value
find first matching element
some true if any match
every true if all match
sort sorted array (in place)
push/pop add/remove from end
unshift/shift add/remove from start
slice new sub-array
splice modify in place
indexOf index or -1
includes true/false

1DOM Quick Reference

el . textContent = " text " ;


el . innerHTML = " <b > bold </ b > " ;
el . style . color = " red " ;
el . setAttribute ( " id " , " x " ) ;
el . getAttribute ( " id " ) ;
el . classList . add / remove / toggle / contains ( " cls " ) ;
el . addEventListener ( " click " , fn ) ;

33
JavaScript Complete Reference BroCode Course

el . appendChild ( child ) ;
el . removeChild ( child ) ;
el . remove () ;

JavaScript Complete Reference — Based on BroCode’s YouTube Course

34

You might also like