Functions in JavaScript
Topics
Function Declarations
Topic Overview
Imagine you have a recipe for making a sandwich. Instead of explaining the steps every time someone wants a sandwich, you write the recipe once and anyone can follow it. Functions work the same way!
A function is a reusable set of instructions that:
- •Has a name (so you can use it later)
- •Can accept inputs (called parameters)
- •Performs a specific task
- •Can return a result
Basic function structure: function functionName(parameter1, parameter2) { // Instructions go here return result; // Optional }
Calling (using) a function: functionName(value1, value2);
Special feature of function declarations:
- •You can use them before they appear in your code (hoisting)
- •They have clear names that describe what they do
- •Perfect for main tasks in your program
Think of functions as your personal assistants - you tell them what to do once, and they'll do it whenever you ask!
Ready to practice? Try the exercise below to reinforce your learning!
Try it yourself
Create a function called "greet" that takes a name parameter and returns a greeting message.