Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Functions and Scope

Author: Sophia

what's covered
In this lesson, you will learn about functions in JavaScript, including how to create them, use them, and understand where variables can be accessed within your code. Specifically, this lesson will cover the following:

Table of Contents

1. Function Basics

A function is a reusable block of code designed to perform a specific task. Functions help you organize your code, avoid repetition, and make programs easier to read and maintain. Instead of writing the same code multiple times, you can write it once inside a function and use it whenever needed.

Think of a function like a machine. You build the machine to perform a specific task, and each time you turn it on, it runs the same set of instructions.

term to know
Function
A reusable block of code designed to perform a specific task.

1a. Declaring Functions

Before you can use a function, you must first declare it. A function declaration defines the function’s name and the code it will execute.

Think of this as building the machine. You are setting up what the machine will do, but it will not run until you turn it on.

The basic syntax uses the function keyword, followed by a name, parentheses, and curly braces that contain the code to run.

EXAMPLE

Here is a simple function declaration:

function greetUser() {
console.log("Welcome to our website!");
}
In this code, greetUser is the function name. The parentheses () are required even when empty. The curly braces {} contain the function body, which holds the code that runs when the function is called.

The following diagram shows the key parts of a function declaration.

Diagram labeling parts of a JavaScript function declaration including the function keyword, function name, parameters, function body, and return statement.

When naming functions, follow these conventions:

  • Use camel-case (start with lowercase; capitalize subsequent words).
  • Choose descriptive names that indicate what the function does.
  • Start with a verb when possible (e.g., calculateTotal, validateInput, displayMessage).
key concept
A function declaration consists of four parts: the function keyword, a name, parentheses, and curly braces containing the code to execute. The function does not run when declared; it only runs when called.

term to know
Function Declaration
The syntax used to define a function, including the function keyword, name, parameters, and code block.

1b. Calling Functions

Declaring a function does not execute its code. To run the code inside a function, you must call (or invoke) it. You call a function by writing its name followed by parentheses.

Calling a function is like turning on the machine. Each time you call it, the machine runs the instructions inside the function.

EXAMPLE

function greetUser() {
console.log("Welcome to our website!");
}

// Call the function
greetUser();
When JavaScript encounters greetUser(), it executes the code inside the function and displays the message in the console. You can call the same function multiple times throughout your program.

try it
Follow these steps to declare and call a function in your Codespace:

1. Open your index.html file.

2. Inside the <body> element, add a <script> element just before the closing </body> tag:

Copy
<script>
function sayHello() {
console.log("Hello!");
}

sayHello();
sayHello();
</script>
3. Save your file.

4. Preview your page in Codespaces.

5. Open the browser console:

  • Right-click on the page.
  • Select “Inspect.”
  • Click the “Console” tab.
6. Observe the output.
What do you expect to see in the console before running the code?
The console displays “Hello!” twice because the function is called two times, and the console.log statement runs each time the function executes.

big idea
Functions allow you to reuse code by defining a task once and executing it whenever needed.


2. Parameters and Return Values

Functions become more powerful when they can accept information and produce a result. Parameters allow functions to receive information, and return values allow functions to send a result back.

Think of this as upgrading the machine from Section 1. Before, the machine always did the same thing every time you turned it on. Now, you can give the machine different information each time it runs. The machine uses that information to produce a result, which it can send back for you to use elsewhere in your program.

term to know
Parameter
A variable listed in a function declaration that receives values when the function is called.

2a. Function Parameters

A parameter is a variable inside a function that receives a value when the function is called. Parameters act as placeholders for the data the function will use.

You can think of parameters as the information you feed into the machine.

EXAMPLE

function greetUser(name) {
console.log("Welcome, " + name + "!");
}

greetUser("Alice"); // Output: Welcome, Alice!
greetUser("Bob"); // Output: Welcome, Bob!
In this code:

  • name is the parameter inside the function
  • "Alice" and "Bob" are the values passed into the function
When the function runs, the value replaces the parameter:

  • First call: name = "Alice"
  • Second call: name = "Bob"
The function uses that value to produce different outputs each time.

Functions can accept multiple parameters, separated by commas.

EXAMPLE

function calculateRectangleArea(width, height) {
console.log(width * height);
}

calculateRectangleArea(5, 10); // Output: 50
calculateRectangleArea(3, 7); // Output: 21
Each value is matched to a parameter based on its position:

  • width = 5, height = 10
  • width = 3, height = 7

 Diagram showing that parameters are variables defined in a function, while arguments are the actual values passed when the function is called, matched by position.

key concept
Parameters allow a function to receive information. When a function is called, the values provided are assigned to the parameters based on their position and called arguments.

2b. The 'return' Statement

So far, your functions have displayed results using console.log(). However, functions can also send a value back to the code that called them.

The return statement specifies the value a function produces.

This is like the machine producing a result after processing the information it was given.

EXAMPLE

function calculateRectangleArea(width, height) {
return width * height;
}

let area = calculateRectangleArea(5, 10);
console.log(area); // Output: 50
In this code:

  • The function calculates a value
  • The return statement sends that value back
  • The result is stored in the variable area

Unlike console.log(), which only displays a value in the console, return sends a value back to the code that called the function so it can be used elsewhere.

A value displayed with console.log() cannot be stored or reused. A value returned from a function can be saved in a variable, used in a calculation, or passed into another function.

When JavaScript encounters a return statement, it immediately stops running the function and sends back the value. Any code written after the return statement inside the function will not run.

EXAMPLE

function testReturn() {
console.log("Step 1");
return "Done";
console.log("Step 2");
}

let result = testReturn();
console.log(result);
In this code:

  • "Step 1" is displayed
  • "Step 2" is never displayed
  • The function stops as soon as it reaches return
  • The value "Done" is sent back and stored in result
This is like the machine stopping as soon as it produces a result. Once the result is produced, the machine does not continue running the remaining steps.

The value that is sent back from a function using return is called a return value.

step by step
Do the following to create a function that returns a value:

  1. Declare the function with the function keyword and a name.
  2. Add parameters inside the parentheses if the function needs input.
  3. Write the code that performs the calculation or operation.
  4. Use return followed by the value to send back.
  5. Call the function and capture the returned value in a variable.

try it
Follow these steps to test a function with parameters and a return value:

1. Open your index.html file.

2. Inside your <script> element, add this:

Copy
function addNumbers(a, b) {
return a + b;
}

let result = addNumbers(8, 12);
console.log(result);
3. Save your file.

4. Preview your page and open the browser console.

5. Observe the result.
What is the value stored in the variable result?
The value is 20. The function adds 8 and 12, then returns the sum.

term to know
Return Value
The value a function sends back to the code that called it, specified by the return statement.


3. Variable Scope

Scope determines where in your code a variable can be used. Some variables are available everywhere, while others only exist in specific parts of your program.

Think of this like the machine from earlier sections. Some information is available to the entire program, while other information exists only inside the machine while it is running. Once the machine stops, that information is no longer available.

Understanding scope is important because it helps you predict where variables can be used and prevents errors when you try to use a variable outside of where it exists.

Variables declared outside of any function have global scope, meaning they can be used anywhere in your code, including inside functions. Variables declared inside a function have local scope, meaning they only exist within that function and cannot be used outside of it.

Think of global variables as information available to the entire program, while local variables exist only inside the function while it is running.

EXAMPLE

let globalMessage = "I am global";

function showMessages() {
let localMessage = "I am local";
console.log(globalMessage); // Works: global variable
console.log(localMessage); // Works: local variable
}

showMessages(); console.log(globalMessage); // Works: global variable console.log(localMessage); // Error: localMessage is not defined
The variable globalMessage is accessible everywhere. The variable localMessage exists only inside the function showMessages and cannot be accessed outside of it.

Local scope keeps variables inside their function, so they do not affect variables in other parts of your program.

 Diagram showing two levels of variable scope in JavaScript: global scope variables that are accessible throughout the program and function scope variables that are only accessible within the function where they are defined.

For example, two different functions can each have a variable with the same name, and they will not interfere with each other because each variable exists only within its own function.

EXAMPLE

function firstFunction() {
let count = 10;
console.log(count); // Output: 10
}

function secondFunction() {
let count = 50;
console.log(count); // Output: 50
}

firstFunction();
secondFunction();
In this code:

  • Each function creates its own variable named count
  • The value of count inside one function does not affect the other
  • Each variable exists only within the function where it is declared

term to know
Scope
The context that determines where variables can be accessed in your code.


4. Function Expressions and Arrow Functions

JavaScript provides multiple ways to define functions. In addition to function declarations, you can also create a function and store it in a variable. This is called a function expression.

In this approach, the function becomes the value of the variable, and you use the variable name to call the function.

EXAMPLE

const calculateSum = function(a, b) {
return a + b;
};

let total = calculateSum(5, 3);
console.log(total); // Output: 8
In this code:

  • A function is stored in the variable calculateSum
  • The function is called using the variable name

Function expressions must be defined before they are called.

JavaScript also provides a shorter way to write function expressions called arrow functions. Arrow functions do the same thing as function expressions but use a more concise syntax. Instead of using the function keyword, they use the => symbol.

EXAMPLE

// Traditional function expression
const multiply = function(a, b) {
return a * b;
};

// Arrow function equivalent
const multiplyArrow = (a, b) => {
return a * b;
};
Both functions work identically, but the arrow function syntax is more concise.

Arrow functions can be shortened further when the function body contains only a single expression. You can omit the curly braces and the return keyword.

 Comparison of three ways to define functions in JavaScript—function declarations, function expressions, and arrow functions—highlighting differences in syntax and behavior.

EXAMPLE

// Arrow function with implicit return
const multiplyArrow = (a, b) => a * b;

console.log(multiplyArrow(4, 5)); // Output: 20
When an arrow function has exactly one parameter, you can also omit the parentheses around the parameter.

const double = x => x * 2;

console.log(double(7)); // Output: 14

step by step
Do the following to convert a function expression to an arrow function:

  1. Remove the function keyword.
  2. Add the arrow => between the parameters and the opening curly brace.
  3. If the function has a single expression, optionally remove the curly braces and the return keyword.
  4. If the function has exactly one parameter, optionally remove the parentheses around it.

try it
Convert the following function expression to an arrow function with the shortest possible syntax:

const square = function(num) {
return num * num;
};
Check your answer.
const square = num => num * num;
Since the function has one parameter and one expression, you can omit the parentheses, curly braces, and the return keyword.

big idea
JavaScript provides multiple ways to define functions. Function expressions store functions in variables, and arrow functions provide a shorter and more concise way to write those functions.

term to know
Arrow Function
A concise function syntax introduced in ES6 that uses the => symbol and provides shorter syntax for writing functions.

summary
In this lesson, you learned about function basics, including declaring functions and calling functions, and how functions allow you to organize and reuse code. You explored parameters and return values, including function parameters and the return statement, to understand how functions receive information and produce results. You examined variable scope to understand where variables can be used and how global and local scope affect your code. Finally, you learned function expressions and arrow functions and how different syntax options can be used to define functions more concisely.

Source: THIS TUTORIAL WAS AUTHORED BY SOPHIA LEARNING. PLEASE SEE OUR TERMS OF USE.

REFERENCES

Mozilla Developer Network. (n.d.). How the web works. developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works

Terms to Know
Arrow Function

A concise function syntax introduced in ES6 that uses the => symbol and provides shorter syntax for writing functions.

Function

A reusable block of code designed to perform a specific task.

Function Declaration

The syntax used to define a function, including the function keyword, name, parameters, and code block.

Parameter

A variable listed in a function declaration that receives values when the function is called.

Return Value

The value a function sends back to the code that called it, specified by the return statement.

Scope

The context that determines where variables can be accessed in your code.