Lesson 1: Introduction to Functions

Learning Objectives

By the end of this lesson, learners will be able to:

  • Understand what functions are and why they’re used in JavaScript
  • Recognize how functions improve code structure and reusability
  • Learn the basic structure (syntax) of a JavaScript function
  • Know the difference between defining and calling a function

What Is a Function?

In programming, a function is a reusable block of code designed to do a specific task.
Instead of writing the same instructions multiple times, we define them once in a function and then call that function whenever we need it.


Real-Life Analogy

Imagine a coffee machine:

  • You push a button (trigger/call)
  • The machine brews the coffee (function logic)
  • You get a cup of coffee (output)

The coffee machine is a function:

  • You use it whenever you want coffee
  • You don’t need to re-invent how to make coffee every time

Why Use Functions?

Here’s why functions are crucial in JavaScript (and all programming):

ReasonExplanation
✅ ReusabilityWrite code once, reuse it everywhere
✅ ClarityBreak code into readable, manageable chunks
✅ MaintainabilityUpdate logic in one place instead of many
✅ DRY PrincipleDon’t Repeat Yourself – avoid copying the same code repeatedly
✅ TestingFunctions are easier to test and debug

Function Structure in JavaScript

Basic Syntax:

function functionName() {
  // code to run when the function is called
}
  • function: JavaScript keyword to define a function
  • functionName: any valid name (should describe what it does)
  • () – parentheses can hold parameters (covered in next lessons)
  • {} – curly braces enclose the function body (code to run)

Example 1: A Simple Function

function greetUser() {
  console.log("Hello! Welcome to Codevisionz!");
}

✅ This function is now defined, but it won’t do anything until you call it.


Calling a Function

greetUser();  // Output: Hello! Welcome to Codevisionz!
  • This line tells the program to execute the code inside greetUser.

Without vs. With a Function

Without a function:

console.log("Welcome!");
console.log("Welcome!");
console.log("Welcome!");

With a function:

function sayWelcome() {
  console.log("Welcome!");
}

sayWelcome();
sayWelcome();
sayWelcome();

➡️ Same result, but cleaner, more reusable code.


Best Practices

  • Use descriptive names: printMessage() is better than doThing()
  • Keep functions focused on one task
  • Use functions to organize code logically (e.g. greetUser(), calculateTotal())

Recap Terms

TermDescription
FunctionA block of code that performs a task
DefineWriting the function once with the function keyword
CallRunning the function using its name followed by ()
BodyThe code inside the function’s {} that runs when called