Computer Programming 1 (JavaScript) • Functions, Scope & Organization

Defining & Calling Functions — I can define and call functions and explain why functions improve organization and reuse.

Functions let you name a block of code and reuse it anywhere, making programs shorter, clearer, and easier to fix.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Before computers even had screens, programmers realized they were writing the same instructions over and over. If you needed to calculate a tax amount in ten different places in your program, you had to copy the same block of code ten times. Every copy was a chance for a typo, and if the tax rate changed, you had to find and update all ten spots. The idea of a function — a named, reusable chunk of code — was the solution to this problem. Functions have been a cornerstone of programming since the very earliest days of computer science.

1950s • Subroutines in Assembly

Early programmers writing in assembly language created subroutines — labeled blocks of machine instructions that could be jumped to and returned from. This was the first practical form of code reuse.

1958 • LISP and First-Class Functions

John McCarthy created LISP, one of the first languages where functions were treated as core building blocks. LISP showed that functions could be passed around like data, an idea that heavily influenced JavaScript decades later.

1972 • C Language Standardizes Functions

Dennis Ritchie's C language made functions the standard way to organize code. Every C program starts with a main() function, and this pattern became the template for most languages that followed.

1995 • JavaScript Is Born

Brendan Eich created JavaScript in just ten days. He borrowed function syntax from C and function-as-data ideas from LISP, giving JavaScript its flexible and powerful approach to functions.

2015 • ES6 Arrow Functions

ECMAScript 2015 (ES6) introduced arrow functions, a shorter syntax for writing functions. This update reflected how central functions had become to modern JavaScript development.

Throughout this history, the core question remained the same: how do we write code once and use it many times without introducing errors? Functions are the answer. In this lesson, you will learn how to define your own functions in JavaScript, how to call them, and why they are essential for writing clean, organized, and reusable programs.

SECTION 2

Core Principles of Functions

A function in JavaScript is a self-contained block of code designed to perform a specific task. You give it a name, and then you can run that block of code whenever you need it simply by using that name. Think of a function as a recipe card in a kitchen: you write the recipe once, and any time you want to make that dish, you just follow the card. The five principles below capture the most important ideas about functions.

1

Define Once, Use Many Times

A function definition describes what the function does. A function call executes that code. You define once but can call as many times as needed.
2

Parameters & Arguments

Parameters are placeholder variables listed in the function definition. Arguments are the actual values you pass in when you call the function.
3

Return Values

A function can send a result back to the code that called it using the return keyword. This output can be stored in a variable or used in an expression.
4

Organization & Readability

Functions break a large program into small, named pieces. Reading calculateTotal() is much clearer than reading 15 lines of arithmetic scattered through your code.
5

DRY — Don't Repeat Yourself

The DRY principle says that every piece of logic should exist in only one place. Functions are the primary tool for achieving DRY code.
✦

KEY TAKEAWAY

A function is like a contact saved in your phone. Instead of memorizing and dialing a ten-digit number every time you want to call a friend, you save it once under a name (like callMom) and just tap that name whenever you need it. The phone number is the code inside the function; the contact name is the function name; and tapping the name is the function call.

SECTION 3

Anatomy of a Function — Visual Explanation

The diagram below labels every part of a JavaScript function definition and shows what happens when you call that function. Study the color-coded labels to connect each syntax element with its purpose.

Anatomy of a JavaScript FunctionfunctiongreetUser(name){return"Hello, " + name + "!";}function keywordfunction nameparameterreturn statementFUNCTION CALL:let message = greetUser("Alice");argument→ "Hello, Alice!"
The function keyword tells JavaScript you are creating a function. The function name is how you will refer to it later. The parameter is a variable that receives input, while the argument is the actual value passed in during the call. The return statement sends the result back to wherever the function was called.

Notice the two separate parts in the diagram: the definition (top box) and the call (bottom box). The definition is like writing instructions; the call is like actually following them. Without the call, the function definition just sits there, and nothing happens. A common beginner mistake is writing a perfect function but forgetting to actually call it.

SECTION 4

How Functions Work Step by Step

When JavaScript encounters a function definition, it does not run the code inside immediately. Instead, it stores the function in memory so it can be used later. The code only executes when JavaScript reaches a function call. Let's walk through exactly what happens behind the scenes, using a concrete example.

The Execution Flow

Consider this code: function add(a, b) { return a + b; } followed by let sum = add(3, 5);. Here is what JavaScript does in order. First, it reads the function definition and stores it. When it reaches add(3, 5), it pauses the current line, jumps into the function body, assigns a = 3 and b = 5, evaluates a + b to get 8, and returns that value. Back on the original line, 8 replaces the function call, so sum gets the value 8.

Function Syntax Patterns

FUNCTION DECLARATION

functionname(param1,param2)/∗body∗/returnresult;function name(param₁, param₂) { /* body */ return result; }

function = keyword that starts the definition; name = identifier you choose; param₁, param₂ = inputs (zero or more); body = the instructions; return = sends result back to the caller.

FUNCTION CALL

letoutput=name(arg1,arg2);let output = name(arg₁, arg₂);

name = the same identifier used in the definition; arg₁, arg₂ = actual values passed in; output = variable that receives the returned result.

FUNCTION WITH NO RETURN

functionsayHi()console.log("Hi!");function sayHi() { console.log("Hi!"); }

Not every function returns a value. When there is no return statement, the function performs its action (like printing to the console) and returns undefined by default.

💡

Parameters vs. Arguments

People often confuse these two terms. Here is a simple rule: Parameters are the variable names in the definition (they are placeholders). Arguments are the actual values in the call. Think of it like a form: the blank labeled "Name" is the parameter, and "Alice" written in the blank is the argument.

SECTION 5

Why Functions Improve Organization & Reuse

Functions are not just a convenience — they fundamentally change how you think about writing programs. The diagram below contrasts a program written without functions against the same program reorganized with functions, showing how readability and maintenance improve dramatically.

Without Functions vs. With Functions❌ WITHOUT FUNCTIONS// Calculate area of room 1let w1 = 10, h1 = 12;let area1 = w1 * h1;console.log(area1);// Calculate area of room 2let w2 = 8, h2 = 15;let area2 = w2 * h2;console.log(area2);// Calculate area of room 3let w3 = 20, h3 = 18;let area3 = w3 * h3;console.log(area3);Problems:12 lines • Repeated logic • Hard to updateIf formula changes → fix in 3 places✓ WITH FUNCTIONSfunction calcArea(w, h) {return w * h;}console.log(calcArea(10, 12));console.log(calcArea(8, 15));console.log(calcArea(20, 18));Benefits:6 lines • Logic in one place • Easy to updateIf formula changes → fix in 1 placeReuse Advantage:Need 100 rooms? Still just 1 function.Need to add units? Change 1 line.Need to test? Test 1 function.
The left side shows repeated code without functions — three copies of the same logic. The right side shows the same program using a function: the logic is written once and called three times. With functions, the program is shorter, easier to read, and much simpler to update.

Three Key Benefits of Functions

  • ✓ Reuse — Write code once and call it wherever you need it. This eliminates copying and pasting, which is a major source of bugs.
  • ✓ Organization — Functions break a large problem into small, named pieces. Your main code reads like a high-level plan: getData(); processData(); displayResults();.
  • ✓ Maintainability — When a bug is found or a requirement changes, you only fix it in one place (inside the function), and every call site benefits automatically.

SECTION 6

Worked Example — Building a Tip Calculator Function

Let's put everything together by writing a function that calculates the tip amount for a restaurant bill. We will define the function, call it with different inputs, and trace through the execution step by step.

Creating and Using a Tip Calculator

  1. 1

    Step 1 — Identify the Task

    We want a function that takes a bill amount and a tip percentage, then returns the tip in dollars. For example, a 20% tip on a $50 bill should return $10.
  2. 2

    Step 2 — Write the Function Definition

    We choose the name calculateTip and define two parameters: bill and tipPercent. The body computes the tip and returns it.
    function calculateTip(bill, tipPercent) { return bill * (tipPercent / 100); }
  3. 3

    Step 3 — Call the Function with Arguments

    We call the function with a $50 bill and a 20% tip rate. The arguments 50 and 20 are passed into the parameters bill and tipPercent.
    let myTip = calculateTip(50, 20);
  4. 4

    Step 4 — Trace the Execution

    JavaScript jumps into the function. bill = 50, tipPercent = 20. It evaluates 50 * (20 / 100) which becomes 50 * 0.2 = 10. The return statement sends 10 back.
    myTip = 10
  5. 5

    Step 5 — Reuse with Different Arguments

    Now we can calculate tips for any bill without rewriting the formula. For a $120 bill at 15%: calculateTip(120, 15) returns 18. For a $30 bill at 25%: calculateTip(30, 25) returns 7.5. The function handles all cases.
    One function definition, unlimited uses!

SECTION 7

Inline Code vs. Functions — Strengths & Trade-Offs

You might wonder: if functions are so great, should every single line of code go inside a function? Not necessarily. The table below compares writing code inline (directly in the main flow) versus wrapping it in a function, so you can make good decisions about when to create a function.

FactorInline CodeUsing a Function
ReusabilityMust copy/paste to reuse; each copy can drift or have typos.Call the function name anywhere; logic lives in one place.
ReadabilityReader must understand every line to grasp intent.A descriptive function name like calculateTip() communicates purpose instantly.
DebuggingBug might exist in multiple copies; fixing one doesn't fix the others.Bug exists in one place; fixing the function fixes every call.
When to preferVery short code used only once, like a single console.log().Any logic used more than once, or any block longer than a few lines.

Inline code vs. function-based code

🔑

RULE OF THUMB

If you catch yourself copying and pasting code, that is a signal you should create a function. Think of it like a shortcut on your phone's home screen: if you open the same app five times a day, you create a shortcut so you don't have to dig through menus every time.

SECTION 8

Connection to Advanced Concepts

Defining and calling functions is just the beginning. As you progress through JavaScript, you will encounter more powerful ways to use functions. The table below shows how today's concepts connect to topics you will see in future lessons and courses.

What You Know NowWhat You'll Learn Next
Function declarations with function keywordArrow functions — a shorter syntax: const add = (a, b) => a + b;
Passing simple values as argumentsPassing functions as arguments — called callbacks, used in event handling and array methods like .map() and .filter()
Naming functions for reuseScope — understanding where variables declared inside a function can and cannot be accessed
Functions that do one taskFunctions calling other functions — composing small functions into larger workflows, and eventually recursion

From basics to advanced function concepts

The great news is that every advanced function concept builds directly on what you are learning today. If you deeply understand how to define a function, pass arguments into it, and receive a return value, you have the foundation for everything that comes next. Many professional developers say that truly understanding functions is the single most important milestone in learning to code.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain the difference between defining a function and calling a function. Why doesn't a function definition alone produce any output?
Show answer
Defining a function is like writing a recipe card — you describe what steps to take, but no food is actually prepared. Calling a function is like actually following the recipe — you execute those steps and get a result. A function definition alone produces no output because JavaScript simply stores the instructions in memory and moves on. The code inside the function only runs when JavaScript encounters a function call, which is the function name followed by parentheses, like myFunction(). Without the call, the instructions sit unused.

Question 2: BASIC CALCULATION

Write a function called double that takes one parameter called num and returns that number multiplied by 2. Then write a function call that passes 7 as the argument and stores the result in a variable called result. What value does result hold?
Show answer
The function definition is: function double(num) { return num * 2; }. The function call is: let result = double(7);. When JavaScript calls double(7), it assigns num = 7, computes 7 * 2 = 14, and returns 14. Therefore result holds the value 14.

Question 3: INTERMEDIATE

Write a function called rectangleArea that takes two parameters, width and height, and returns the area. Then write a second function called describeRoom that takes roomName, w, and h, and returns a string like "The Kitchen is 120 sq ft." by calling rectangleArea inside it.
Show answer
First: function rectangleArea(width, height) { return width * height; }. Second: function describeRoom(roomName, w, h) { let area = rectangleArea(w, h); return "The " + roomName + " is " + area + " sq ft."; }. Calling describeRoom("Kitchen", 10, 12) first calls rectangleArea(10, 12) which returns 120, then builds and returns the string "The Kitchen is 120 sq ft." This demonstrates one function calling another, which is how real programs compose small tasks into larger ones.

Question 4: APPLIED

You are building a grade converter for your school. Write a function called getLetterGrade that takes a numerical score (0–100) and returns the letter grade: 90–100 = "A", 80–89 = "B", 70–79 = "C", 60–69 = "D", below 60 = "F". Then explain why using a function here is better than writing if/else blocks every time you need to convert a score.
Show answer
The function: function getLetterGrade(score) { if (score >= 90) { return "A"; } else if (score >= 80) { return "B"; } else if (score >= 70) { return "C"; } else if (score >= 60) { return "D"; } else { return "F"; } }. Using a function is superior because a school program might convert hundreds of scores (for report cards, transcripts, and GPA calculations). Without a function, you would copy the same if/else block everywhere. If the grading scale changed (say, 93+ becomes an A), you would need to find and update every copy. With the function, you change one line and every call instantly uses the new scale.

Question 5: CRITICAL THINKING

A classmate writes a function function multiply(a, b) { console.log(a * b); } and then writes let product = multiply(4, 5);. They expect product to equal 20, but when they check, it equals undefined. Explain the bug, how to fix it, and what broader lesson this teaches about the difference between console.log() and return.
Show answer
The bug is that the function uses console.log(a * b) instead of return a * b. The console.log() displays the value 20 on the screen, but it does not send 20 back to the caller. Since there is no return statement, the function returns undefined by default, and that is what gets stored in product. The fix is to replace console.log(a * b) with return a * b. The broader lesson is that printing and returning are two completely different actions: printing shows information to a human, while returning passes data back to the program for further use.

SUMMARY

Lesson Summary

Summary

A function is a named, reusable block of code. You create one using a function definition, which includes the function keyword, a descriptive name, optional parameters in parentheses, and a body enclosed in curly braces. The return statement sends a value back to the code that called the function.

You execute a function by writing a function call — the function name followed by parentheses containing arguments (actual values). Functions improve your code in three critical ways: reuse (write once, call many times), organization (break big problems into named pieces), and maintainability (fix bugs in one place). Following the DRY principle — Don't Repeat Yourself — means using functions wherever you see repeated logic.

Varsity Tutors • Computer Programming 1 (JavaScript) • Defining & Calling Functions