2.7 Functions
After exploring objects and arrays, let's look at the last reference type in JavaScript: functions. A function is a named block of statements that performs a task or calculates a value. Functions are the building blocks of every real application — most programs are essentially collections of functions working together.
Declaring and calling a function
To declare a function, use the function keyword, followed by a name, a pair of parentheses, and a pair of braces. The code inside the braces is called the body of the function. To run that code, you call the function by writing its name followed by parentheses:
function greet() {
console.log('Hello everyone');
}
greet(); // prints "Hello everyone"
Notice that the function declaration itself does not end with a semicolon (it's a declaration, not a statement). The call greet() however does end with a semicolon — calling a function is a statement.
Parameters and arguments
Functions become powerful when they accept inputs. Inputs are declared as parameters between the parentheses, and they behave like local variables only meaningful inside the function. When you call the function, you pass actual values called arguments:
function greet(name, lastName) {
console.log('Hello ' + name + ' ' + lastName);
}
greet('John', 'Smith'); // "Hello John Smith"
greet('Mary', 'Doe'); // "Hello Mary Doe"
- A parameter is the placeholder declared in the function signature.
- An argument is the actual value passed when the function is called.
- If you forget to pass an argument, its value defaults to
undefined(you would get "Hello John undefined" in the example above).
That's it for this short demonstration. In the next video, we'll explore the different types of functions in JavaScript.