Introduction
Functions are one of the basic building blocks in JavaScript. A function is a set of instructions that perform a task or calculate a value. Functions are reusable and can be called anywhere in your code. They also help organize your code and make it more readable.
Function Declaration
Here's how to define a simple function in JavaScript.
123function FnName(parameters) {
// code to be executed
}
- function is a keyword that starts the function declaration.
- nameOfFunction is the name of the function. Function names can contain letters, digits, underscores, and dollar signs.
- parameters are optional and represent values that we can pass into the function. They act as placeholders for actual values, also known as arguments, that will be input when the function is called.
Refer to the following example.
123function greet(name) {
console.log("Hello, " + name);
}
In the function greet, name is a parameter. When we call the function, we provide an argument for that parameter.
Refer to the following code snippet.
1greet("Alice"); // Outputs: "Hello, Alice"
Functions can have multiple parameters.
1234567function addNumbers(num1, num2) {
return num1 + num2;
}
let sum = addNumbers(5, 10);
console.log(sum); // Outputs: 15
In this case, the function addNumbers is returning the sum of num1 and num2, which is stored in the variable sum and then logged to the console.
Function Expression
Function expressions in JavaScript are a way to define functions as expressions rather than standalone function declarations. Function expressions can be stored in variables, array values, and object properties and passed as arguments to other functions or returned as values by other functions.
Function expressions can be named or anonymous.
Here is an example of a named function expression.
123let greet = function sayHello() {
console.log("Hello, world!");
}
In this example, sayHello is the name of the function. However, this name is only in scope within the function itself, which is useful for recursion (when a function calls itself). Outside the function, you would still call it using the variable name: greet();
Function expressions are used for a variety of reasons, such as:
- They can be used in places where statements aren't allowed, such as inside ternary operators or inside expressions.
- They allow you to define "private" functions that can only be accessed within the scope of an outer function.
- They can be used to define Immediately Invoked Function Expressions (IIFEs), which run as soon as they are defined.
In general, function expressions provide a lot of flexibility in how you define and use functions in JavaScript.
Arrow Function
Arrow functions were introduced in ES6 (ECMAScript 2015) as a new syntax for writing JavaScript functions. They save developers time and simplify function scope.
Here's a basic example of an arrow function.
123let greet = (name) => {
console.log("Hello, " + name);
}
This will behave the same way as the previous function expression examples.
You can also call this function the same way.
1greet("Caroline"); // Output: "Hello, Caroline"
Arrow functions are more powerful and flexible than this, however.
If there's only one argument, you can omit the parentheses around the parameters.
123let greet = name => {
console.log("Hello, " + name);
}
If the function body just returns a value, you can omit the curly braces and the return keyword.
1234let square = num => num * num;
console.log(square(5)); // Output: 25
This version of the function takes a number, squares it, and returns the result.
One key feature of arrow functions is that they do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope. This is different from regular function expressions, which create their own this value. This makes arrow functions very useful when working with object methods, callbacks, and closures.
Immediately Invoked Function Expressions (IIFE)
An IIFE (pronounced "iffy") is a JavaScript function that is executed as soon as it is defined. The main reason for using an IIFE is privacy, because variables declared inside the IIFE cannot be accessed by the outside world.
Here is the syntax of an IIFE.
123(function() {
// statements
})();
Or it can also be written with arrow function syntax.
123(() => {
// statements
})();
Here's a simple example.
1234567(function() {
let message = "Hello, world!";
console.log(message); // Output: "Hello, world!"
})();
console.log(message); // Output: Error: message is not defined
In this example, message is a variable that's only visible within the scope of the IIFE. The IIFE runs immediately, printing "Hello, world!" to the console. When we try to log message outside of the IIFE, we get an error because message is not defined in that scope.
IIFEs are commonly used to create a new lexical scope — they allow you to create local variables that don't pollute the global scope. This is particularly useful if you're writing a library and you don't want to add any new global variables that could conflict with other scripts on the page.
It's important to note that while IIFEs were once the common way to create private scope, the introduction of block-scoped variables (let and const) and modules in ES6 has provided other, often clearer, ways to accomplish the same goals.
Methods
In JavaScript, functions can also be defined as object properties. When a function is a property of an object, we call it a method.
Here's an example of an object that has a method.
1234567let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In this case, fullName is a method of the person object. You can call it as shown in the following code snippet.
1console.log(person.fullName()); // Outputs: "John Doe"
Note the use of the this keyword in the fullName method. Inside a method, this refers to the object that the method is a part of. So this.firstName is equivalent to person.firstName, and this.lastName is equivalent to person.lastName
It's important to note that starting with ES6, there's a new shorthand for defining methods in an object.
Refer to the following code snippet.
1234567let person = {
firstName: "John",
lastName: "Doe",
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
In this case, the function keyword is dropped and we use template literals for string concatenation, which is a more modern approach and is widely used in contemporary JavaScript code.
Whether you're using methods to manipulate the data within your object, or to provide functionality related to your object, methods are a fundamental part of working with objects in JavaScript.