In JavaScript, functions are first-class citizens, which means that they can be treated like any other value, such as numbers or strings. A function is a block of code that performs a specific task and can be called from other parts of a program.
Functions can take input values, known as parameters, and can return output values. Functions are defined using the function keyword, followed by the name of the function, the parameters enclosed in parentheses, and the function body enclosed in curly braces.
Here is an example of a simple function in JavaScript:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // outputs "Hello, John!"
In this example, the greet function takes a name parameter and outputs a greeting message to the console.
Functions in JavaScript can also be assigned to variables, passed as arguments to other functions, and returned as values from other functions. This makes them very powerful and flexible for building complex programs.
Here is an example of assigning a function to a variable:
var sum = function(a, b) {
return a + b;
};
console.log(sum(2, 3)); // outputs 5
In this example, the sum function is assigned to a variable and can be called using the variable name, just like any other value.