JavaScript Full Course: Learn to Code

A comprehensive 12-hour JavaScript course covering variables, operators, DOM manipulation, events, asynchronous programming, APIs, and six real projects (calculator, stopwatch, rock-paper-scissors, image slider, weather app, Pokémon fetcher). Designed for beginners with HTML/CSS knowledge.

Course Overview & Setup

What JavaScript Does

JavaScript is a programming language that runs in web browsers to create dynamic and interactive web pages. It responds to user actions and transforms user input, enabling functionality beyond static HTML and CSS styling.

Project Portfolio Built in Course

Students build six portfolio projects: a digital clock, stopwatch, functioning calculator, rock-paper-scissors game, image slider, and a weather app that fetches live API data.

Development Environment Setup

Use VS Code as a text editor, create a project folder with three files (index.html, style.css, index.js), link them together, and install the Live Server extension for automatic page refresh during development.

JavaScript Fundamentals

Basic Output Methods

Use console.log() to output text to the browser console for debugging, window.alert() to create popup messages, and document.getElementById().textContent to display text on the web page itself.

Variables: Declaration and Assignment

Variables are containers that store values. Create them using the let keyword (declaration), then assign a value with the equals sign. Variable names must be unique; each variable behaves as the value it contains.

Data Types: Numbers, Strings, Booleans

JavaScript has three basic data types: numbers (25, 10.99) for calculations, strings (series of characters in quotes) for text, and booleans (true/false) typically used as flags in programs.

Template Literals for String Insertion

Use backticks (`) instead of quotes to create template literals. Insert variables with ${variableName} syntax to embed values directly into strings without concatenation.

Arithmetic Operators

Perform math with +, -, *, / (division), ** (exponent), and % (modulus for remainders). Follow operator precedence: parentheses, exponents, multiplication/division/modulus, then addition/subtraction.

Augmented Assignment Operators

Shorthand for reassigning variables: += (add and assign), -= (subtract and assign), *= (multiply and assign), /= (divide and assign), ++ (increment by 1), -- (decrement by 1).

Type Conversion

Convert data types using Number() to convert strings to numbers, String() to convert to text, or Boolean() to convert to true/false. Essential when accepting user input (always a string) that needs math operations.

Constants with const Keyword

Use const for variables that should never change (like pi = 3.14159). Once assigned, constants cannot be reassigned; attempting to do so throws a TypeError. Capitalize constant names by convention.

User Input & Interaction

Two Methods to Accept User Input

Easy method: use window.prompt() for a popup dialog. Professional method: create an HTML text box with <input type='text'> and a submit button, then read the value with .value property.

Handling Form Submission

Attach an onclick event handler to a button or use a form's submit event. Call preventDefault() to stop page refresh, then read input values and process them.

Control Flow: Conditionals

If/Else Statements

Execute code conditionally: if a condition is true, run one block; else run another. Use comparison operators (>, <, >=, <=, ===, !==) to test conditions.

Nested If Statements

Place if statements inside other if statements to test multiple conditions in sequence. Indentation shows nesting level. Only inner code runs if all outer conditions are true.

Else If Statements

Check multiple conditions in order: if first condition is false, check else if conditions. Order matters—once a condition is true, remaining conditions are skipped.

Ternary Operator

Shorthand for if/else: condition ? valueIfTrue : valueIfFalse. Useful for assigning variables based on a condition in a single line.

Switch Statements

Efficient alternative to many else if statements. Examine a value against matching cases; if a case matches, execute code until a break statement. Include a default case for no matches.

DOM Manipulation & Events

Selecting HTML Elements

Use document.getElementById(id) to select by ID, document.querySelector(selector) for CSS selectors, or document.querySelectorAll() to select multiple elements as a NodeList.

Changing Element Properties

Modify .textContent to change visible text, .value to get/set input values, .style.property to change CSS, or .classList to add/remove CSS classes.

Event Listeners

Attach event listeners to elements to trigger functions when events occur. Use element.addEventListener(eventType, callbackFunction) or set onclick/onsubmit attributes directly.

Checked Property for Checkboxes & Radio Buttons

Access element.checked to determine if a checkbox or radio button is selected (returns true/false). Group radio buttons with the same name attribute so only one can be selected.

ClassList for CSS Class Management

Use element.classList.add(className) to add a CSS class, .remove() to remove, .toggle() to switch on/off, and .contains() to check if a class exists.

String Methods & Manipulation

Common String Methods

charAt(index) gets a character at position, indexOf() finds first occurrence, length property gets string size, toUpperCase()/toLowerCase() change case, trim() removes whitespace.

String Validation Methods

startsWith() checks if string begins with characters, endsWith() checks the end, includes() checks if substring exists anywhere. All return true/false.

String Slicing

Use slice(startIndex, endIndex) to extract a substring. Start index is inclusive, end index is exclusive. Negative indices count from the end (-1 is last character).

String Replacement & Formatting

replace() changes first occurrence, replaceAll() changes all occurrences. padStart() and padEnd() add characters to reach a specified length.

Math Object & Random Numbers

Math Object Properties & Methods

Access Math.PI (3.14159...) and Math.E for constants. Use Math.round(), Math.floor(), Math.ceil(), Math.abs() for rounding and absolute values.

Generating Random Numbers

Math.random() generates decimal 0-1. Multiply by max, floor result, add min to get integer range: Math.floor(Math.random() * (max - min + 1)) + min.

Asynchronous Programming

Callback Hell Problem

Nesting callbacks within callbacks creates pyramid-shaped, hard-to-read code. Occurs when multiple asynchronous tasks must complete in sequence, each waiting for the previous to finish.

Promises for Async Operations

A Promise wraps asynchronous code and returns either resolved (success) or rejected (failure). Chain .then() methods to handle results and .catch() to handle errors.

Async/Await Syntax

Declare function with async keyword to use await inside. await pauses execution until a promise resolves, allowing synchronous-looking code for async operations. Wrap in try/catch for error handling.

Working with APIs & JSON

JSON Format

JSON (JavaScript Object Notation) is a text format for data exchange. Objects use key-value pairs in curly braces; arrays use square brackets. JSON.stringify() converts objects to strings; JSON.parse() converts strings back to objects.

Fetch API for HTTP Requests

fetch(url) makes HTTP requests to retrieve resources. Returns a promise with a response object. Call response.json() to parse JSON data. Check response.ok before processing.

API Integration Example

Construct API URLs with query parameters, fetch data, parse JSON, and display results. Handle errors gracefully if API is unavailable or data not found.

Project 1: Counter Program

Counter Program Structure

Create buttons to increase, decrease, and reset a counter. Store count in a variable, update display on each button click, and use CSS for styling.

Project 2: Rock-Paper-Scissors Game

Game Logic Implementation

Create three buttons for player choices. Generate random computer choice. Compare choices using switch statement. Display winner and update score. Use CSS classes to color results (green for win, red for loss).

Project 3: Image Slider

Image Slider Implementation

Store images in a NodeList. Use setInterval() to auto-advance slides every 5 seconds. Previous/Next buttons manually navigate. Reset index when reaching start/end to loop. Add fade animation with CSS keyframes.

Project 4: Weather App

Weather App with OpenWeatherMap API

Fetch weather data from OpenWeatherMap API using city name. Parse JSON response to extract temperature, humidity, description. Convert Kelvin to Celsius/Fahrenheit. Display weather emoji based on weather code. Handle errors for invalid cities.

Weather Code to Emoji Mapping

Weather API returns codes: 200-299 (thunderstorm), 300-399 (drizzle), 500-599 (rain), 600-699 (snow), 700-799 (atmosphere), 800 (clear), 801-809 (clouds). Map each range to appropriate emoji.

Notable quotes

By using JavaScript we can respond to user actions and transform user input. — Instructor
A variable is a container that stores a value. The variable behaves as if it were the value it contains. — Instructor
Promises promise to return a value. They will be pending until they complete, then either resolved or rejected. — Instructor

Action items

  • Download and install VS Code from code.visualstudio.com
  • Create a project folder with index.html, style.css, and index.js files
  • Link CSS and JavaScript files to HTML using <link> and <script> tags
  • Install the Live Server extension in VS Code
  • Build the counter program with increase, decrease, and reset buttons
  • Create a rock-paper-scissors game with score tracking
  • Build an image slider with auto-advance and manual navigation
  • Sign up for a free OpenWeatherMap API key at openweathermap.org
  • Create a weather app that fetches and displays weather data
  • Build a Pokémon image fetcher using the Pokémon API
Bro Code
12 hr video
3 min read
JavaScript Full Course: Learn to Code
You just saved 11 hr 57 min.
The big takeaway
A comprehensive 12-hour JavaScript course covering variables, operators, DOM manipulation, events, asynchronous programming, APIs, and six real projects (calculator, stopwatch, rock-paper-scissors, image slider, weather app, Pokémon fetcher). Designed for beginners with HTML/CSS knowledge.
Course Overview & Setup
What JavaScript Does
JavaScript is a programming language that runs in web browsers to create dynamic and interactive web pages. It responds to user actions and transforms user input, enabling functionality beyond static HTML and CSS styling.
Project Portfolio Built in Course
Students build six portfolio projects: a digital clock, stopwatch, functioning calculator, rock-paper-scissors game, image slider, and a weather app that fetches live API data.
1
Digital Clock
2
Stopwatch
3
Calculator
4
Rock-Paper-Scissors
5
Image Slider
6
Weather App
Six projects completed throughout the course
Development Environment Setup
Use VS Code as a text editor, create a project folder with three files (index.html, style.css, index.js), link them together, and install the Live Server extension for automatic page refresh during development.
1
Download VS Code from code.visualstudio.com
2
Create project folder on desktop
3
Create index.html, style.css, index.js files
4
Link CSS file with <link> tag in HTML
5
Link JavaScript file with <script> tag at bottom of HTML body
6
Install Live Server extension in VS Code
7
Right-click HTML file and open with Live Server
Setting up your JavaScript development environment
JavaScript Fundamentals
Basic Output Methods
Use console.log() to output text to the browser console for debugging, window.alert() to create popup messages, and document.getElementById().textContent to display text on the web page itself.
Variables: Declaration and Assignment
Variables are containers that store values. Create them using the let keyword (declaration), then assign a value with the equals sign. Variable names must be unique; each variable behaves as the value it contains.
1
Declare variable with 'let' keyword: let x;
2
Assign value with equals sign: x = 100;
3
Or combine both: let x = 100;
4
Use variable in expressions: console.log(x)
Creating and using variables in JavaScript
Data Types: Numbers, Strings, Booleans
JavaScript has three basic data types: numbers (25, 10.99) for calculations, strings (series of characters in quotes) for text, and booleans (true/false) typically used as flags in programs.
1
Number
25, 10.99, 3.14
2
String
"hello", 'pizza'
3
Boolean
true, false
Three basic JavaScript data types
Template Literals for String Insertion
Use backticks (`) instead of quotes to create template literals. Insert variables with ${variableName} syntax to embed values directly into strings without concatenation.
Arithmetic Operators
Perform math with +, -, *, / (division), ** (exponent), and % (modulus for remainders). Follow operator precedence: parentheses, exponents, multiplication/division/modulus, then addition/subtraction.
1
+
Addition
2
-
Subtraction
3
*
Multiplication
4
/
Division
5
**
Exponent
6
%
Modulus (remainder)
Arithmetic operators in JavaScript
Augmented Assignment Operators
Shorthand for reassigning variables: += (add and assign), -= (subtract and assign), *= (multiply and assign), /= (divide and assign), ++ (increment by 1), -- (decrement by 1).
Type Conversion
Convert data types using Number() to convert strings to numbers, String() to convert to text, or Boolean() to convert to true/false. Essential when accepting user input (always a string) that needs math operations.
1
User input from text box is always a string
2
Use Number() function to convert to number
3
Use Boolean() to check if input is empty
4
Now safe to use in arithmetic or conditionals
Type conversion workflow for user input
Constants with const Keyword
Use const for variables that should never change (like pi = 3.14159). Once assigned, constants cannot be reassigned; attempting to do so throws a TypeError. Capitalize constant names by convention.
User Input & Interaction
Two Methods to Accept User Input
Easy method: use window.prompt() for a popup dialog. Professional method: create an HTML text box with <input type='text'> and a submit button, then read the value with .value property.
window.prompt()
1 line of code
HTML input + button
3 elements
Complexity comparison of input methods
Handling Form Submission
Attach an onclick event handler to a button or use a form's submit event. Call preventDefault() to stop page refresh, then read input values and process them.
Control Flow: Conditionals
If/Else Statements
Execute code conditionally: if a condition is true, run one block; else run another. Use comparison operators (>, <, >=, <=, ===, !==) to test conditions.
1
Write condition in parentheses: if (age >= 18)
2
Execute code in curly braces if true
3
Use else clause for alternative code
4
Use else if for additional conditions
Structure of if/else conditional statements
Nested If Statements
Place if statements inside other if statements to test multiple conditions in sequence. Indentation shows nesting level. Only inner code runs if all outer conditions are true.
Else If Statements
Check multiple conditions in order: if first condition is false, check else if conditions. Order matters—once a condition is true, remaining conditions are skipped.
Ternary Operator
Shorthand for if/else: condition ? valueIfTrue : valueIfFalse. Useful for assigning variables based on a condition in a single line.
Switch Statements
Efficient alternative to many else if statements. Examine a value against matching cases; if a case matches, execute code until a break statement. Include a default case for no matches.
1
switch(value) { examine value
2
case 1: execute if value === 1
3
case 2: execute if value === 2
4
default: execute if no matches
5
break; exits switch after each case
Switch statement structure
DOM Manipulation & Events
Selecting HTML Elements
Use document.getElementById(id) to select by ID, document.querySelector(selector) for CSS selectors, or document.querySelectorAll() to select multiple elements as a NodeList.
Changing Element Properties
Modify .textContent to change visible text, .value to get/set input values, .style.property to change CSS, or .classList to add/remove CSS classes.
Event Listeners
Attach event listeners to elements to trigger functions when events occur. Use element.addEventListener(eventType, callbackFunction) or set onclick/onsubmit attributes directly.
1
click
User clicks element
2
submit
Form submitted
3
mouseover
Cursor enters element
4
mouseout
Cursor leaves element
5
change
Input value changes
Common JavaScript event types
Checked Property for Checkboxes & Radio Buttons
Access element.checked to determine if a checkbox or radio button is selected (returns true/false). Group radio buttons with the same name attribute so only one can be selected.
ClassList for CSS Class Management
Use element.classList.add(className) to add a CSS class, .remove() to remove, .toggle() to switch on/off, and .contains() to check if a class exists.
String Methods & Manipulation
Common String Methods
charAt(index) gets a character at position, indexOf() finds first occurrence, length property gets string size, toUpperCase()/toLowerCase() change case, trim() removes whitespace.
1
charAt()
Get character at index
2
indexOf()
Find first occurrence
3
length
Get string size
4
toUpperCase()
Convert to uppercase
5
toLowerCase()
Convert to lowercase
6
trim()
Remove whitespace
Essential string methods in JavaScript
String Validation Methods
startsWith() checks if string begins with characters, endsWith() checks the end, includes() checks if substring exists anywhere. All return true/false.
String Slicing
Use slice(startIndex, endIndex) to extract a substring. Start index is inclusive, end index is exclusive. Negative indices count from the end (-1 is last character).
1
slice(0, 3) extracts first 3 characters
2
slice(4) extracts from index 4 to end
3
slice(-3) extracts last 3 characters
4
Original string unchanged
String slicing with slice() method
String Replacement & Formatting
replace() changes first occurrence, replaceAll() changes all occurrences. padStart() and padEnd() add characters to reach a specified length.
Math Object & Random Numbers
Math Object Properties & Methods
Access Math.PI (3.14159...) and Math.E for constants. Use Math.round(), Math.floor(), Math.ceil(), Math.abs() for rounding and absolute values.
1
Math.PI
3.14159
2
Math.round()
Round to nearest
3
Math.floor()
Round down
4
Math.ceil()
Round up
5
Math.abs()
Absolute value
Key Math object methods
Generating Random Numbers
Math.random() generates decimal 0-1. Multiply by max, floor result, add min to get integer range: Math.floor(Math.random() * (max - min + 1)) + min.
1
Math.random() returns 0 to 0.999...
2
Multiply by range size (e.g., * 6 for 1-6 dice)
3
Math.floor() removes decimals
4
Add minimum value to shift range
Generating random integers in a range
Asynchronous Programming
Callback Hell Problem
Nesting callbacks within callbacks creates pyramid-shaped, hard-to-read code. Occurs when multiple asynchronous tasks must complete in sequence, each waiting for the previous to finish.
Promises for Async Operations
A Promise wraps asynchronous code and returns either resolved (success) or rejected (failure). Chain .then() methods to handle results and .catch() to handle errors.
1
Create promise: new Promise((resolve, reject) => {})
2
Call resolve() on success with value
3
Call reject() on failure with error
4
Chain .then() to handle resolved value
5
Chain .catch() to handle rejection
Promise workflow for async operations
Async/Await Syntax
Declare function with async keyword to use await inside. await pauses execution until a promise resolves, allowing synchronous-looking code for async operations. Wrap in try/catch for error handling.
1
Declare function with 'async' keyword
2
Use 'await' before promises to pause
3
Code reads top-to-bottom like synchronous
4
Wrap in try/catch for error handling
Async/await simplifies promise handling
Working with APIs & JSON
JSON Format
JSON (JavaScript Object Notation) is a text format for data exchange. Objects use key-value pairs in curly braces; arrays use square brackets. JSON.stringify() converts objects to strings; JSON.parse() converts strings back to objects.
Fetch API for HTTP Requests
fetch(url) makes HTTP requests to retrieve resources. Returns a promise with a response object. Call response.json() to parse JSON data. Check response.ok before processing.
1
fetch(url) initiates request
2
Returns promise with response object
3
Check response.ok (status 200-299)
4
Call response.json() to parse data
5
Use .then() or await to handle result
Fetching data from an API
API Integration Example
Construct API URLs with query parameters, fetch data, parse JSON, and display results. Handle errors gracefully if API is unavailable or data not found.
Project 1: Counter Program
Counter Program Structure
Create buttons to increase, decrease, and reset a counter. Store count in a variable, update display on each button click, and use CSS for styling.
Project 2: Rock-Paper-Scissors Game
Game Logic Implementation
Create three buttons for player choices. Generate random computer choice. Compare choices using switch statement. Display winner and update score. Use CSS classes to color results (green for win, red for loss).
1
Player clicks rock, paper, or scissors button
2
Generate random computer choice (0-2)
3
Compare choices with switch statement
4
Determine winner and update score
5
Display result with color coding
Rock-paper-scissors game flow
Project 3: Image Slider
Image Slider Implementation
Store images in a NodeList. Use setInterval() to auto-advance slides every 5 seconds. Previous/Next buttons manually navigate. Reset index when reaching start/end to loop. Add fade animation with CSS keyframes.
1
Store all images in NodeList
2
Initialize with first image displayed
3
setInterval() auto-advances every 5 seconds
4
Previous/Next buttons manually navigate
5
Reset index at boundaries to loop
6
Fade animation on slide change
Image slider workflow
Project 4: Weather App
Weather App with OpenWeatherMap API
Fetch weather data from OpenWeatherMap API using city name. Parse JSON response to extract temperature, humidity, description. Convert Kelvin to Celsius/Fahrenheit. Display weather emoji based on weather code. Handle errors for invalid cities.
1
User enters city name in text box
2
Construct API URL with city and API key
3
Fetch data and parse JSON response
4
Extract name, temp, humidity, description
5
Convert temperature from Kelvin
6
Select emoji based on weather code
7
Display in card format or show error
Weather app data flow
Weather Code to Emoji Mapping
Weather API returns codes: 200-299 (thunderstorm), 300-399 (drizzle), 500-599 (rain), 600-699 (snow), 700-799 (atmosphere), 800 (clear), 801-809 (clouds). Map each range to appropriate emoji.
1
200-299
Thunderstorm ⛈
2
300-399
Drizzle 🌧
3
500-599
Rain 🌧
4
600-699
Snow ❄
5
700-799
Atmosphere 🌫
6
800
Clear ☀
7
801-809
Clouds ☁
Weather code to emoji mapping
Worth quoting
"By using JavaScript we can respond to user actions and transform user input."
— Instructor, at [1:02]
"A variable is a container that stores a value. The variable behaves as if it were the value it contains."
— Instructor, at [12:51]
"Promises promise to return a value. They will be pending until they complete, then either resolved or rejected."
— Instructor, at [652:18]
Try this
Download and install VS Code from code.visualstudio.com
Create a project folder with index.html, style.css, and index.js files
Link CSS and JavaScript files to HTML using <link> and <script> tags
Install the Live Server extension in VS Code
Build the counter program with increase, decrease, and reset buttons
Create a rock-paper-scissors game with score tracking
Build an image slider with auto-advance and manual navigation
Sign up for a free OpenWeatherMap API key at openweathermap.org
Create a weather app that fetches and displays weather data
Build a Pokémon image fetcher using the Pokémon API
Made with Glimpse by Wozart
glimpse.wozart.com/v/2wd4llc6
Share this infographic

More like this