JavaScript Function

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when “something” invokes it (calls it).

Function Invocation(Call )

  • When an event occurs (like when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked or self called)

Here’s the basic syntax of a JavaScript function:

				
					function functionName(parameters) {
  // block of code to perform a particular task
  return returnValue; // Optional - used to return a value from the function
}
				
			

Let’s break down the components:

  • functionName: This is the name you give to the function. It’s used to call the function later.

  • parameters: These are optional inputs that you can provide to the function.  They act as placeholders for values that will be used in the function’s operations.

  • Function body: This is where you put the actual code that the function will execute when called. It can consist of any JavaScript statements and expressions.

  • return: This keyword is used to send a value back from the function to the caller. Not all functions need to return a value. If a function doesn’t explicitly return anything, it returns undifined.

Here’s a simple example of a JavaScript function

Function for add two values:

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

const result = addNumbers(5, 3);
console.log(result); // Output: 8

				
			

Arrow Function

An arrow function in JavaScript is a concise way to write function expressions. It was introduced in ECMAScript 6 (ES6) to provide a shorter syntax for creating anonymous functions. Arrow functions are particularly useful for functions that can be expressed in a single line of code.

syntax of a JavaScript Arrow function:

 

				
					const functionName = (parameters) => {
  // Function body: code to be executed when the function is called
  return returnValue; // Optional - used to return a value from the function
};

				
			

Or, if the function body consists of a single expression, you can use an even more concise syntax

 

				
					const functionName = (parameters) => expression;

				
			

Here’s an example of an arrow function that squares a number:

single expression Arrow function

				
					const square = (x) => x * x;

console.log(square(5)); // Output: 25

				
			

Arrow function for more then one line code:

Always include curly brackets For multiline function arrow function. 

				
					const multiLineArrowFunction = (param1, param2) => {
  // Multiple lines of code here
  const sum = param1 + param2;
  const product = param1 * param2;
  return `Sum: ${sum}, Product: ${product}`;
};

console.log(multiLineArrowFunction(5, 3));

				
			

Watch video for better understand about function

https://www.youtube.com/playlist?list=PL01_nAWW7Scv4fE0Lh-Q-vkieJpEq6AdA

Leave a Reply

Your email address will not be published. Required fields are marked *