In JavaScript, a function is a block of code that performs a specific task. Functions are an essential part of the language and are used to organize and structure your code. You can create your own functions in JavaScript and there are some built-in functions too.
A JavaScript function has the following syntax:
function functionName(parameter1, parameter2, ...) {
// Function code goes here
}
The function
keyword is used to declare a function. After the keyword, you specify the name of the function (which should be a descriptive and unique identifier). In the parentheses, you can specify one or more parameters that the function can accept. These are the values that will be passed to the function when it is called. The code for the function goes inside the curly braces.
Here is an example of a simple function that calculates the sum of two numbers:
function sum(x, y) {
return x + y;
}
To call a function, you simply use the function’s name followed by the required arguments in the parentheses. For example:
sum(1, 2); // returns 3
Functions can also be defined using the function
keyword followed by the function name and a fat arrow (=>
). This is called an arrow function and is a shorthand syntax for defining functions. For example:
const sum = (x, y) => x + y;
In this example, we are defining a function named sum
that accepts two parameters (x
and y
) and returns the sum of those two numbers. The arrow function syntax is more concise and can be useful when defining short or single-line functions.
I hope this helps! Let me know if you have any questions.