JavaScript Function

What is Function in JavaScript?

JavaScript function is a group of code designed to perform a particular task. it function can be called anywhere in your program.

Syntax :

function name(parameter1, parameter2, parameter3) {
  // code to be executed

Below are the rules for creating Js function:

  • Every function should begin with the keyword function followed by,
  • A user defined function name which should be unique,
  • A list of parameters enclosed within parenthesis and separated by commas,
  • A list of statement composing the body of the function enclosed within curly braces {}.

Example :

// Function definition
function greeting(name) {
   document.write("Hello " + name + " welcome to Elite-Corner");
// creating a variable
var nameVal = "Admin";
// calling the function

Output :

Hello Admin welcome to Elite-Corner

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JS will “return” to execute the code after the invoking statement.

Functions often compute a return value. The return value is “returned” back to the “caller”:

let sum = myFunction(4, 3);   // Function is called, return value will end up in sum

function myFunction(a, b) {
  return a + b;             // Function returns the product of a and b

//sum = 07

I hope you like this article.

Also Read :