JavaScript functions are one of the most essential features of the language. They are a set of statements that perform a specific task or calculate a value. In JavaScript, a function is defined with the keyword, followed by a name and parentheses ()
. The code inside the function is enclosed in curly braces {}
.
Creating a Function
Here is a basic example of a JavaScript function that adds two numbers together:
function addNumbers(num1, num2) {
return num1 + num2;
}
In this example, addNumbers
is the name of the function. num1
and num2
are parameters of the function, and they represent the two numbers that will be added together. The return
keyword is used to return the sum of num1
and num2
.
Calling a Function
Once a function is defined, it can be called (or invoked) later in the code using the function name and passing in arguments for the parameters. Here is an example of how to call the addNumbers
function:
var sum = addNumbers(5, 7);
console.log(sum); // Output: 12
In this example, the addNumbers
the function is called with the arguments 5
and 7
. The returned value of 12
is stored in the sum
variable, which is then logged into the console.
Function Expressions
Another way to define a function in JavaScript is by using a function expression. This involves assigning a function to a variable:
var multiplyNumbers = function(num1, num2) {
return num1 * num2;
};
In this example, the function is assigned to a variable named multiplyNumbers
. The function can then be called by using the variable name and passing in arguments:
var product = multiplyNumbers(4, 3);
console.log(product); // Output: 12
Anonymous Functions
An anonymous function is a function that does not have a name. Anonymous functions are often used in JavaScript when passing a function as an argument to another function. Here is an example of an anonymous function:
setTimeout(function() {
alert('Hello, World!');
}, 5000);
In this example, the setTimeout
the function is called with an anonymous function as the first argument. The anonymous function will be executed after a delay of 5000 milliseconds (5 seconds), and it will display an alert message.
Functions are a fundamental aspect of JavaScript programming. They allow us to encapsulate and reuse code, and they provide a way to organize and structure our code. In addition to the basics covered in this article, there are many more advanced topics related to functions in JavaScript, such as closures and recursion. By mastering functions, you will be well on your way to becoming a proficient JavaScript programmer.