JavaScript Functions

JavaScript functions are blocks of code that can be reused multiple times throughout a program. They are defined using the "function" keyword, followed by a name and a set of parentheses. The parentheses may contain parameters, which are values that are passed into the function when it is called.

Here is an example of a simple JavaScript function that takes in a single parameter, called "name":

function greet(name) {
  console.log("Hello, " + name + "!");
}

This function can be called by using the function name, followed by the parameter in parentheses:

greet("John");  // Output: "Hello, John!"
greet("Jane");  // Output: "Hello, Jane!"

Functions can also return a value using the "return" keyword. For example:


function add(a, b) {
  return a + b;
}

let sum = add(3, 4);  // sum is equal to 7

Functions can also be defined as variables and can be assigned to variables and also they can be passed as an argument to another function. For example:

let greet = function(name) {
  console.log("Hello, " + name + "!");
}

JavaScript also supports arrow functions, which are a shorthand way of defining anonymous functions. Here is the previous example written as an arrow function:

let greet = (name) => {
  console.log("Hello, " + name + "!");
}

JavaScript functions are a powerful tool that allows you to write clean, reusable code. They can be used to perform a wide variety of tasks, from simple calculations to complex logic. By breaking your code into small, manageable functions, you can make your programs more readable and easier to understand.