Edit Template
Edit Template

JavaScript Functions

In JavaScript, functions are reusable blocks of code designed to perform specific tasks. Think of them as small machines: you give them some input, and they return a result after processing it.

Functions allow us to avoid repeating code and to organize logic in a cleaner, more efficient way.

What Is a Function?

A function is defined once, and it can be called (used) whenever needed.

				
					function greet(name) {
  return "Hello, " + name + "!";
}

				
			

Why Use Functions?

  • To avoid repeating code

  • To organize logic into meaningful pieces

  • To make code easier to test, read, and reuse

  • To pass blocks of logic around like values (functions are first-class citizens)

Function Structure

				
					function functionName(parameters) {
  // your code goes here
  return result;
}

				
			
  • functionName: what you want to call it

  • parameters: input values (optional)

  • return: sends back the result

Example: A Simple Calculator
				
					function add(a, b) {
  return a + b;
}

let result = add(4, 6); // 10

				
			

You can pass any values to it—numbers, strings, even other functions!

Arrow Functions (Shorter Syntax)

Arrow functions are often used when the function is small and simple.

				
					const multiply = (x, y) => x * y;

console.log(multiply(3, 7)); // 21

				
			

If there’s just one parameter, you can skip the parentheses:

				
					const greet = name => "Hi " + name;

				
			

Function Inside Function (Nested)

You can even define functions inside other functions:

				
					function outer(num) {
  function double(x) {
    return x * 2;
  }
  return double(num) + 5;
}

console.log(outer(4)); // 13


				
			

Nested functions help in scoping and organizing logic that’s only needed inside the parent function.

Functions Are First-Class in JavaScript

In JavaScript, functions can:

  • Be assigned to variables

  • Be passed as arguments to other functions

  • Be returned from other functions

This makes JavaScript powerful for writing flexible and reusable code (especially in libraries and frameworks like React).

Wrap-up

Functions are a core concept in JavaScript. Whether you’re creating a calculator, form validator, or an entire app, you’ll use functions every step of the way.

Scroll to Top