JS Functions

Overview

Functions are reusable blocks of code that perform specific tasks or calculations. They help in organizing and modularizing code, promoting reusability and maintainability.


Function Definition

A function is defined using the function keyword, followed by a function name and parentheses containing optional parameters.

Try yourself
        
            function greet(name) {
    console.log("Hello, " + name + "!");
}

greet("Alice");
        
    

Function Parameters

Parameters are placeholders in the function definition that receive values when the function is called.

Try yourself
        
            function add(a, b) {
    return a + b;
}

add(3,4)
        
    

Function Return

Functions can return values using the return statement. The value returned can be assigned to a variable.

Try yourself
        
            function multiply(x, y) {
    return x * y;
}

let result = multiply(4, 6); // result is 24
        
    

Function Expression

Functions can also be assigned to variables, creating function expressions.

Try yourself
        
            const greet = function(name) {  
    console.log("Hello, " + name + "!");
};

greet("Bob");    // Outputs: Hello, Bob!

        
    

Anonymous Functions

Function expressions without a name are called anonymous functions.

Try yourself
        
            var greet = function(name) {  // Anonymous Functions
    console.log("Hello, " + name + "!");
};

greet("Eve");    // Outputs: Hello, Eve!


function getName(name) {  // Named Functions
    console.log("Hello, " + name + "!");
}
getName("Alex"); // Outputs: Hello, Alex!
        
    

Arrow Functions (ES6)

Arrow functions provide a concise syntax for defining functions.

Try yourself
        
            var square = (x) => x * x;
console.log(square(3)); // Outputs: 9
        
    

Function Scope

Variables declared within a function are only accessible within that function's scope.

Try yourself
        
            function scopeExample() {
    var localVar = "I'm local!";
    console.log(localVar);   // Outputs: I'm local! (Accessible)
}
scopeExample()
console.log(localVar);       // Error: localVar is not defined. (Not accessible)
        
    

Lexical this Binding

Arrow functions do not have their own this context. Instead, they inherit the this value from the enclosing function or context in which they are defined.

Try yourself
        
            function Person(name) {
    this.name = name;
}
const john = new Person('John');
console.log(john.name);  // Output: John

const Person = (name) => {
    this.name = name; // 'this' is not properly bound
};
const john = new Person('John');
console.log(john.name);  // Output: Error - this.name is not defined

        
    
Regular Functions

In regular functions, the value of the this keyword is determined by how the function is called. It can take on different values depending on the context in which the function is invoked:

Try yourself
        
            function regularFunction() {
    console.log(this);
}

const obj = {
    method: regularFunction
};

regularFunction(); // `this` refers to the global object (window in a browser)
obj.method();      // `this` refers to `obj`

        
    
Arrow Functions

Arrow functions do not have their own this context. Instead, they inherit the this value from the surrounding lexical context. This makes arrow functions particularly useful when you want to maintain the value of this from the outer scope, such as when using them as callbacks within other functions or when working with closures.

Try yourself
        
            const obj = {
    arrowMethod: () => {
        console.log(this);
    },
    regularMethod: function() {
        console.log(this);
    }
};

obj.arrowMethod();   // `this` refers to the surrounding lexical context (often global)
obj.regularMethod(); // `this` refers to `obj`

        
    

More Examples

Try yourself
        
            // Regular Function:
function multiply(a, b) {
    return a * b;
}

// Arrow Function:
const multiply = (a, b) => a * b;
// or
const multiply = (a, b) => {
    return a * b
};