JavaScript Complete Reference
JavaScript Complete Reference
JavaScript
Complete Study Reference
0 1 Contents
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
6 Constants (#6) 4
10 If Statements (#10) 6
10.0.1 Nested If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
10.0.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1
JavaScript Complete Reference BroCode Course
22 Functions (#22) 11
25 Arrays (#25) 12
28 Callbacks (#30) 14
29 forEach() (#31) 14
30 map() (#32) 14
31 filter() (#33) 15
32 reduce() (#34) 15
37 Constructors (#39) 17
2
JavaScript Complete Reference BroCode Course
38 Classes (#40) 17
40 Inheritance (#42) 18
43 Destructuring (#45) 20
46 Sorting (#48) 21
49 Closures (#51) 22
50 setTimeout() (#52) 22
62 NodeLists (#66) 26
63 classList (#67) 27
3
JavaScript Complete Reference BroCode Course
65 Promises (#71) 27
69 Projects Summary 29
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
1Comments
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
1Template Literals
1typeof Operator
3 1 Arithmeti
Operators (#3)
1Increment / Decrement
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 ) ;
// HTML : < input id =" myText " type =" text " > < button id =" myBtn " > Submit </ button
>
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 ;
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 >
8 1 Math
Object (#8)
The Math object provides mathematical constants and methods.
1Properties
Math . PI // 3.14159...
Math . E // 2.71828...
1Common Methods
// 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
10 1 If
Statements (#10)
let age = 18;
1Nested If Statements
1Comparison Operators
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 " >
9
JavaScript Complete Reference BroCode Course
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 " ;
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 ‘) ;
}
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 ";
15 1 String
Slicing (#15)
Create a substring from a portion of a string without altering the original.
const fullName = " Bro Code " ;
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 : " ) ;
11
JavaScript Complete Reference BroCode Course
17 1 Logical
Operators (#17)
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
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
1Login Example
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
}
21 1 Number
Guessing Game (#21)
const minNum = 1 , maxNum = 100;
13
JavaScript Complete Reference BroCode Course
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
// 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 ) ;
}
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
25 1 Arrays
(#25)
An array can store multiple values in a single variable.
let fruits = [ " apple " , " orange " , " banana " ];
// 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
26 1 Spread
Operator (#26)
The spread operator (...) unpacks elements of an array or string.
let nums = [1 , 2 , 3 , 4 , 5];
// 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 " ) ;
}
// 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];
30 1 map()
(#32)
Like forEach but returns a new array. Original is preserved.
const nums = [1 , 2 , 3 , 4 , 5];
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 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];
// 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 () ;
18
JavaScript Complete Reference BroCode Course
setTimeout ( function () {
console . log ( " Hello after 3 s " ) ;
} , 3000) ;
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 } ‘) ;
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
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 ; }
}
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 ‘) ; }
}
21
JavaScript Complete Reference BroCode Course
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 ‘) ;
}
}
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 ;
}
22
JavaScript Complete Reference BroCode Course
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 "
}
};
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 } ,
];
const maxCal = fruits . reduce (( max , f ) = > f . calories > max . calories ? f :
max ) ;
46 1 Sorting
(#48)
// Sort strings ( lexicographic )
[ " banana " ," apple " ," cherry " ]. sort () ; // alphabetical
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 ; }
};
}
50 1 setTimeou
(#52)
Schedules a function to run once after a delay.
// setTimeout ( callback , delayMs )
setTimeout (() = > alert ( " Hello ! " ) , 3000) ; // run after 3 s
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;
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 ; }
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 " ) ;
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
// 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)
27
JavaScript Complete Reference BroCode Course
57 1 DOM
Navigation (#61)
const list = document . getElementById ( " fruits " ) ;
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 3: Append
document . body . append ( newH1 ) ; // last child
document . body . prepend ( newH1 ) ; // first child
// Remove element
document . body . removeChild ( newH1 ) ;
// or : newH1 . remove () ;
59 1 Mouse
Events (#63)
const box = document . getElementById ( " myBox " ) ;
28
JavaScript Complete Reference BroCode Course
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 ‘;
}
}) ;
61 1 Hide
/ Show HTML (#65)
const img = document . getElementById ( " myImg " ) ;
const btn = document . getElementById ( " myBtn " ) ;
62 1 NodeLists
(#66)
A NodeList is a static collection of elements returned by querySelectorAll.
29
JavaScript Complete Reference BroCode Course
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 " ) ;
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 !
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) ;
}) ;
}
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} ’
31
JavaScript Complete Reference BroCode Course
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 ) ) ;
69 1 Projects
Summary
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
// Optional chaining
obj ?. property ?. nested
// Nullish coalescing
value ?? " default "
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
33
JavaScript Complete Reference BroCode Course
el . appendChild ( child ) ;
el . removeChild ( child ) ;
el . remove () ;
34