Home / Web Basics / JavaScript Basics

Lesson 6 of 6

JavaScript Basics

Estimated time: 2.5–3 hours

What You Will Learn

  • How to write functions — reusable blocks of code that you can call whenever you need them
  • How to use conditionals (if, else if, else) to make your code make decisions
  • What the DOM (Document Object Model) is and how JavaScript uses it to interact with your HTML page
  • How to use document.querySelector to find and select elements on the page
  • How to change content, styles, and HTML dynamically with JavaScript
  • How to use addEventListener to respond to user actions like clicks and key presses
  • How to build a fully interactive mini-project that combines HTML, CSS, and JavaScript together

Welcome to the final lesson of the Web Basics track! You have come a long way. In Lesson 5 you got your first taste of JavaScript — variables, data types, and printing messages to the console. Now it is time to level up. In this lesson you will learn how to write functions, make decisions with conditionals, and — most exciting of all — use JavaScript to actually change what appears on your web page. By the end, you will build a small interactive project that brings together everything you have learned across all six lessons. Let's go!

1. Functions: Reusable Blocks of Code

Imagine you work at a coffee shop in Lansing and every time a customer walks in, you say "Welcome to the shop!" You do not re-learn how to say that greeting each time — you just do it automatically. A function in JavaScript works the same way. It is a named block of code that you write once and can use over and over again.

Here is how you create a function:

function greet(name) {
  return "Hello, " + name + "!";
}

Let's break that down:

To call (use) the function, you write its name followed by parentheses with the value you want to pass in:

Try It Yourself

Run the code below, then try changing the name inside the parentheses to your own name. Try calling greet multiple times with different names!

function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Lansing"));
console.log(greet("Maria"));
console.log(greet("Coders Farm"));

Functions can have multiple parameters too. Here is a function that adds two numbers together:

function add(a, b) {
  return a + b;
}

console.log(add(5, 3));
console.log(add(100, 250));

Arrow Functions (A Shortcut)

JavaScript also has a shorter way to write functions called arrow functions. They do the same thing but use less code. Here is the greet function written as an arrow function:

const greet = (name) => "Hello, " + name + "!";

The => symbol (called an "arrow") replaces the function keyword. For short, simple functions this is very convenient. You will see arrow functions everywhere in modern JavaScript. For now, just know they exist — you can stick with regular functions while you are learning.

2. Conditionals: Making Decisions

So far, our code runs every line from top to bottom. But what if you want your code to make a choice? That is what conditionals are for. They let you say: "If this condition is true, do one thing. Otherwise, do something else."

The basic pattern looks like this:

if (condition) {
  // do this if the condition is true
} else {
  // do this if the condition is false
}

You can also chain multiple conditions with else if:

if (temperature > 90) {
  console.log("It is hot outside!");
} else if (temperature > 60) {
  console.log("Nice weather today.");
} else {
  console.log("Better grab a jacket!");
}

Comparison Operators

Inside the parentheses of an if statement, you use comparison operators to compare values:

Logical Operators

You can combine conditions using logical operators:

Try It Yourself

The function below checks if someone is old enough to vote in the United States (you must be 18 or older). Try changing the age value and running the code. What happens when you enter 18? What about 17?

function canVote(age) {
  if (age >= 18) {
    return "Yes, you can vote!";
  } else {
    return "Not yet — you need to be 18.";
  }
}

console.log(canVote(21));
console.log(canVote(15));
console.log(canVote(18));
Why === instead of ==? In JavaScript, == does "loose" comparison and can give surprising results (for example, "5" == 5 is true). The triple equals === checks both the value and the type, which is safer and more predictable. Always use === as a beginner.

3. The DOM: Connecting JavaScript to HTML

Here is where things get really exciting. So far, we have been using console.log to see our output. But JavaScript can do much more than print messages to a hidden console. It can actually reach into your web page and change it.

How? Through something called the DOM, which stands for Document Object Model.

When your browser loads an HTML page, it does not just display the text. It reads through all of your HTML and builds a tree of objects — a structured representation of every element on the page. That tree is the DOM. Every heading, paragraph, button, image, and link becomes an object in the tree that JavaScript can find, read, and change.

Think of it like this: your HTML file is like the blueprint of a house. The DOM is the actual house that the browser builds from that blueprint. JavaScript is the homeowner who can walk through the house, rearrange the furniture, repaint the walls, and add new rooms.

4. Selecting Elements with document.querySelector

Before you can change something on the page, you need to find it. The most common way to select an element is with document.querySelector(). This method takes a CSS selector (just like the ones you learned in Lesson 4!) and returns the first matching element.

// Select by tag name
document.querySelector("h1");

// Select by class name (use a dot, just like CSS)
document.querySelector(".my-class");

// Select by ID (use a hash, just like CSS)
document.querySelector("#my-id");

Notice something familiar? The selectors are exactly the same as what you used in CSS. Your CSS knowledge is already paying off!

There is also document.getElementById(), which is a shortcut for selecting by ID:

// These two do the same thing:
document.querySelector("#my-id");
document.getElementById("my-id");

5. Changing Content on the Page

Once you have selected an element, you can change it. Here are the three most important properties for changing what appears on the page:

Try It Yourself

The example below shows all three in action. Run it to see the heading change. Then try modifying the JavaScript to change the text, HTML, or styles to something different!

<h1 id="demo-heading">I am the original heading.</h1>
<p id="demo-text">I am the original paragraph.</p>

<script>
// Change the text of the heading
document.getElementById("demo-heading").textContent = "I was changed by JavaScript!";

// Change the HTML inside the paragraph
document.getElementById("demo-text").innerHTML = "Now I have <strong>bold text</strong> and <em>italic text</em>!";

// Change the style of the heading
document.getElementById("demo-heading").style.color = "#16825d";
document.getElementById("demo-heading").style.fontSize = "28px";
</script>
Style property names: In CSS you write font-size with a hyphen. In JavaScript you write fontSize using camelCase (no hyphen, capitalize the second word). So background-color becomes backgroundColor, and border-radius becomes borderRadius.

6. addEventListener: Responding to User Actions

Changing elements when the page loads is useful, but the real magic happens when you respond to what the user does. When someone clicks a button, presses a key, or moves their mouse, the browser creates an event. You can use addEventListener to tell JavaScript: "When this event happens on this element, run this function."

Here is the basic pattern:

element.addEventListener("click", function() {
  // code to run when the element is clicked
});

The first argument is the event type (like "click", "keydown", or "mouseover"). The second argument is a function that runs when that event happens. This is how every interactive website works — from social media "like" buttons to shopping cart "add to cart" buttons.

Try It Yourself

Click the button in the preview to see it in action. Then try changing the message or adding a second button that does something different!

<h2 id="message">Click the button below!</h2>
<button id="myBtn" style="padding: 10px 24px; font-size: 16px; cursor: pointer;">Click Me</button>

<script>
var clickCount = 0;

document.getElementById("myBtn").addEventListener("click", function() {
  clickCount = clickCount + 1;
  document.getElementById("message").textContent = "You clicked " + clickCount + " time(s)!";
});
</script>

7. Interactive Exercise: Make a Button That Changes Text

This is the capstone exercise for the entire Web Basics track! You are going to combine HTML, CSS, and JavaScript into one interactive project. The goal: create a page with a heading and a button. When the user clicks the button, the heading's text and color change.

This exercise brings together everything you have learned across all six lessons:

Try It Yourself

Run the code below and click the button to see it work. Then try these challenges:

  • Change the colors to your favorites.
  • Add a second button that resets the heading back to its original text and color.
  • Make the button change the background color of the entire page.
  • Add a counter that shows how many times the button has been clicked.
<style>
  body {
    font-family: Arial, sans-serif;
    text-align: center;
    padding: 40px;
    background-color: #f9f9f9;
  }
  #main-heading {
    font-size: 32px;
    color: #333;
    transition: all 0.3s ease;
  }
  .action-btn {
    padding: 12px 32px;
    font-size: 18px;
    border: none;
    border-radius: 8px;
    background-color: #16825d;
    color: white;
    cursor: pointer;
    margin: 8px;
  }
  .action-btn:hover {
    background-color: #12694b;
  }
  #click-counter {
    margin-top: 16px;
    font-size: 14px;
    color: #777;
  }
</style>

<h1 id="main-heading">Welcome to Coders Farm!</h1>
<button class="action-btn" id="change-btn">Change the Heading</button>
<button class="action-btn" id="reset-btn">Reset</button>
<p id="click-counter">Clicks: 0</p>

<script>
var clicks = 0;
var heading = document.getElementById("main-heading");
var changeBtn = document.getElementById("change-btn");
var resetBtn = document.getElementById("reset-btn");
var counter = document.getElementById("click-counter");

var messages = [
  "You are a coder now!",
  "JavaScript is awesome!",
  "Keep building cool things!",
  "Lansing's newest developer!",
  "HTML + CSS + JS = Magic!"
];

var colors = ["#e74c3c", "#3498db", "#9b59b6", "#e67e22", "#16825d"];

changeBtn.addEventListener("click", function() {
  clicks = clicks + 1;
  var index = (clicks - 1) % messages.length;
  heading.textContent = messages[index];
  heading.style.color = colors[index];
  counter.textContent = "Clicks: " + clicks;
});

resetBtn.addEventListener("click", function() {
  heading.textContent = "Welcome to Coders Farm!";
  heading.style.color = "#333";
  clicks = 0;
  counter.textContent = "Clicks: 0";
});
</script>
Congratulations! If you can read the code above and understand how the HTML structure, CSS styles, and JavaScript event listeners work together, you have a solid foundation in web development. This is exactly how real websites are built — just on a larger scale.

8. Course Wrap-Up: You Did It!

Take a moment to feel proud of yourself. You have just completed the entire Web Basics track at Coders Farm! When you started Lesson 1, you may have never written a single line of code. Now look at what you know:

That is a real skill set. HTML, CSS, and JavaScript are the three core technologies that power every website on the internet — from simple personal blogs to massive platforms like Google, YouTube, and Amazon. You now understand the fundamentals of all three.

What Comes Next?

This is just the beginning of your coding journey. Here are some ideas to keep growing:

Remember: every expert was once a beginner. You have already taken the hardest step — starting. Keep going, keep building, and keep being curious. The Lansing coding community is cheering for you!

Test Your Knowledge

1. What does the return keyword do inside a function?

Correct! The return keyword sends a value back from the function to the code that called it. For example, if you write var result = add(3, 5);, the return statement inside add is what gives result its value of 8. It does not print anything — that is what console.log is for.

2. Which method do you use to select an HTML element by its CSS selector in JavaScript?

That's right! document.querySelector() lets you pass in any CSS selector — a tag name, a class with a dot, or an ID with a hash — and it returns the first matching element from the page. The other options are made up and do not exist in JavaScript.

3. What does addEventListener("click", function() { ... }) do?

Correct! addEventListener waits for a specific event (in this case, a "click") and then runs the function you provide. It does not run immediately — it waits until the user actually clicks the element. This is the foundation of making interactive web pages!

Wonderful work finishing the final lesson and the entire Web Basics track! You now have a real foundation in web development. Save your projects, share them with friends, and keep coding. We cannot wait to see what you build next!

Finished this lesson?

← Previous: Intro to JavaScript Next: Your Path to Employment →