DEV Community

G Gokul
G Gokul

Posted on

FUNCTIONS IN JAVASCRIPT

Functions:

  • Functions are one of the fundamental building blocks in JavaScript.
  • In JavaScript, a function is a reusable block of code designed to perform a specific task.
  • It can take inputs (parameters), process them, and optionally return an output.
  • Functions help in organizing code, improving reusability, and making programs modular.

How function works in js:

1. Function Declaration:

  • A function must be defined before it can be used.

2. Function Execution:

  • Creates a new execution context.
  • Passes arguments to parameters.
  • Executes the function body line by line.
  • Returns the result (or undefined if no return).

Why use functions:

usage

Understanding Functions:

function

In functions, parameters are placeholders defined in the function, while arguments are the actual values you pass when calling the function.

example:
function greet(name) {
console.log("Hello " + name);
}
greet("Alice");

output:
Hello Alice
Parameter: name (placeholder inside the function).
Argument: "Alice" (real value given at call time).

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.

example:
function add(a, b) {
return a + b; // returns the sum
}
let result = add(5, 10);
console.log(result);

output:
15

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.

example:
const add = function(a, b) {
return a + b;
};
console.log(add(2, 3));

output:
5

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.

example:
const square = n => n * n;
console.log(square(4));

output:
16

References:


Functions in JavaScript - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org

Top comments (0)