This content originally appeared on DEV Community and was authored by Dumebi Okolo
I am a bit ashamed to say that my learning progress hasn’t been all that since the last article I posted. So far, I have learned more on functions and DOM manipulations in JavaScript. We did a bit of both in the last article, but we will be going deeper into them today!
Keep in mind that if you’re revisiting JavaScript after some time or building foundational skills from scratch, understanding functions and the Document Object Model (DOM) is essential.
Today, we’ll explore:
- What functions are and how they help organize your code.
- How to create and use functions effectively.
- Understanding function parameters, return values, and scope.
- The role of the DOM in modern web development.
- Techniques for selecting, modifying, and listening to events on DOM elements.
- Building a complete Rock Paper Scissors game using these concepts.
Understanding JavaScript Functions: Reusable Logic Made Easy
A function in JavaScript is a block of code designed to perform a specific task. It can be reused multiple times throughout your application, helping you write cleaner, more maintainable code.
Basic Function Syntax in JavaScript
function sayHello() {
console.log("Hello, world!");
}
To run this function, you invoke or call it like this:
sayHello(); // Outputs: Hello, world!
This simple example shows how functions encapsulate logic that can be triggered anytime.
Parameters in Functions: Dynamic Functions
Functions become even more powerful when you introduce parameters, seen as placeholders for values passed into the function when it’s called.
function greetUser(name) {
console.log("Hello, " + name);
}
greetUser("Alice"); // Outputs: Hello, Alice
greetUser("Bob"); // Outputs: Hello, Bob
Here, name
is a parameter, and "Alice"
and "Bob"
are arguments passed into the parameter (actual values provided during the function call).
You can pass multiple parameters:
function addNumbers(a, b) {
console.log("The sum is:", a + b);
}
addNumbers(5, 10); // Outputs: The sum is: 15
JavaScript Function Return: Getting Results Back
Instead of just logging output like we have been doing, functions can also return results for further use:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 6);
console.log(result); // Outputs: 24
Returning values allows functions to be used in expressions, assignments, and other parts of your program.
Function Scope: Where Variables Live
Variables declared INSIDE a function are only accessible within that function. This is known as local scope.
function myFunction() {
let message = "Inside the function";
console.log(message);
}
myFunction(); // Outputs: Inside the function
console.log(message); // Error: message is not defined
To access a variable outside a function, declare it in the global scope:
let globalMessage = "Outside the function";
function showMessage() {
console.log(globalMessage);
}
showMessage(); // Outputs: Outside the function
Understanding scope helps prevent naming conflicts and makes debugging easier.
Best Practices When Writing Functions
- Keep functions small and focused: Each function should do one thing well.
-
Use descriptive names: Name functions based on what they do, e.g.,
calculateTotal()
instead ofdoSomething()
. - Avoid side effects: Try to keep functions pure — meaning they don’t modify variables outside their scope unless necessary.
- Use comments or JSDoc: Especially useful for complex functions.
- Default Parameters : ES6 introduced default values for function parameters:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Outputs: Hello, Guest
greet("Alice"); // Outputs: Hello, Alice
Understanding the Document Object Model (DOM) In JavaScript
The Document Object Model (DOM) is a programming interface for HTML documents. It represents the structure of a document as a tree of objects, enabling JavaScript to read, modify, and react to changes in the page content.
Think of the DOM as a bridge between your HTML and JavaScript.
Syntax For Selecting HTML Elements In JavaScript
Before you can manipulate an element, you need to select it using methods like:
-
document.querySelector()
: Selects the first matching element. -
document.querySelectorAll()
: Returns all matching elements. -
document.getElementById()
: Selects by ID. -
document.getElementsByClassName()
: Selects by class name.
Example:
<p id="intro">Welcome to our site!</p>
<button class="btn">Click me</button>
// By ID
const introParagraph = document.getElementById("intro");
// By class
const button = document.querySelector(".btn");
// By tag name
const paragraph = document.querySelector("p");
Modifying HTML Content In JavaScript
Once selected, you can change the text or HTML inside an element.
-
textContent
: Updates the text content. -
innerHTML
: Updates both text and HTML (be cautious with user-generated content).
Example:
introParagraph.textContent = "Welcome back!";
button.innerHTML = "<strong>Submit</strong>";
Event Listener Snippet In JavaScript
Make your web pages interactive by responding to user actions like clicks, key presses, or form submissions.
button.addEventListener("click", function () {
alert("Button clicked!");
});
You can also pass named functions:
function handleClick() {
console.log("Button was clicked.");
}
button.addEventListener("click", handleClick);
JavaScript Event Listener Practical: Updating Scores Dynamically
Let’s say you have a score display in your HTML:
<p>Your Score: <span id="score">0</span></p>
You can update it dynamically using JavaScript:
let score = 0;
function increaseScore() {
score++;
document.getElementById("score").textContent = score;
}
Now every time increaseScore()
is called, the displayed score updates instantly.
Example DOM Projects You Can Build As A Refresher
- Interactive To-Do List
- Form Validation
- Image Slider
- Dark Mode Toggle
- Rock Paper Scissors Game
We’ll build the last one now.
Project: Rock Paper Scissors with Functions & DOM
Let’s combine everything we’ve learned to create a fully functional Rock Paper Scissors game.
Step 1: HTML Structure
<h2>Rock Paper Scissors</h2>
<button class="js-rock">Rock</button>
<button class="js-paper">Paper</button>
<button class="js-scissors">Scissors</button>
<p class="js-result"></p>
<p class="js-score">Score: 0</p>
Step 2: JavaScript Logic
let score = 0;
function playGame(playerMove) {
const moves = ["rock", "paper", "scissors"];
const computerMove = moves[Math.floor(Math.random() * 3)];
let result = "";
if (playerMove === computerMove) {
result = "It's a tie!";
} else if (
(playerMove === "rock" && computerMove === "scissors") ||
(playerMove === "paper" && computerMove === "rock") ||
(playerMove === "scissors" && computerMove === "paper")
) {
result = "You win!";
score++;
} else {
result = "You lose!";
score--;
}
document.querySelector(".js-result").textContent =
`You chose ${playerMove}, Computer chose ${computerMove}. ${result}`;
document.querySelector(".js-score").textContent = `Score: ${score}`;
}
Step 3: Add Event Listeners
document.querySelector(".js-rock").addEventListener("click", () => {
playGame("rock");
});
document.querySelector(".js-paper").addEventListener("click", () => {
playGame("paper");
});
document.querySelector(".js-scissors").addEventListener("click", () => {
playGame("scissors");
});
This exercise includes concepts we haven’t learned in this article or the previous one. Hopefully, we will discuss more on them in the coming article, especially Conditionals in JavaScript.
Until then, I hope this article helps you and gives you a refresher!
Advanced Tips for Working with Functions & DOM
1. Caching DOM Elements
Don’t query the DOM repeatedly — store references in variables.
const resultElement = document.querySelector(".js-result");
const scoreElement = document.querySelector(".js-score");
// Later in your function:
resultElement.textContent = "New result...";
scoreElement.textContent = "Score updated";
2. Using Arrow Functions in Event Listeners
Arrow functions provide a concise syntax:
button.addEventListener("click", () => {
console.log("Clicked!");
});
3. Event Delegation
Instead of attaching event listeners to each element, listen at a parent level:
document.body.addEventListener("click", function(event) {
if (event.target.matches(".js-rock")) {
playGame("rock");
}
});
This is especially useful for dynamically added elements.
Functions and DOM manipulation are foundational to vanilla JavaScript and web development. Whether you’re building small interactive features or large-scale apps, knowing this will allow you to:
- Write clean, reusable code.
- Make your websites dynamic and responsive.
- Improve performance and maintainability.
This tutorial was obtained from this training video by SuperSimpleDev,
This content originally appeared on DEV Community and was authored by Dumebi Okolo