learn2kode.in

JavaScript Functions

A function in JavaScript is a reusable block of code designed to perform a specific task.

You can define a function once and use (call) it many times — this makes your code cleaner, shorter, and easier to manage.

Why Functions Are Useful?

Function Syntax

Function declaration
function functionName() {
  // code to run
}

Calling a function

1. Creating and Calling a Function
Example
function sayHello() {
  console.log("Hello, welcome to Learn2Kode!");
}

sayHello(); // calling the function
2. Functions with Parameters

Parameters allow you to send values into a function.

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

greet("Mani"); 
greet("John");
3. Functions with Return Values

Functions can return a value using return.

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

let total = add(10, 5);
console.log(total); // 15
4. Default Parameters

If a value is not provided, JavaScript uses the default.

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

greet();          // Hello Guest
greet("learn2kode");    // Hello Mani
5. Function Expressions

A function can be stored in a variable.

const multiply = function (x, y) {
  return x * y;
};

console.log(multiply(4, 5)); // 20
6. Arrow Functions (ES6)

A shorter way to write functions.

const add = (a, b) => {
  return a + b;
};

console.log(add(3, 7)); // 10

If the function has only one line:

const square = n => n * n;

console.log(square(5)); // 25
7. Anonymous Functions

A function with no name, often used in event listeners.

setTimeout(function () {
  console.log("This runs after 2 seconds");
}, 2000);
8. Callback Functions

Passing a function as a parameter to another function.

function printMessage() {
  console.log("Hello from callback");
}

function executeCallback(callback) {
  callback();
}

executeCallback(printMessage);
Summary Table
Type Description Example
Function Declaration Standard way to define functions function greet() {}
Function Expression Function stored in a variable const x = function() {}
Arrow Function Short ES6 function syntax const x = () => {}
Callback Function Function passed into another function fn(() => {})