JavaScript for Beginners
JavaScript is a programming language used to make webpages interactive and responsive to user actions.
While HTML provides the structure of a webpage and CSS controls its appearance, JavaScript allows the page to respond to button clicks, validate forms, update content, perform calculations and create dynamic user experiences.
In this beginner-friendly course, you will learn variables, data types, operators, conditions, loops, functions, arrays, objects, browser events and the Document Object Model.
Learning Outcomes
What you will be able to do after completing this course.
By the end of this course, you should be able to write clear beginner JavaScript and use it to create an interactive webpage.
- Explain what JavaScript is and how it is used in web development.
- Understand how JavaScript works together with HTML and CSS.
- Add JavaScript directly inside an HTML document.
- Connect an external JavaScript file to a webpage.
- Use the browser developer console to run and test JavaScript code.
- Display information using console.log().
- Write JavaScript comments to explain and organise code.
- Create variables using let and const.
- Understand strings, numbers, booleans, arrays and objects.
- Use arithmetic, assignment, comparison and logical operators.
- Combine text using concatenation and template literals.
- Use if, else if, else and switch statements.
- Create repeated processes using for and while loops.
- Define and call reusable functions.
- Pass parameters and return values from functions.
- Create, access and update arrays.
- Create objects containing related properties and values.
- Select HTML elements using getElementById() and querySelector().
- Change text, HTML content, attributes, styles and CSS classes.
- Respond to clicks, keyboard input and form submission.
- Read and validate values entered into form fields.
- Show, hide, create, insert and remove HTML elements.
- Use basic number, string and array methods.
- Understand local and global variable scope.
- Recognise common syntax and runtime errors.
- Use browser developer tools to troubleshoot JavaScript.
- Organise code using clear naming and indentation.
- Create a simple interactive webpage using HTML, CSS and JavaScript.
Course Roadmap
Follow the lessons in order or select a topic to review.
Understanding JavaScript in Web Development
Learn how HTML, CSS and JavaScript work together.
HTML
Provides webpage structure and content.
CSS
Controls layout, colour and appearance.
JavaScript
Adds logic, interaction and dynamic behaviour.
Inline JavaScript
<script>
console.log("Hello from JavaScript");
</script>
External JavaScript
<script src="/app.js"></script>
Practice Activity
- Create a basic HTML page.
- Add one inline script.
- Create app.js and connect it to the page.
Using the Console and Writing Comments
Test code and add useful explanations.
Console Output
console.log("JavaScript is running");
console.warn("Check this value");
console.error("Something went wrong");
Comments
// This is a single-line comment
/*
This is a multi-line comment
*/
- Use console.log() to inspect values.
- Use console.table() for arrays and objects.
- Write comments that explain important reasoning.
- Remove unnecessary debugging output before publishing.
Console Exercise
- Open the browser console.
- Run three JavaScript statements.
- Write one warning and one error.
- Add both comment styles.
Variables and Basic Data Types
Store information using let and const.
Creating Variables
let score = 0;
let userName = "Lemon";
const courseName = "JavaScript for Beginners";
| Type | Example |
|---|---|
| String | "Hello" |
| Number | 42 |
| Boolean | true |
| Array | ["HTML", "CSS"] |
| Object | { name: "Lemon" } |
| Undefined | A variable without a value |
const when the variable should not be reassigned and let when its value may change.Variable Exercise
- Create string, number and boolean variables.
- Display each value in the console.
- Change one let variable.
- Try reassigning a const and inspect the error.
Operators, Concatenation and Template Literals
Perform calculations and combine text with values.
| Group | Examples |
|---|---|
| Arithmetic | + - * / % |
| Assignment | = += -= |
| Comparison | === !== > < >= <= |
| Logical | && || ! |
Template Literal
const name = "Lemon";
const score = 95;
const message = `Hello, ${name}. Your score is ${score}.`;
console.log(message);
Operator Exercise
- Create two number variables.
- Calculate their sum and product.
- Compare the values.
- Build a sentence with a template literal.
Making Decisions with Conditions
Run different code based on values.
If, Else If and Else
const score = 82;
if (score >= 80) {
console.log("Excellent");
} else if (score >= 50) {
console.log("Passed");
} else {
console.log("Try again");
}
Switch
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost the weekend");
break;
default:
console.log("Regular day");
}
=== where practical.Condition Exercise
- Create a score variable.
- Write an if, else if and else decision.
- Create a switch statement with three cases.
Repeating Code with Loops
Use for and while loops safely.
For Loop
for (let number = 1; number <= 5; number += 1) {
console.log(number);
}
While Loop
let count = 1;
while (count <= 5) {
console.log(count);
count += 1;
}
- Set a clear starting value.
- Use a condition that eventually becomes false.
- Update the loop variable.
- Avoid unnecessary work inside the loop.
Loop Exercise
- Print numbers 1 to 10.
- Print even numbers from 2 to 20.
- Create a while loop that stops at 5.
Creating Reusable Functions
Group instructions, pass parameters and return values.
Basic Function
function greetUser() {
console.log("Welcome!");
}
greetUser();
Parameters and Return
function calculateTotal(price, quantity) {
return price * quantity;
}
const result = calculateTotal(25, 3);
console.log(result);
Arrow Function
const addNumbers = (first, second) => {
return first + second;
};
calculateTotal or validateForm.Function Exercise
- Create a greeting function.
- Add a name parameter.
- Create a function that returns a calculation.
- Call each function more than once.
Storing Multiple Values in Arrays
Create, access, update and remove array items.
Create and Access
const skills = ["HTML", "CSS", "JavaScript"];
console.log(skills[0]);
console.log(skills.length);
Update the Array
skills.push("Git");
skills.pop();
skills.unshift("Web Design");
skills.shift();
skills[1] = "Modern CSS";
Loop Through Items
skills.forEach(function (skill) {
console.log(skill);
});
Array Exercise
- Create an array with four items.
- Display the first and last items.
- Add and remove an item.
- Display every item with forEach().
Grouping Related Data with Objects
Store properties and values together.
Create an Object
const student = {
name: "Lemon",
course: "JavaScript",
completed: false
};
Access and Update
console.log(student.name);
console.log(student["course"]);
student.completed = true;
student.level = "Beginner";
Object Method
const user = {
name: "Lemon",
greet: function () {
return `Hello, ${this.name}`;
}
};
console.log(user.greet());
Object Exercise
- Create an object with four properties.
- Display two properties.
- Update one property.
- Add a simple method.
Selecting Elements with the DOM
Connect JavaScript to webpage elements.
Example HTML
<h2 id="page-title">Welcome</h2>
<button class="action-button">Click Me</button>
JavaScript Selectors
const title = document.getElementById("page-title");
const button = document.querySelector(".action-button");
const items = document.querySelectorAll(".list-item");
null. Check spelling and script timing.DOM Selection Exercise
- Create a heading with an ID.
- Create a button with a class.
- Select both elements.
- Display them in the console.
Changing Content, Attributes and Styles
Modify a webpage after it loads.
Change Text and HTML
const title = document.getElementById("page-title");
const box = document.querySelector(".message-box");
title.textContent = "JavaScript Updated This Text";
box.innerHTML = "<strong>Success!</strong>";
Classes and Attributes
box.classList.add("is-active");
box.classList.remove("is-hidden");
box.classList.toggle("highlight");
box.setAttribute("aria-live", "polite");
Inline Style
box.style.backgroundColor = "#eef8e8";
box.style.padding = "16px";
Content Exercise
- Change a heading with textContent.
- Add a CSS class to a box.
- Set one attribute.
- Toggle a highlight class.
Responding to Browser Events
Run code when users click, type or submit forms.
Click Event
const button = document.querySelector("#action-button");
button.addEventListener("click", function () {
console.log("Button clicked");
});
Input Event
const input = document.querySelector("#name-input");
input.addEventListener("input", function (event) {
console.log(event.target.value);
});
- click
- input
- change
- keydown
- submit
- mouseenter
Event Exercise
- Respond to a button click.
- Add a text input.
- Display its value while the user types.
- Handle one keyboard event.
Reading and Validating Form Values
Check user input before a form continues.
Example Form
<form id="contact-form">
<input id="user-name" type="text">
<button type="submit">Submit</button>
</form>
<p id="form-message"></p>
Validation Script
const form = document.querySelector("#contact-form");
const nameInput = document.querySelector("#user-name");
const message = document.querySelector("#form-message");
form.addEventListener("submit", function (event) {
event.preventDefault();
const name = nameInput.value.trim();
if (name === "") {
message.textContent = "Please enter your name.";
return;
}
message.textContent = `Welcome, ${name}!`;
});
Form Exercise
- Create name and email fields.
- Prevent default submission.
- Check for empty values.
- Display a success or error message.
Showing, Hiding, Creating and Removing Elements
Build webpage content dynamically.
Show and Hide
const panel = document.querySelector("#details-panel");
panel.hidden = true;
panel.hidden = false;
Create and Insert
const list = document.querySelector("#task-list");
const item = document.createElement("li");
item.textContent = "Learn JavaScript";
list.appendChild(item);
Remove
item.remove();
- Use textContent for plain text.
- Create elements with createElement().
- Add classes for styling.
- Avoid inserting untrusted content with innerHTML.
Dynamic Element Exercise
- Create a show-and-hide button.
- Create a list item from input.
- Insert it into a list.
- Add a remove button.
Useful Number, String and Array Methods
Transform and inspect common values.
| Type | Methods |
|---|---|
| String | trim(), toLowerCase(), includes(), slice() |
| Number | Number(), parseInt(), toFixed(), isNaN() |
| Array | push(), pop(), includes(), forEach(), map() |
Examples
const cleanName = " Lemon ".trim();
const formattedPrice = (12.5).toFixed(2);
const skills = ["HTML", "CSS", "JavaScript"];
const hasJavaScript = skills.includes("JavaScript");
const upperSkills = skills.map(function (skill) {
return skill.toUpperCase();
});
Method Exercise
- Trim a string.
- Convert text to lowercase.
- Format a number with two decimals.
- Use includes() and map() on an array.
Scope, Errors and Debugging
Understand variable availability and fix problems.
Global and Local Scope
const globalMessage = "Available outside the function";
function showMessage() {
const localMessage = "Available only inside the function";
console.log(globalMessage);
console.log(localMessage);
}
| Error | Typical Cause |
|---|---|
| Syntax Error | Missing bracket, quote or invalid code |
| Reference Error | Using a name that does not exist |
| Type Error | Using a value in an unsupported way |
| Logic Error | Code runs but produces the wrong result |
- Read the first console error.
- Open the reported file and line.
- Check spelling, brackets and quotes.
- Log important values.
- Use breakpoints.
- Test one change at a time.
Debugging Exercise
- Create and fix one syntax error.
- Create and fix a missing-variable error.
- Use console.log() to trace a calculation.
Organising Clear JavaScript Code
Use naming, indentation and structure that are easy to maintain.
- Use descriptive variable and function names.
- Give each function one clear responsibility.
- Use consistent indentation.
- Keep related code together.
- Remove unused variables and old code.
- Use comments for important reasoning.
- Use an external file for larger pages.
- Check the console before publishing.
Example Structure
"use strict";
// Element references
const form = document.querySelector("#task-form");
const input = document.querySelector("#task-input");
const list = document.querySelector("#task-list");
// Functions
function createTask(text) {
const item = document.createElement("li");
item.textContent = text;
return item;
}
// Event listeners
form.addEventListener("submit", function (event) {
event.preventDefault();
const text = input.value.trim();
if (text === "") return;
list.appendChild(createTask(text));
input.value = "";
});
Organisation Exercise
- Rename unclear variables.
- Move repeated code into a function.
- Apply consistent indentation.
- Separate references, functions and events.
Final Project: Create an Interactive Task List
Combine HTML, CSS and JavaScript in one beginner project.
Project Requirements
- Create an HTML page with a heading.
- Add a task-entry form and text input.
- Add a submit button and empty task list.
- Connect an external JavaScript file.
- Select all required elements.
- Handle the form submit event.
- Prevent the default submission.
- Read and trim the input value.
- Reject an empty task.
- Create and insert a new list item.
- Add a completed-task toggle.
- Add a remove button.
- Display a task count.
- Use clear function names.
- Check the console for errors.
Suggested Workflow
- Build HTML
- Style Page
- Select Elements
- Create Functions
- Add Events
- Validate
- Debug
- Test
Starter JavaScript
"use strict";
const form = document.querySelector("#task-form");
const input = document.querySelector("#task-input");
const list = document.querySelector("#task-list");
const count = document.querySelector("#task-count");
function updateTaskCount() {
count.textContent = list.children.length;
}
function createTask(text) {
const item = document.createElement("li");
const label = document.createElement("span");
const removeButton = document.createElement("button");
label.textContent = text;
removeButton.type = "button";
removeButton.textContent = "Remove";
label.addEventListener("click", function () {
item.classList.toggle("is-complete");
});
removeButton.addEventListener("click", function () {
item.remove();
updateTaskCount();
});
item.appendChild(label);
item.appendChild(removeButton);
return item;
}
form.addEventListener("submit", function (event) {
event.preventDefault();
const taskText = input.value.trim();
if (taskText === "") return;
list.appendChild(createTask(taskText));
input.value = "";
input.focus();
updateTaskCount();
});
Final Verification Checklist
- The external file loads.
- The form does not reload the page.
- Empty tasks are rejected.
- Valid tasks appear in the list.
- Tasks can be completed and removed.
- The task count updates.
- No console errors remain.
- The page works on desktop and mobile.
Congratulations!
You have completed JavaScript for Beginners.
You can now work with variables, conditions, loops, functions, arrays, objects, DOM elements, events, forms and dynamic webpage content.
Continue practising by adding small interactive features to your existing HTML and CSS projects.

