JavaScript Functions

Functions are fundamental building blocks in JavaScript. They encapsulate reusable code, help organize logic, and support modular programming. JavaScript offers multiple ways to define and use functions, including function declarations, function expressions, arrow functions, callback functions, and higher-order functions.


Function Declarations in JavaScript

A function declaration defines a named function that can be invoked later in the code. It uses the function keyword followed by the function name, parameters, and a block of executable code.

Function Declaration Syntax

function functionName(parameters) {
  // Code to be executed
}

Basic Function Declaration Example

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Output: "Hello, Alice!"

Hoisting Behavior in Function Declarations

Function declarations are hoisted, meaning they can be called before their definition appears in the code.

console.log(add(5, 3)); // Output: 8

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

Function Expressions in JavaScript

A function expression defines a function and assigns it to a variable. Unlike function declarations, function expressions are not hoisted.

Function Expression Syntax

const functionName = function(parameters) {
  // Code to be executed
};

Basic Function Expression Example

const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5)); // Output: 20

Anonymous Function Expressions

Function expressions are often used to create anonymous functions, which do not have a function name.

const sayHello = function() {
  console.log("Hello!");
};

sayHello(); // Output: "Hello!"

Arrow Functions in JavaScript

Arrow functions provide a shorter syntax for writing functions and do not have their own this context. They are ideal for concise logic and preserving lexical scope.

Arrow Function Syntax

const functionName = (parameters) => {
  // Code to be executed
};

Arrow Function with Single Parameter

const square = x => x * x;

Arrow Function with No Parameters

const greet = () => "Hello!";

Basic Arrow Function Example

const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5

Arrow Functions and the this Keyword

Arrow functions inherit this from their surrounding context instead of defining their own.

function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++;
    console.log(this.age);
  }, 1000);
}

const person = new Person();

Callback Functions in JavaScript

A callback function is passed as an argument to another function and executed after a specific operation completes. Callbacks are commonly used for asynchronous tasks.

Synchronous Callback Example

function processUserInput(callback) {
  const name = prompt("Please enter your name:");
  callback(name);
}

function greet(name) {
  console.log(`Hello, ${name}!`);
}

processUserInput(greet);

Asynchronous Callback Example Using setTimeout

console.log("Start");

setTimeout(() => {
  console.log("This is a callback function");
}, 2000);

console.log("End");

Output

Start
End
This is a callback function

Higher-Order Functions in JavaScript

A higher-order function is a function that can accept other functions as arguments, return functions, or both. These functions are central to JavaScript’s functional programming paradigm.

Custom Higher-Order Function Example

function repeatTask(task, times) {
  for (let i = 0; i < times; i++) {
    task();
  }
}

function sayHello() {
  console.log("Hello!");
}

repeatTask(sayHello, 3);

Built-in Higher-Order Functions in JavaScript

JavaScript provides several built-in higher-order functions for working with arrays.

map() Function Example

const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(num => num * num);

console.log(squares); // Output: [1, 4, 9, 16, 25]

filter() Function Example

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]

reduce() Function Example

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);

console.log(sum); // Output: 15

Summary of JavaScript Functions

JavaScript offers multiple ways to define and use functions, making them highly flexible and powerful.

  • Function declarations support hoisting
  • Function expressions provide flexibility with variable assignment
  • Arrow functions simplify syntax and preserve this
  • Callback functions enable asynchronous programming
  • Higher-order functions enhance functional programming capabilities

Mastering these function types is essential for building efficient, scalable, and modular JavaScript applications.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *