JavaScript Functions

Subject: JavaScript

Functions in JavaScript are reusable blocks of code created to perform a specific task. They improve code readability, modularity, and help reduce repetition.


What is a Function?

A function is a group of statements that performs a task or returns a value. You define it once and can call it multiple times.


Syntax

  • functionName: Name used to call the function
  • parameters: Optional values passed into the function

Example 1: Basic Function


Example 2: Function with Parameters


Example 3: Function Expression


Example 4: Arrow Function (ES6+)


Example 5: Default Parameters


Types of Functions

TypeDescription
Function DeclarationDeclared with the function keyword
Function ExpressionStored in a variable
Arrow FunctionShorter ES6 syntax
Anonymous FunctionFunction without a name
Callback FunctionPassed as an argument to another function

Key Takeaways

  • Functions promote reusability and modular design.
  • You can use return to send a value back.
  • JavaScript supports default parameters.
  • Functions can be passed around as first-class citizens.
  • Choose between declaration, expression, or arrow functions based on use case.
Next : Function Parameters