![]() |
VOOZH | about |
In JavaScript, functions are blocks of reusable code designed to perform a specific task. Understanding how to declare and invoke (call) functions is fundamental to writing efficient and maintainable code.
Function Declaration is how we define a function using the function keyword, giving it a name, optional parameters, and a body of code to execute. These declarations are a powerful way to structure your programs.
Syntax
function functionName(parameters) {
// code to execute
}
Note: Function declarations are hoisted. This means you can call them before they’re defined in the code!
Function invocation refers to executing the code defined in a function. Function invocation occurs when a function is called or executed in JavaScript. When invoked, the code inside the function block is run, and any return value is computed and passed back to the caller.
Syntax
function functionName(parameters) {
// code to be executed
}
JavaScript provides several ways to invoke functions. Each method affects the behavior of this (the execution context) and other factors.
When a function is called directly using its name, it operates in the global or local scope.
Scope: In non-strict mode, this defaults to the global object (window in browsers).
When a function is a property of an object and is invoked as object.method(), it is called a method invocation.
In method invocation, this refers to the object that owns the method (in this case, user).
Functions can be invoked as constructors using the new keyword. When invoked this way, the function creates a new object and sets this to refer to that object.
A constructor invocation returns the newly created object.
Functions can be invoked indirectly using call(), apply(), or bind().
call(): Invokes a function and explicitly sets this and individual arguments.
apply(): Similar to call(), but arguments are passed as an array.
Output
Hi, Riya!bind(): Creates a new function with this permanently set to the provided value.
Self-invoking (or immediately invoked) functions run automatically without being explicitly called. These are often written as Immediately Invoked Function Expressions (IIFEs).
IIFEs are commonly used for encapsulating code to avoid polluting the global scope.
Arrow functions are invoked like regular functions but differ in how they handle this. They do not bind their own this; instead, they inherit this from their lexical scope.