DEV Community

Cover image for Functions in JavaScript
Raghul
Raghul

Posted on • Edited on

Functions in JavaScript

Functions in JavaScript

Functions are one of the fundamental building blocks designed to perform specific tasks in JavaScript. They allow you to organize, reuse, and modularize code. They can take inputs, perform actions, and return outputs. In functions, parameters are placeholders defined in the function, while arguments are the actual values you pass when calling the function.
Uses of function
1.Code reusability
2.Modularity
3.Readability
4.Maintainaability

function greet(name) {   // 'name' is a parameter
  console.log("Hello " + name);
}

greet("Alice");  // "Alice" is the argument
Enter fullscreen mode Exit fullscreen mode

Return Statement
The return statement is used to send a result back from a function. When return executes, the function stops running at that point. The returned value can be stored in a variable or used directly.

function add(a, b) {
  return a + b; // returns the sum
}

let result = add(5, 10);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Type of Function
Here are the three main types of functions in JavaScript:

1. Named Function
A function that has its own name when declared. It’s easy to reuse and debug because the name shows up in error messages or stack traces.

function greet() {
  return "Hello!";
}
console.log(greet());
Enter fullscreen mode Exit fullscreen mode

2. Function Expression
A function expression is a function created as part of an expression and assigned to a variable or passed to another function. It can be named or anonymous.

const add = function(a, b) {
  return a + b;
};
console.log(add(2, 3));
Enter fullscreen mode Exit fullscreen mode

3. Arrow Function
A new way to write functions using the => syntax. They are shorter and do not have their own this binding, which makes them useful in some cases.

const square = n => n * n;
console.log(square(4));
Enter fullscreen mode Exit fullscreen mode

4. Constructor Function
A special type of function used to create multiple objects with the same structure. It’s called with the new keyword.

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

const user = new Person("Neha", 22);
console.log(user.name);
Enter fullscreen mode Exit fullscreen mode

5. Nested Functions
Functions defined within other functions are called nested functions. They have access to the variables of their parent function.

function outerFun(a) {
    function innerFun(b) {
        return a + b;
    }
    return innerFun;
}

const addTen = outerFun(10);
console.log(addTen(5));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)