In programming, the term “function” can have different meanings. In Functional Programming (FP), it has a strict mathematical definition. But in JavaScript, a function is more broadly understood as a procedure: a set of statements that can be invoked multiple times, may receive inputs, and may return outputs.
From the early days of JS, functions have been defined like this:
function awesomeFunction(coolThings) {
// ...
return amazingStuff;
}This is a function declaration because it appears as a standalone statement. The association between the name awesomeFunction and the function value happens during the compile phase, before execution.
Functions can also be defined as expressions and assigned to variables:
var awesomeFunction = function(coolThings) {
// ...
return amazingStuff;
};Unlike declarations, function expressions are associated with their identifiers at runtime, not during compilation.
In JavaScript, functions are values — they can be assigned to variables, passed as arguments, and stored in data structures. JS functions are a special type of object, which enables functional programming patterns.
Functions can receive input via parameters:
function greeting(myName) {
console.log(`Hello, ${myName}!`);
}
greeting("Kyle"); // Hello, Kyle!myName is a parameter that acts as a local variable inside the function. You can define any number of parameters, and each receives the corresponding argument from the function call.
Functions can return values using the return keyword:
function greeting(myName) {
return `Hello, ${myName}!`;
}
var msg = greeting("Kyle");
console.log(msg); // Hello, Kyle!Only one value can be returned directly, but multiple values can be wrapped in an array or object.
Because functions are values, they can be assigned as properties on objects:
var whatToSay = {
greeting() {
console.log("Hello!");
},
question() {
console.log("What's your name?");
},
answer() {
console.log("My name is Kyle.");
}
};
whatToSay.greeting(); // Hello!Here, three functions are defined as properties of the whatToSay object. Each can be called by accessing the property name. This style is simpler than class-based syntax, which is covered later in the book.
Functions in JavaScript are powerful and versatile. They can be declared or expressed, accept parameters, return values, and be stored as object properties. Understanding these forms and behaviors is essential for writing clean, reusable, and expressive code.