πŸ“˜ JavaScript Function Definitions

βœ… 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

  1. Define a function multiply(x, y) that returns the product.
  2. Convert a traditional function to an arrow function.
  3. Create an IIFE that logs “Ready to go!”

πŸ“˜ Summary Table

Syntax StyleHoistedSupports thisTypical 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?