JavaScript Functions

Summary: in this tutorial, you will learn about JavaScript functions and how to use them to structure the code into smaller and more reusable units.


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. or you can also say Functions are one of the fundamental building blocks in js.

JavaScript Function 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
greeting(nameVal);
  

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

Summary

  • Use the <strong>function</strong> keyword to declare a function.
  • Use the <strong>functionName()</strong> to call a function.
  • All functions implicitly return undefined if they don’t explicitly return a value.
  • Use the <strong>return</strong> statement to return a value from a function explicitly.
  • The <strong>arguments</strong> variable is an array-like object inside a function, representing function arguments.
  • The function hoisting allows you to call a function before declaring it.

Que : What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: 

  1. Function Declaration.
  2.  Function Expression
  3. Arrow Function.

I hope you like this Amazing javascript Functions article.

Also Read :