Lesson 4 / 11

Functions and Arrow Functions

function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

const greetArrow = (name, greeting = "Hello") => `${greeting}, ${name}!`;

console.log(greet("Yash"));         // Hello, Yash!
console.log(greetArrow("Yash"));    // Hello, Yash!

Why arrow functions

Arrow functions are shorter to write and, importantly, don’t rebind this the way regular functions do — which matters a great deal once you start writing callbacks and class methods later in this course. For simple one-off functions, especially ones passed as arguments to another function, arrow functions are now the default choice in modern JavaScript.

Default parameters

Just like greeting = "Hello" above, any parameter can have a default value that’s used only when the caller doesn’t supply one. This removes the need for manual checks like if (greeting === undefined) { greeting = "Hello"; } that older JavaScript code was full of.

Callback functions

function processOrder(item, onDone) {
  console.log(`Processing ${item}...`);
  onDone();
}
processOrder("Course", () => console.log("Done!"));

Passing a function as an argument to another function is called a callback, and it’s one of the most common patterns in JavaScript — addEventListener, setTimeout, and array methods like .map() all work this way. You’ll see this pattern constantly for the rest of the course.

Function expressions vs declarations

function declared() { return 1; }   // hoisted -- usable before it's defined in the file
const expression = function() { return 2; };   // not hoisted -- must be defined first

A function declaration is available anywhere in its scope, even in code written above it in the file, because JavaScript “hoists” it to the top. A function stored in a variable (like an arrow function) is not hoisted — it only exists after that line has actually run.