- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Function Declaration
In JavaScript, a function declaration is the most traditional way to define a function. Think of it as creating a recipe: you give it a name, list the ingredients (parameters), and write down the steps to follow (the function body). Once declared, you can "cook" that recipe as many times as you want throughout your program.
One unique feature of function declarations is hoisting. This means JavaScript moves the declaration to the top of its scope during execution, allowing you to call the function even before the line where it is defined.
calculateTotal or fetchUserData). This makes your code self-documenting and easier for other developers to read.
Syntax:
function functionName(parameter1, parameter2, /* ... */) {
// Code to be executed when the function is called
}
- functionName: The unique identifier you'll use to call the function later.
- parameter1, parameter2, ...: Placeholders that accept input values. You can have zero, one, or many parameters.
- Function body: The block of code wrapped in curly braces
{}that performs the actual task.
Why it is Used:
- Modular Code: Instead of writing the same logic ten times, you write it once inside a function and call it whenever needed. This makes your codebase smaller and easier to manage.
- Code Organization: Functions allow you to group related logic together, making the overall structure of your application logical and predictable.
- Code Reusability: Once a function is declared, it can be shared across different parts of your application or even across different projects.
Example:
// Function Declaration
function greet(name) {
console.log('Hello, ' + name + '!');
}
// Calling the Function
greet('John'); // Output: Hello, John!
() when calling a function. If you write greet instead of greet(), JavaScript will return the function definition itself rather than executing the code inside it.
Examples:
Simple Addition Function
This is a classic example of a function that takes inputs, processes them, and returns a result to the caller using the return keyword.
// Function Declaration for Addition
function addNumbers(a, b) {
return a + b;
}
// Calling the Function and storing the result in a variable
const sum = addNumbers(5, 7);
console.log('Sum:', sum); // Output: Sum: 12
Greeting Function with Default Parameter
Modern JavaScript allows you to set "default" values. If someone calls the function without providing an argument, the default value kicks in.
// Function Declaration with Default Parameter
function greet(name = 'Guest') {
console.log('Hello, ' + name + '!');
}
// Calling without an argument
greet(); // Output: Hello, Guest!
// Calling with an argument
greet('Alice'); // Output: Hello, Alice!
Area of a Rectangle Function
In real-world applications, you might use functions to handle UI calculations, such as determining the size of a container or a canvas element.
// Function Declaration for Calculating Area
function calculateRectangleArea(length, width) {
return length * width;
}
// Calling the Function
const area = calculateRectangleArea(10, 5);
console.log('Area of Rectangle:', area); // Output: Area of Rectangle: 50
Checking Even or Odd Function
Functions are often used to encapsulate logic that returns a boolean or a specific string based on a condition, which is very common in data filtering.
// Function Declaration for Even or Odd
function checkEvenOrOdd(number) {
return number % 2 === 0 ? 'Even' : 'Odd';
}
// Calling the Function
console.log(checkEvenOrOdd(7)); // Output: Odd
console.log(checkEvenOrOdd(10)); // Output: Even
return keyword if you want your function to give a value back to the rest of your program. Without it, the function will return undefined by default.
Summary
- Named Definitions: Function declarations define a reusable block of code with a specific name.
- Hoisting: These functions are moved to the top of their scope, meaning they can be called before they appear in the source code.
- Structure: They always use the
functionkeyword followed by a name, parameters in parentheses, and a body in curly braces. - Reusability: They are the primary building block for creating clean, modular, and maintainable JavaScript applications.