Sobes.tech
Intern

What is a function in JavaScript?

sobes.tech AI

Answer from AI

A function in JavaScript is a block of reusable code that performs a specific task. Functions can accept input data (arguments) and return a value.

Types of functions:

  • Function Declaration:
    // Declaration of function 'greet'
    function greet(name) {
      return "Hello, " + name + "!";
    }
    
  • Function Expression:
    // Function expression assigned to variable 'sayHello'
    const sayHello = function(name) {
      return "Hello, " + name + "!";
    };
    
  • Arrow Function:
    // Arrow function for concise syntax
    const multiply = (a, b) => a * b;
    

Main features:

  • First-Class Objects: Functions can be assigned to variables, passed as arguments, and returned from other functions.
  • Scope: Functions create their own variable scope (local variables).
  • Closures: Functions can "remember" and access variables from their outer scope even after that outer function has finished execution.

Example of closure:

function createCounter() {
  let count = 0; // Variable in outer scope

  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2