Functions

A function is a reusable block of code that performs a specific task.

Instead of writing the same code again and again, you write it once inside a function and call it whenever needed.


Basic Function

function greet(){
   console.log("Hello");
}

greet();
  • function → keyword to create a function
  • greet → function name
  • {} → function body

At this point, nothing is printed.

The function is only stored in memory.

Call the function

greet();

Output:

Hello

The code inside the function executes.


Function with Parameters

Parameters allow a function to receive data.

function greet(name){
   console.log("Hello " + name);
}

greet("John");

Output:

Hello John

Multiple Parameters

function introduce(name, age){
   console.log(name + " is " + age + " years old");
}

introduce("John", 25);

Output:

John is 25 years old


Return Value

Sometimes a function should send a value back.

For that we use:

return

Example:

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

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

Output:

8

Why Return is Important

Without return:

function add(a,b){
   a+b;
}

Output:

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

Result:

undefined

Because nothing was returned.