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