All about Functions In JavaScript

All about Functions In JavaScript

Functions are a fundamental building block of JavaScript. we'll cover all these terminologies related to functions in Javascript.

What are the Functions?

A function is a group of reusable code that can be called anywhere in your program.

There are different ways to define functions in JavaScript:

Function Declarations

Function declaration is a way to define a function in JavaScript using the function keyword, followed by the function name, a pair of parentheses for optional parameters, and a code block enclosed in curly braces.

function add(a, b) {
  return a + b;
}
console.log(add(1,3));  // 4

Function Expression

Function expression is another way to define a function in JavaScript by assigning it to a variable or a constant. Unlike function declarations, function expressions are not hoisted, meaning they must be defined before they are used.

const add = function(a, b) {
  return a + b;
};
console.log(add(1,3));  // 4

Function Declaration Vs Function Expression

 a();
 b();

function a(){
    console.log("This is a function statement example")
}

var b = function (){
    console.log("This is a function expression example")
}
// This is a function statement example
// typeError b is not defined

As shown in the above example, function statements are hoisted, but function expression is not hoisted.

Please refer to this article on hoisting.

Anonymous Functions

A function without a name is called an anonymous function.

An example which we see above in function expression is actually an anonymous function.

const add = function(a, b) {
  return a + b;
};
console.log(add(1,3));  // 4

Named Function Expression

If you provide a name to the function and assign it to a variable.

const add = function named(a, b) {
  console.log(a+b)
};

console.log(add); 
// ƒ addFn(a, b) {
// console.log(a+b)
// } 
add(1,3) // 4
named(1,3)  // Uncaught ReferenceError: named is not defined

In the above example, we assign a function named to the variable add. Now we can access this function using variable add.

If you try to access the named function directly, then it will result in Reference Error.

Parameters and Arguments

  • Parameters are variables listed as a part of the function definition.

  • Arguments are values passed to the function when it is invoked.

Take a look at the following example:

const add = function(a, b) {
  return a + b;
};
console.log(add(1,3));  // 4

In the above code snippet, a & b are Parameters and they are local to the function.

1 & 3 act as an Arguments.

We can pass both variables and functions as function arguments.

Self-Invoking Function

A self-invoking function, also known as an Immediately Invoked Function Expression (IIFE), is a function that is defined and immediately executed or invoked after it is created.

The syntax for a self-invoking function is as follows:

(function() {
  // code to be executed
})();

For Example

(function() {
  var message = "Hello, world!";
  console.log(message);
})();

In the above example, the self-invoking function defines a variable message and logs its value to the console. The function is invoked immediately after it is defined, so the message is printed without needing to explicitly call the function.

The Function() Constructor

The Function() constructor is a built-in constructor in JavaScript that creates a new function object.

It allows you to dynamically define a function at runtime by specifying the function body as a string and a list of arguments.

The syntax for creating a function using the Function() constructor is as follows:

new Function(arg1, arg2, ..., functionBody)
var add = new Function('num1', 'num2', 'return num1 + num2;');
var result = add(5, 10);
console.log(result); // Output: 15

In the above example, a new function object named add is created using the Function() constructor. The function takes two arguments num1 and num2 and returns their sum. The function is then invoked with arguments 5 and 10, resulting in the output 15.

Most of the time, you can avoid using the new keyword in JavaScript.

Constructor Function

a constructor function is a special type of function that is used to create and initialize objects. It serves as a blueprint or template for creating multiple objects with similar properties and behaviors.

Constructor functions are defined using the function keyword.

The name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.

Here's an example of a constructor function for creating a Person object:

function Person(name, age) {
  this.name = name;
  this.age = age;

  this.greet = function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}

// Create instances of the Person object
const person1 = new Person('John', 25);
const person2 = new Person('Jane', 30);

// Access properties and call methods
console.log(person1.name);  // Output: "John"
console.log(person2.age);   // Output: 30
person1.greet();            // Output: "Hello, my name is John and I am 25 years old."
person2.greet();            // Output: "Hello, my name is Jane and I am 30 years old."

In the example above, the Person constructor function takes two parameters (name and age) and assigns them as properties to the newly created object using the this keyword. It also defines a greet method that can be called on instances of the Person object.

To create a new object from the constructor function, you use the new keyword followed by the function call (new Person(...)). This creates a new instance of the object, sets the properties based on the arguments passed, and assigns the newly created object to the variable (person1, person2).

First Class Functions

First-class functions refer to the concept in programming languages where functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, returned as values from other functions, and stored in data structures.

Functions can be assigned to variables:

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

sayHello(); // Output: Hello!

Functions can be passed as arguments to other functions:

function greet(fn) {
  fn();
}

function sayHi() {
  console.log("Hi!");
}

greet(sayHi); // Output: Hi!

Functions can be returned as values from other functions:

function createGreeter() {
  return function() {
    console.log("Greetings!");
  };
}

const greeter = createGreeter();
greeter(); // Output: Greetings!

generator Function

A generator function is a special type of function in JavaScript that can be paused and resumed during its execution. It allows you to define an iterative algorithm by writing a single function that generates a sequence of values on-demand.

To define a generator function, you use the function* syntax (the asterisk (*) denotes that it's a generator function). Within the generator function, you use the yield keyword to specify the values that should be returned when the generator is iterated.

They can be stopped midway and then continue from where they had stopped.

function* numberGenerator() {
  let number = 1;
  while (true) {
    yield number;
    number++;
  }
}

// Create a generator object
const generator = numberGenerator();

// Iterate over the generated values
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3
// ...

In the example above, the numberGenerator function is a generator function that generates an infinite sequence of numbers starting from 1. The yield keyword is used to produce the current value of number and pause the execution of the generator function. Each time generator.next() is called, the generator resumes its execution and continues from where it left off, returning the next value in the sequence.