You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are reusable blocks of code that perform a specific task. They are one of the most important concepts in JavaScript — almost everything you build will be organised into functions.
The classic way to define a function:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // "Hello, Alice!"
return statement sends a value back to the caller.return is specified, the function returns undefined.A function assigned to a variable:
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob")); // "Hello, Bob!"
Function expressions are not hoisted — you must define them before you use them.
Introduced in ES6, arrow functions provide a shorter syntax:
// Standard arrow function
const greet = (name) => {
return "Hello, " + name + "!";
};
// Concise body (implicit return for single expressions)
const double = (x) => x * 2;
// No parentheses needed for a single parameter
const square = x => x * x;
// No parameters
const sayHi = () => "Hi!";
| Feature | Regular Function | Arrow Function |
|---|---|---|
this binding | Dynamic (depends on how it is called) | Lexical (inherits from surrounding scope) |
arguments object | Available | Not available (use rest parameters) |
| Hoisting | Yes (declarations) | No |
| Use as constructor | Yes (new MyFunc()) | No |
| Best for | Methods, constructors | Callbacks, functional-style code |
function greet(name = "World") {
return "Hello, " + name + "!";
}
console.log(greet()); // "Hello, World!"
console.log(greet("Alice")); // "Hello, Alice!"
Collect any number of arguments into an array:
function sum(...numbers) {
let total = 0;
for (const n of numbers) {
total += n;
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
function printUser({ name, age }) {
console.log(name + " is " + age + " years old.");
}
printUser({ name: "Alice", age: 30 });
// "Alice is 30 years old."
Scope determines where variables are accessible.
Variables declared outside any function or block are globally accessible:
const appName = "MyApp"; // global
function showApp() {
console.log(appName); // accessible here
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.