Skip to main content

What is function in Javascript?

A function is a block of code that performs a specific task and can be reused throughout your code.

Functions can take inputs (called parameters) and return outputs.

Example of a basic function:

function addNumbers(num1, num2) {
return num1 + num2;
}
  • This function takes two parameters, num1 and num2, and returns their sum.

You can call this function by passing in arguments for the parameters:

let result = addNumbers(5, 10); // result is 15

Functions in JavaScript can also be assigned to variables or passed as arguments to other functions.

Here is an example:

let multiplyNumbers = function (num1, num2) {
return num1 * num2;
};

let result = multiplyNumbers(5, 10); // result is 50

Functions can also return multiple values using arrays or objects:

function getValues() {
return [1, 2, 3];
}

let [a, b, c] = getValues(); // a is 1, b is 2, c is 3

function getUser() {
return {
name: "John",
age: 30,
};
}

let {name, age} = getUser(); // name is 'John', age is 30

JavaScript Function Syntax

The syntax for declaring a JavaScript function is as follows:

function functionName(parameter1, parameter2, ...) {
// function body
// statements to be executed when the function is called
return value; // optional return statement
}

In this example:

  • The function keyword is used to declare a function.
  • functionName is the name of the function. It can contain letters, digits, underscores, and dollar signs. It must not start with a digit.
  • parameter1, parameter2, and so on are the parameters that the function accepts. They are optional. Multiple parameters are separated by commas.
  • The function body is enclosed in curly braces {}. It contains statements to be executed when the function is called.
  • The return keyword is used to return a value from the function. It is optional. If used, it must be followed by an expression or a value to be returned.

Example of a simple function that takes two parameters and returns their sum:

function addNumbers(a, b) {
return a + b;
}

This function can be called with two arguments like this:

let result = addNumbers(2, 3); // result = 5

Function Return

In JavaScript, a function can return a value using the return keyword. The returned value can be assigned to a variable or used in an expression.

An example of a function that returns the sum of two numbers:

function addNumbers(a, b) {
return a + b;
}

let result = addNumbers(2, 3); // result = 5

In this example:

  • The function addNumbers() returns the sum of its two parameters a and b.
  • The returned value is assigned to the variable result using the assignment operator =.

A function can also return an object, an array, or any other type of value.

As an example:

function createPerson(name, age) {
return {name: name, age: age};
}

let person = createPerson("John", 30); // person = {name: "John", age: 30}

In this example:

  • The function createPerson() returns an object with two properties name and age.
  • The returned object is assigned to the variable person.

If a function does not explicitly return a value using the return keyword, it returns undefined by default.

As an example:

function sayHello(name) {
console.log(`Hello, ${name}!`);
}

let result = sayHello("John"); // result = undefined

In this example:

  • The function sayHello() does not have a return statement, so it returns undefined by default.
  • The variable result is assigned the value undefined.

Why Functions?

Functions are an essential feature of JavaScript and other programming languages because they provide a way to group together a set of related instructions and execute them repeatedly. To understand the significance of functions, consider the following reasons:

Reusability

Functions allow you to write a block of code once and reuse it multiple times throughout your code. This can save a lot of time and effort.

Modularity

Functions help to make your code more modular and easier to understand by breaking it up into smaller, more manageable pieces.

Encapsulation

Functions provide a way to encapsulate your code, meaning that the details of how a particular operation is performed are hidden from the rest of the code. This can make your code more secure and easier to maintain.

Abstraction

Functions simplify complex operations by creating reusable code blocks. For instance, a function can perform a complicated mathematical calculation that can be used repeatedly in the code.

Testing

Functions make it easier to test your code because you can test each function individually and ensure that it works correctly before integrating it into the rest of your code.

Summary

Functions are crucial for efficient, modular, and reusable code. They break down the code into smaller, manageable pieces, improving Understanding and maintenance.

Arrow Function

Arrow functions, also known as fat arrow functions, are a shorthand syntax for writing functions in JavaScript.

They were introduced in ECMAScript 6 (ES6) and have since become a popular way to define functions in modern JavaScript code.

To define an arrow function, use this basic syntax:

(parameters) => {
// function body
};

Take a look at this example of an arrow function that adds two numbers:

let addNumbers = (a, b) => {
return a + b;
};

let result = addNumbers(2, 3); // result = 5

In this example:

  • The arrow function addNumbers takes two parameters a and b and returns their sum.

Unique Features of Arrow functions

Arrow functions have some unique features compared to regular functions, such as:

Concise syntax

Arrow functions have a shorter and more concise syntax compared to regular functions. They are especially useful for writing one-liner functions.

Implicit return

If the function body contains only a single expression, you can omit the curly braces {} and the return keyword. The result of the expression is automatically returned.

let square = (number) => number * number;

let result = square(5); // result = 25

In this example

  • The arrow function square takes a single parameter number and returns its square.
  • The curly braces and return keyword are omitted because the function body contains only a single expression.

Lexical this

Arrow functions do not have their own this keyword. Instead, they inherit the this keyword from the surrounding scope.

let person = {
name: "John",
sayHello: function () {
// this refers to the person object
console.log(`Hello, ${this.name}!`);
},
sayHelloArrow: () => {
// this refers to the global object (window)
console.log(`Hello, ${this.name}!`);
},
};

person.sayHello(); // prints "Hello, John!"
person.sayHelloArrow(); // prints "Hello, undefined!"

In this example

  • The sayHello method is a regular function that has its own this keyword, which refers to the person object.
  • The sayHelloArrow method is an arrow function that does not have its own this keyword, so it inherits the this keyword from the surrounding scope, which is the global object (window in a web browser).

Default Parameter in Function

Default parameters allow you to specify a default value for a function parameter in case no value or undefined is passed in.

This feature was introduced in ECMAScript 6 (ES6) and is supported in modern JavaScript environments.

Here's a function that demonstrates the use of default parameters:

function greet(name = "World") {
console.log(`Hello, ${name}!`);
}

greet(); // prints "Hello, World!"
greet("John"); // prints "Hello, John!"

In this example

  • The greet function has a single parameter name with a default value of "World".
  • If no argument is passed in when the function is called, the default value is used.
  • If an argument is passed in, that value is used instead.