JavaScriptEasy
What is a function in JavaScript?
A function is a callable object that wraps reusable logic; in JavaScript functions are first-class values, so they can be stored in variables, passed as arguments, returned from other functions and given properties.
Ways to create one
- Function declaration:
function add(a, b) {}. Hoisted, has its ownthisandarguments. - Function expression:
const add = function (a, b) {}. Not usable before the line it is defined on. - Arrow function:
const add = (a, b) => a + b. Shorter, no ownthis,argumentsorprototype, cannot be used withnew. - Method shorthand:
{ add(a, b) {} }inside objects and classes. - Also: generator functions (
function*), async functions and class constructors.
Parameters
- Default values:
function greet(name = "friend"). - Rest parameters:
function sum(...nums)collects extra arguments into an array. - Missing arguments are
undefined; extra ones are ignored.
Why "first-class" matters
Because functions are values, JavaScript supports callbacks, higher-order functions (map, filter), closures, and patterns like middleware and event handlers.
Return values
A function without a return (or with a bare return) returns undefined.
Code example
js
1// Declaration (hoisted)2function add(a, b = 0) {3 return a + b;4}56// Expression and arrow7const multiply = function (a, b) {8 return a * b;9};10const square = (n) => n * n;1112// Rest parameters13const sum = (...nums) => nums.reduce((total, n) => total + n, 0);1415// Functions are values: pass them and return them16const apply = (fn, ...args) => fn(...args);17const makeGreeter = (greeting) => (name) => `${greeting}, ${name}!`;1819console.log(add(2)); // 220console.log(multiply(3, 4)); // 1221console.log(apply(square, 5)); // 2522console.log(sum(1, 2, 3, 4)); // 1023console.log(makeGreeter("Hello")("Ada")); // Hello, Ada!2425// Functions are objects, so they have properties26console.log(add.name, add.length); // "add" 1 (params before the first default)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.