Skip to main content

Definitions of Function

JavaScript functions are used to define reusable pieces of code that can be executed when called.

Functions are an essential part of JavaScript programming and allow for modular and organized code.

Basic syntax of define functions in JavaScript:

Function Declaration

function functionName(parameters) {
// function body
// code to be executed
// ...
}
  • This is the most common way to define a function in JavaScript.
  • The function declaration starts with the function keyword, followed by the function name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces {}.

Function Expression

An expression can also be used to define a JavaScript function.

A function expression can be stored in a variable:

var functionName = function (parameters) {
// function body
// code to be executed
// ...
};

In this example:

  • Function is defined as an anonymous function and assigned to a variable.
  • The variable then becomes a reference to the function and can be invoked like a regular function.

Arrow Function (ES6+)

Now let's look at the syntax for defining an arrow function in JavaScript.

const functionName = (parameters) => {
// function body
// code to be executed
// ...
};

Arrow functions are a concise way to define functions in JavaScript introduced in ECMAScript 6 (ES6).

They use a shorter syntax and have lexical scoping of this, making them useful for certain scenarios.

Function Constructor

The Basic syntax of Arrow Function:

var functionName = new Function("parameters", "... function body ...");

The Function constructor is a less common way to define functions in JavaScript. It takes a series of strings as arguments that represent the parameters and function body and returns a new function object.

Function Hoisting

Function hoisting is a behavior in JavaScript where function declarations are automatically moved to the top of the code during the compilation phase, before the code is executed. This allows you to call a function before it is actually defined in the code.

As an example:

foo(); // Function call before declaration

function foo() {
console.log("Function has been hoisted!");
}

In this example:

  • The foo() function is called before its declaration, JavaScript hoists the function declaration to the top of the code, making it accessible for execution.
  • This code will run without any errors and print "Function has been hoisted!" to the console.

Self-Invoking Functions

Self-invoking functions, also known as Immediately Invoked Function Expressions (IIFE), are functions in JavaScript that are defined and executed immediately after their creation. They are often used to create a private scope for variables and functions, preventing them from polluting the global scope.

Here's an example of a self-invoking function:

(function () {
// Function body
// Code to be executed
})();

In the above example:

  • A function is defined within parentheses () and immediately invoked with an additional set of parentheses at the end ().
  • This causes the function to be executed immediately after it is defined.

Common use of self-invoking functions

Self-invoking functions are commonly used in JavaScript for various purposes.

such as:

Creating a private scope

Variables and functions defined within a self-invoking function are scoped to that function and are not accessible from outside the function, effectively creating a private scope. This can help prevent variable name clashes and keep the global scope clean.

As an example:

(function () {
var privateVar = "This is private";
// privateVar is only accessible within the function
})();

console.log(privateVar); // Error: privateVar is not defined

Encapsulating code

Self-invoking functions can be used to encapsulate code, allowing you to group related logic and isolate it from the rest of the codebase. This can improve code organization and readability.

As an example:

(function () {
// Code related to a specific task or feature
// ...
})();

Achieving module-like behavior

Self-invoking functions can be used to create modular code by encapsulating functionality within a self-contained function that exposes only the necessary public interfaces.

As an example:

var module = (function () {
var privateVar = "This is private";

function privateFunction() {
// Code for private function
}

return {
publicVar: "This is public",
publicFunction: function () {
// Code for public function
},
};
})();

console.log(module.publicVar); // "This is public"
module.publicFunction(); // Call to public function

Functions Can Be Used as Values

Functions are first-class citizens in javascript, which means they can be treated as values and used in various ways just like other types of values such as numbers, strings, or objects. This is one of the powerful features of JavaScript that allows for functional programming paradigms.

Here are some examples of how functions can be used as values in JavaScript:

Assigning functions to variables

As an example:

const greet = function () {
console.log("Hello!");
};

greet(); // "Hello!"

In the above example:

  • A function expression is assigned to a variable greet, and the function can be called using the variable as a regular function.

Passing functions as arguments to other functions

As an example:

function execute(callback) {
callback();
}

function greet() {
console.log("Hello!");
}

execute(greet); // "Hello!"

In the above example:

  • The greet function is passed as an argument to the execute function, which then calls the callback function.

Returning functions from other functions

As an example:

function getGreeting() {
return function () {
console.log("Hello!");
};
}

const greet = getGreeting();
greet(); // "Hello!"

In the above example:

  • The getGreeting function returns another function, which can be assigned to a variable and called like any other function.

Using functions as objects

As an example:

function greet() {
console.log("Hello!");
}

greet.message = "Welcome!";

console.log(greet.message); // "Welcome!"

In the above example:

  • Functions can have properties just like objects, and you can attach custom properties or methods to a function.

Creating higher-order functions

As an example:

function multiplyBy(factor) {
return function (num) {
return num * factor;
};
}

const double = multiplyBy(2);
console.log(double(5)); // 10

In the above example:

  • The multiplyBy function returns another function, creating a higher-order function that can generate new functions with specific behavior.