JavaScript Functions - CodingQue

JavaScript Functions

In JavaScript, functions are reusable blocks of code that perform a specific task. They make code modular, efficient, and easy to manage.

1. Defining Functions

Functions can be defined in two primary ways in JavaScript:

Example: Defining Functions with function Keyword

The function keyword is followed by the function name, parameters (if any), and the function body.

function greet(name) {
    return "Hello, " + name;
}

Example: Using Arrow Functions

Arrow functions offer a shorter syntax, especially useful for simple functions.

let greetArrow = (name) => "Hello, " + name;

2. Calling Functions

To execute a function, use its name followed by parentheses. Pass any required arguments within the parentheses.

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

3. Function Parameters and Arguments

Functions can accept multiple parameters, separated by commas. When calling the function, values passed are called arguments.

function add(a, b) {
    return a + b;
}
console.log(add(5, 10)); // Outputs: 15

4. Default Parameters

In ES6, JavaScript introduced default parameters, allowing functions to use default values if no argument is provided.

function greet(name = "Guest") {
    return "Hello, " + name;
}
console.log(greet()); // Outputs: Hello, Guest

5. Function Expressions

Functions can also be assigned to variables. These are called function expressions and are often anonymous (no name).

const square = function(number) {
    return number * number;
};
console.log(square(5)); // Outputs: 25

6. IIFE (Immediately Invoked Function Expressions)

IIFEs are functions that are invoked immediately after they are defined, often used to create a private scope.

(function() {
    console.log("IIFE Executed!");
})();

7. Arrow Functions vs Regular Functions

Arrow functions have a lexical this context, meaning they do not have their own this, but inherit it from the surrounding code.

function regularFunction() {
    console.log(this);
}
const arrowFunction = () => {
    console.log(this);
};
regularFunction(); // 'this' depends on how it's called
arrowFunction(); // 'this' refers to the outer scope

8. Function Scope

Variables defined within a function are only accessible within that function (local scope). Variables defined outside are in global scope.

function showMessage() {
    let message = "Hello!";
    console.log(message);
}
showMessage(); // Outputs: Hello!
console.log(message); // Error: message is not defined

9. Returning Multiple Values

Functions can return multiple values using arrays or objects.

function calculate(a, b) {
    return [a + b, a - b];
}
let [sum, difference] = calculate(10, 5);
console.log(sum, difference); // Outputs: 15 5
Previous Next
Modern Footer