Lesson 3 โข Beginner
JavaScript Functions ๐
Learn how to create reusable, organized, and efficient blocks of code with functions โ one of the most powerful features in JavaScript.
What You'll Learn in This Lesson
- โDefine and call functions
- โPass parameters and get return values
- โArrow function syntax (ES6)
- โDefault parameter values
- โFunction scope and local variables
- โFunction composition and reusability
๐ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a
.htmlfile with<script>tags and open it in your browser
๐ญ Real-World Analogy: Functions are like machines in a factory:
- โข You give them inputs (raw materials / parameters)
- โข They do some work (the code inside)
- โข They give you an output (the return value)
- โข You can use the same machine over and over with different inputs!
๐ง What Are Functions?
A function is a reusable block of code that performs a specific task.
Instead of writing the same code multiple times, you can write it once, give it a name, and then call it whenever you need it.
| Concept | What It Means | Factory Analogy |
|---|---|---|
| Parameters | Values you pass in | Raw materials |
| Function body | The code that runs | The assembly line |
| Return value | What comes back | The finished product |
Functions make your code:
- โ Easier to read
- โ Easier to debug
- โ More efficient and modular
๐งฉ Basic Structure
A function typically looks like this:
function nameOfFunction() {
// code to run
}You can then call the function by writing its name followed by parentheses ():
nameOfFunction();๐ฌ Example 1: Simple Function
function greet() {
console.log("Hello, World!");
}
greet(); // Call the function๐ข Output:
Hello, World!The code inside the function runs only when you call it.
โ๏ธ Function with Parameters (Input Values)
Parameters are like "placeholders" that let you pass values into your function.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice");
greet("Boopie");๐ข Output:
Hello, Alice!
Hello, Boopie!๐ก Think of parameters as inputs and the function as a machine that uses those inputs to produce something.
๐งฎ Return Values
Sometimes you don't just want to print something โ you want to return a result you can use elsewhere in your program.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);๐ข Output:
8The keyword return sends a value back to the part of the code that called the function.
๐ก A function can only return one value โ but that value can be anything: a number, string, object, or even another function.
๐ Real-World Analogy
Imagine a coffee machine:
- โข You give it inputs (water + coffee beans)
- โข It does some work (heats and brews)
- โข It gives you an output (coffee โ)
That's exactly what a function does!
๐ฆ Example 2: Function That Returns a Message
function getWelcomeMessage(user) {
return `Welcome back, ${user}!`;
}
let message = getWelcomeMessage("Brayan");
console.log(message);๐ข Output:
Welcome back, Brayan!โก Arrow Functions โ Modern JavaScript Style
Arrow functions are a shorter syntax introduced in ES6 (modern JavaScript).
๐งฉ Example 1: Regular Function
function greet(name) {
console.log(`Hello, ${name}!`);
}โก Arrow Function Equivalent
const greet = (name) => {
console.log(`Hello, ${name}!`);
};If your function has only one line and returns something, you can make it even shorter:
const add = (a, b) => a + b;๐ก No return or {} needed in one-line arrow functions โ it returns automatically!
๐ก Example 2: Double a Number
const double = (num) => num * 2;
console.log(double(10));๐ข Output:
20๐งฐ Default Parameters
You can give parameters default values that are used if the caller doesn't provide one.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!๐ก This makes your code safer โ it prevents errors if someone forgets to pass an argument.
๐งฉ Example: Default Value with Math Function
function power(base, exponent = 2) {
return base ** exponent;
}
console.log(power(5)); // 25
console.log(power(5, 3)); // 125๐ง Function Scope โ Where Variables Live
Variables created inside a function are only available inside that function. This is called local scope.
function showMessage() {
let message = "Hello from inside the function!";
console.log(message);
}
showMessage();
console.log(message); // โ Error: message is not defined๐ก Use local variables inside functions to avoid conflicts with other parts of your program.
๐งฉ Combining Functions Together
You can use one function inside another โ this is called function composition.
function add(a, b) {
return a + b;
}
function square(num) {
return num * num;
}
console.log(square(add(2, 3))); // (2+3)^2 = 25This helps break down complex logic into smaller, reusable pieces.
๐ Example: Real Use Case โ Discount Calculator
function calculateTotal(price, discount) {
let finalPrice = price - (price * discount / 100);
return finalPrice;
}
console.log(calculateTotal(100, 10)); // 90
console.log(calculateTotal(250, 25)); // 187.5๐งฉ Modular logic: The same function can calculate discounts for any product, just by changing the parameters.
๐ง Why Functions Are Essential
Functions are the building blocks of all modern apps and websites.
They are used for:
- โข Handling user input
- โข Calculating values (shopping cart totals, scores, distances, etc.)
- โข Fetching data from servers (API calls)
- โข Responding to events like clicks or scrolls
- โข Organizing your entire app into readable parts
๐ Example: Function for Greeting Users
function welcomeUser(username) {
console.log(`Welcome to LearnCodingFast, ${username}!`);
}
welcomeUser("Boopie");๐ข Output:
Welcome to LearnCodingFast, Boopie!JavaScript Functions Practice
Create and call your own functions!
// Function basics
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Boopie");
greet("Alice");
// Function with return
function add(a, b) {
return a + b;
}
console.log("5 + 3 =", add(5, 3));
console.log("10 + 20 =", add(10, 20));
// Arrow function
const double = (num) => num * 2;
console.log("Double of 10:", double(10));
// Default parameters
function power(base, exponent = 2) {
return base ** exponent;
}
console.log("5^2 =", power(5));
console.log("5^3 =", power(
...๐ Function Expressions vs Declarations
You can also store functions inside variables.
// Declaration
function greet() {
console.log("Hello!");
}
// Expression
const sayHello = function() {
console.log("Hi there!");
};
greet();
sayHello();๐ก Both work the same, but arrow functions and function expressions are better for modern coding.
๐งฉ Functions Can Return Anything
A function can return numbers, strings, arrays, objects, or even other functions!
Example:
function getUser() {
return {
name: "Brayan",
age: 16
};
}
console.log(getUser().name); // Brayan๐ง Advanced Example โ Function Returning a Function
function multiplier(x) {
return function(y) {
return x * y;
};
}
const double = multiplier(2);
console.log(double(5)); // 10๐ก This is called a closure โ a powerful concept you'll learn later in advanced lessons.
๐งฑ Best Practices for Functions
โ Use descriptive names
function calculateTotal() { ... } // good
function ct() { ... } // badโ Keep functions small
Each function should do one task only.
โ Use arrow functions for short code
const square = n => n * n;โ Return values
Return instead of printing if you need to use the result somewhere else.
โ Avoid global variables
Keep variables local whenever possible to prevent conflicts.
โ๏ธ Common Mistakes to Avoid
โ Forgetting to call a function
function greet() { console.log("Hi!"); }
greet; // โ Does nothing
greet(); // โ
Calls the functionโ Forgetting return
function add(a, b) { a + b; } // โโ Correct:
function add(a, b) { return a + b; }โ Overusing global variables โ causes hard-to-track bugs.
๐ฏ Practice Challenge
Create these functions to test your understanding:
1๏ธโฃ A function that converts Celsius to Fahrenheit
function toFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
console.log(toFahrenheit(0)); // 322๏ธโฃ A function that checks if a number is even
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(10)); // true3๏ธโฃ An arrow function that finds the maximum of two numbers
const max = (a, b) => (a > b ? a : b);
console.log(max(5, 10)); // 104๏ธโฃ A function with default parameters that creates a greeting message
function greet(name = "Guest") {
return `Hello, ${name}! Welcome back!`;
}
console.log(greet());
console.log(greet("Brayan"));๐ฌ Recap
- โ Functions let you group reusable logic
- โ Parameters allow input flexibility
- โ
returngives you reusable results - โ Arrow functions make syntax modern and shorter
- โ Default parameters make your functions safer
๐ก Final Thought
If variables are the nouns of programming, functions are the verbs โ they do things.
Mastering functions gives you the power to automate and create truly dynamic apps!
(Experiment with creating your own functions and try combining them to build mini tools!)
๐ Quick Reference โ Functions
| Concept | Syntax |
|---|---|
| Declaration | function greet(name) { ... } |
| Arrow function | const greet = (name) => { ... } |
| Return value | return a + b; |
| Default param | function greet(name = "Guest") |
| Short arrow | const double = x => x * 2; |
Lesson 3 Complete โ JavaScript Functions!
You can now write reusable code with parameters, return values, arrow functions, and default arguments.
Up next: DOM Manipulation โ use JavaScript to modify HTML and bring your webpages to life! ๐จ
Sign up for free to track which lessons you've completed and get learning reminders.