← Back to Roadmap

Functions

Easy

In plain terms

A function is a named block of code that runs when you call it. Instead of repeating the same code in many places, you write it once inside a function and call that function whenever you need it.

Functions can accept inputs called parameters. For example, greet(name) takes a name and uses it. Functions can also return a value—whatever you put after return gets sent back to the caller.

In JavaScript, functions are "first-class": you can store them in variables, pass them as arguments, and return them from other functions. This flexibility makes functions very powerful.

What you need to know

  • function name(params) { }
  • return sends value back
  • First-class: can be assigned, passed

Try it yourself

Copy the code below and run it in your browser console or a code editor:

function greet(name) {
  return 'Hello, ' + name;
}
greet('Alice');  // "Hello, Alice"

function add(a, b) {
  return a + b;
}
add(2, 3);  // 5

// No return = undefined
function log(x) {
  console.log(x);
}

Why this matters

First-class functions are core to JS; callbacks, closures, and higher-order functions all build on this. Interviewers ask about hoisting, arrow vs regular functions, and passing functions as arguments.

How it connects

Functions lead to closures (inner functions capturing outer scope), call/apply/bind (controlling this), and async (callbacks, Promises). They are the unit of reuse before you get to classes and modules.

Interview focus

Be ready to explain these; they come up often in JS interviews.

  • First-class: functions can be assigned, passed, returned. Enables callbacks and HOFs.
  • Declaration vs expression: hoisting difference; arrow functions and lexical this.
  • Pure functions: same input → same output, no side effects; easier to test.

Learn more

Dive deeper with these trusted resources: