Functions in JavaScript
A function is a block of code designed to perform a particular task. A function is executed when “something” invokes it (calls it).
Why use Functions?
- Reusability: You can define the code once and use it many times.
- Abstraction: You can use the code many times with different arguments, to produce different results.
Function Declaration
A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:
- The name of the function.
- A list of parameters to the function, enclosed in parentheses and separated by commas.
- The JavaScript statements that define the function, enclosed in curly brackets,
{ ... }.
Syntax:
function functionName(parameter1, parameter2) { // code to be executed}Example:
function greet(name) { console.log("Hello, " + name + "!");}
greet("Alice"); // Output: Hello, Alice!Function Expression
A function can also be defined using an expression. A function expression can be stored in a variable:
const square = function(number) { return number * number;};
console.log(square(4)); // Output: 16Arrow Functions
Arrow functions were introduced in ES6. They allow us to write shorter function syntax:
const add = (a, b) => { return a + b;};
console.log(add(5, 3)); // Output: 8If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:
const multiply = (a, b) => a * b;
console.log(multiply(5, 3)); // Output: 15Parameters and Arguments
- Parameters are the names listed in the function’s definition.
- Arguments are the real values passed to the function.
function sum(x, y) { // x and y are parameters return x + y;}
let result = sum(10, 20); // 10 and 20 are argumentsThe Return Statement
When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will “return” to execute the code after the invoking statement.
Functions often compute a return value. The return value is “returned” back to the “caller”:
function myFunction(a, b) { return a * b;}
let x = myFunction(4, 3); // x will be 12Happy Coding!