DEV Community

Cover image for Mastering JavaScript Functions & DOM Manipulation: A Beginner-Friendly Deep Dive
Dumebi Okolo
Dumebi Okolo

Posted on • Edited on

26 2 3 4 3

Mastering JavaScript Functions & DOM Manipulation: A Beginner-Friendly Deep Dive

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!");
}
Enter fullscreen mode Exit fullscreen mode

To run this function, you invoke or call it like this:

sayHello(); // Outputs: Hello, world!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 of doSomething().
  • 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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
// By ID
const introParagraph = document.getElementById("intro");

// By class
const button = document.querySelector(".btn");

// By tag name
const paragraph = document.querySelector("p");
Enter fullscreen mode Exit fullscreen mode

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>";
Enter fullscreen mode Exit fullscreen mode

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!");
});
Enter fullscreen mode Exit fullscreen mode

You can also pass named functions:

function handleClick() {
  console.log("Button was clicked.");
}

button.addEventListener("click", handleClick);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

You can update it dynamically using JavaScript:

let score = 0;

function increaseScore() {
  score++;
  document.getElementById("score").textContent = score;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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}`;
}
Enter fullscreen mode Exit fullscreen mode

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");
});
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

2. Using Arrow Functions in Event Listeners

Arrow functions provide a concise syntax:

button.addEventListener("click", () => {
  console.log("Clicked!");
});
Enter fullscreen mode Exit fullscreen mode

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");
  }
});
Enter fullscreen mode Exit fullscreen mode

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.

Find me on LinkedIn.
Email

This tutorial was obtained from this training video by SuperSimpleDev,

Warp.dev image

The best coding agent. Backed by benchmarks.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (4)

Collapse
 
artyprog profile image
ArtyProg

You are doing a great job, continue :-)

Collapse
 
dumebii profile image
Dumebi Okolo

Thank you!

Collapse
 
liaqatxd profile image
Liaqat Ali

Thanks man!

Collapse
 
dumebii profile image
Dumebi Okolo

You're welcome.

Build seamlessly, securely, and flexibly with MongoDB Atlas. Try free.

Build seamlessly, securely, and flexibly with MongoDB Atlas. Try free.

MongoDB Atlas lets you build and run modern apps in 125+ regions across AWS, Azure, and Google Cloud. Multi-cloud clusters distribute data seamlessly and auto-failover between providers for high availability and flexibility. Start free!

Learn More

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are encouraged to share their viewpoints and expand our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. If you found this valuable, a quick note of gratitude to the author goes a long way.

Get Started