JavaScript Functions

JavaScript Functions

JavaScript Functions

In JavaScript, a function is a block of code that can be called and executed to perform a specific task. Functions are used to break up complex code into smaller, more manageable pieces, and to reuse code across different parts of a program. Here’s an example of a simple function in JavaScript:

				
					function sayHello(name) {


console.log("Hello, " + name + "!");


}
				
			

This function takes a parameter called name and uses it to print out a greeting to the console. To call this function and pass in a name, you would write:

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

Functions in JavaScript can also return values. Here’s an example of a function that takes two numbers and returns their sum:

				
					function addNumbers(num1, num2)
{

return num1 + num2;

}
				
			

To call this function and get the result, you would write:

				
					let result = addNumbers(5, 3);
// Assigns the value 8 to the variable result

console.log(result); // Output:
8
				
			

Functions in JavaScript can be defined in several ways, including as function declarations, function expressions, and arrow functions. They can also be stored in variables, passed as arguments to other functions, and returned from other functions. Understanding how to use functions effectively is a key part of writing good JavaScript code.

Join To Get Our Newsletter
Spread the love