Ch 8 · Functions · JavaScript

Topic 8 of 13 in JavaScript — Complete Tutorial (Beginner) — 4 lessons.

What is a Function and Why Use One?

A function is a named, reusable block of code that performs a specific, well-defined task. Instead of writing the same instructions in multiple places throughout your program, you write them once inside a function, give the function a clear and descriptive name, and then call that name whenever you need the task performed. This principle is so important that programmers give it a name: DRY, which stands for "Do not Repeat Yourself." Every time you find yourself copying and pasting the same code to a second or third location, that is a signal that the code should be a function instead.

Parameters and Return Values

Parameters are the inputs a function expects to receive. You declare them inside the round brackets in the function definition, giving each one a name. When you call the function, you pass actual values (called arguments) in the same order as the parameters. Inside the function, the parameters behave exactly like regular variables. You can give a parameter a default value with =, which is used automatically when the caller does not provide that argument.

Arrow Functions

Arrow functions are a shorter, more compact syntax for writing functions. They were introduced in modern JavaScript and are now the preferred style in most projects. Instead of writing the function keyword followed by a name, you assign the function to a const variable and use the => arrow symbol (equals sign followed by greater-than) to connect the parameters on the left to the function body on the right. Arrow functions work identically to regular functions for the vast majority of cases in a beginner's context — the difference is purely about style and brevity.

Functions in a Real Program

Here is a complete example that uses multiple functions working together — which is how real programs are always structured. Each function does one specific job: one calculates a grade, one checks if a student passed, and one prints the full report. Notice how the printReport function calls the other two functions inside it. This is called function composition — combining small, focused functions into a larger workflow — and it is the hallmark of well-organised code.

All topics in JavaScript Beginner

  1. Introduction to Programming & JavaScript
  2. Your First JavaScript Program
  3. Variables — Your Data Containers
  4. Data Types — Kinds of Values
  5. Operators & Expressions
  6. Conditional Statements
  7. Loops & Iterations
  8. Functions
  9. Arrays — Lists of Data
  10. Objects & Classes
  11. Strings — Working with Text
  12. Error Handling
  13. Mini-Projects & Practice