JavaScript(JS) Functions

h‮:sptt‬//www.theitroad.com

JavaScript functions are blocks of code that can be defined and invoked to perform a specific task. Functions are a fundamental concept in JavaScript and are used extensively in web development.

Here is an example of a basic JavaScript function:

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

In this example, greet is the name of the function, and name is the parameter that is passed to the function. The code in the function body will execute whenever the function is called.

To call the function, you can simply use its name followed by parentheses and the argument you want to pass in:

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

Functions can also return a value. Here is an example:

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

In this example, the add function takes two parameters a and b and returns their sum using the return keyword. To use the returned value, you can assign the function call to a variable:

let result = add(2, 3);
console.log(result); // Output: 5

Functions can also be assigned to variables or passed as arguments to other functions, making them a powerful and flexible tool in JavaScript.