J

Functions

JavaScript syntax guide

Function declarations and expressions in JavaScript

Functions

Function declarations and expressions in JavaScript

JavaScript functions (javascript)
        
          // 1. FUNCTION DECLARATIONS (Hoisted)
function greet(name) {
  return `Hello, ${name}!`;
}

// Function declarations are hoisted (can be called before definition)
console.log(greet("Alice")); // ✅ Works: "Hello, Alice!"

// 2. FUNCTION EXPRESSIONS (Not hoisted)
const greetExpression = function(name) {
  return `Hello, ${name}!`;
};

// Anonymous function expression
const square = function(x) {
  return x * x;
};

// Named function expression (useful for debugging)
const factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);
};

// 3. ARROW FUNCTIONS (ES6+)
const greetArrow = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const getUser = () => ({ name: "John", age: 30 }); // Return object

// Arrow functions don't have their own 'this'
const person = {
  name: "Alice",
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, I'm ${this.name}`); // ✅ 'this' refers to person
    }, 1000);
  }
};

// 4. DEFAULT PARAMETERS
function createUser(name, role = "user", active = true) {
  return { name, role, active };
}

createUser("John");           // { name: "John", role: "user", active: true }
createUser("Jane", "admin");  // { name: "Jane", role: "admin", active: true }

// 5. REST PARAMETERS (...args)
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

sum(1, 2, 3);      // 6
sum(10, 20, 30, 40); // 100

function logArguments(first, second, ...others) {
  console.log(first, second, others);
}

logArguments(1, 2, 3, 4, 5); // 1, 2, [3, 4, 5]

// 6. IMMEDIATELY INVOKED FUNCTION EXPRESSIONS (IIFE)
(function() {
  const privateVar = "I'm private";
  console.log(privateVar);
})();

// IIFE with parameters
const result = (function(a, b) {
  return a + b;
})(5, 10);

// 7. HIGHER-ORDER FUNCTIONS
function calculator(operation, a, b) {
  return operation(a, b);
}

const multiply = (x, y) => x * y;
calculator(multiply, 4, 5); // 20

// 8. CLOSURES
function createCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
counter(); // 1
counter(); // 2

// 9. RECURSION
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

fibonacci(6); // 8

// 10. FUNCTION PROPERTIES
function greetUser(name) {
  greetUser.callCount = (greetUser.callCount || 0) + 1;
  return `Hello, ${name}! (Called ${greetUser.callCount} times)`;
}

greetUser("Alice"); // "Hello, Alice! (Called 1 times)"
greetUser("Bob");   // "Hello, Bob! (Called 2 times)"
        
      

Explanation

JavaScript supports multiple ways to define functions. Arrow functions provide concise syntax and lexical this binding.

Common Use Cases

  • Code reusability
  • Event handling
  • API calls

Related JavaScript Syntax

Master Functions in JavaScript

Understanding functions is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using functions effectively in your JavaScript projects.

Key Takeaways

  • Code reusability
  • Event handling
  • API calls