β 1. What Is a Function Definition?
A function definition is how you create a function β specifying its name, parameters, and the block of code it should run when called.
π 2. Ways to Define Functions in JavaScript
A. Function Declaration (Named Function)
β Hoisted (can be used before it’s defined)
jsCopyEditfunction greet() {
console.log("Hello!");
}
greet(); // "Hello!"
B. Function Expression
A function assigned to a variable.
β Not hoisted (must be defined before use)
jsCopyEditconst sayHello = function() {
console.log("Hi there!");
};
sayHello(); // "Hi there!"
C. Arrow Function (ES6)
β
Shorter syntax
β No this
, arguments
, or super
binding (not suitable as methods)
jsCopyEditconst add = (a, b) => a + b;
console.log(add(2, 3)); // 5
If one parameter, you can omit parentheses:
jsCopyEditconst square = x => x * x;
If no parameters, use
() =>
:
jsCopyEditconst greet = () => console.log("Hi!");
D. Anonymous Function
A function without a name, often used as a callback.
jsCopyEditsetTimeout(function() {
console.log("This runs after 1 second");
}, 1000);
E. Immediately Invoked Function Expression (IIFE)
Runs immediately after being defined.
jsCopyEdit(function() {
console.log("I run automatically!");
})();
F. Constructor Function (Less Common Today)
Used with the new
keyword to create objects.
jsCopyEditfunction Person(name) {
this.name = name;
}
const p = new Person("Alice");
console.log(p.name); // "Alice"
π 3. Function Parameters and Arguments
jsCopyEditfunction greet(name) {
console.log("Hello, " + name);
}
greet("Tom"); // "Hello, Tom"
Use default parameters:
jsCopyEditfunction greet(name = "Guest") {
console.log("Hello, " + name);
}
π 4. Return Values
jsCopyEditfunction add(a, b) {
return a + b;
}
let result = add(3, 4); // 7
π§ Best Practices
- Use arrow functions for short callbacks.
- Use named functions when you need hoisting or better stack traces.
- Use default parameters to avoid
undefined
errors. - Keep functions small and single-purpose.
π§ͺ Practice Challenges
- Define a function
multiply(x, y)
that returns the product. - Convert a traditional function to an arrow function.
- Create an IIFE that logs “Ready to go!”
π Summary Table
Syntax Style | Hoisted | Supports this | Typical Use Case |
---|---|---|---|
function myFunc() | β | β | Standard functions |
const x = function() | β | β | Assign to variables |
const x = () => {} | β | β | Short, simple functions |
(function() {})() | β | β | Run immediately (IIFE) |
Would you like:
- π A PDF or slide version of this tutorial?
- π» An interactive JS playground (CodePen, JSFiddle)?
- π§ A quiz or practice worksheet?