JavaScript Functions

JavaScript Tutorial

JavaScript Functions

In JavaScript Functions is a block of code designed to perform a specific task. Instead of writing the same code again and again, you can put it inside a function and reuse it whenever needed.

Functions help make code modular, reusable, and cleaner.


 Function Syntax

To run (call) a function:


Example

Output:

Hello, welcome to JavaScript!

Functions with Parameters

Parameters allow you to pass values into a function.

Output:

Hello Vipul
Hello John

Functions with Return Value

A function can return a value using return.

Output:

15

 Function Expressions

Functions can also be stored in a variable.


 


Arrow Functions (ES6)

Arrow functions provide a shorter syntax.


 


 Self-Invoking Function

A function that runs automatically without being called:


Summary Table

Type of FunctionExample
Normal Functionfunction myFun() {}
Function with Parametersfunction add(a,b){}
Return Functionreturn value;
Function Expressionconst x = function(){}
Arrow Functionconst x = () => {}
Self Invoking(function(){})();

 Why Use Functions?

  • Reuse code (write once, use many times)

  • Makes code clean and organized

  • Helps in modular programming

You may also like...