What Are Functions in JavaScript? A Complete Guide for Beginners

0

 

what are javascript functions

Ever clicked a button on a website and watched something instantly happen? Or filled out a form and marveled as the page responded in seconds? Behind those smooth interactions is the invisible hand of JavaScript. And at the core of JavaScript’s power is something called functions.


Think of functions as tiny workshops within your code — you hand them materials (inputs), they get to work behind the scenes, and return a finished product (an output) when they're done. Whether you're building a calculator, processing what users type, or simply organizing your code into tidy, reusable pieces, functions are the reliable craftspeople that keep your programs running smoothly.


In this guide, we’re going to break functions down step by step. You’ll learn what functions are, why they’re useful, and how to create and use them — all in a clear, beginner-friendly way. No prior experience needed — just your curiosity and a little bit of practice.



📋 Table of Contents

  • What is a Function in JavaScript?
  • How Do Functions Work in JavaScript?
  • How to Write a Function in JavaScript
  • Calling Functions
  • Types of Functions in JavaScript
  • How to nest a Function
  • Conclusion & Recap



What is a Function in JavaScript?

A function in JavaScript is a block of code that performs a specific task — but it’s much more powerful than just that.
Think of it as a named set of instructions that you can store once and run whenever you like, as many times as you want.


Why do we need functions?

Without functions, every time you wanted to do the same task — like showing a message, calculating a total, or validating a form — you’d have to rewrite the same code again and again.
Functions save you from repeating yourself (a core programming idea called DRY: Don't Repeat Yourself). They help make your code:

  • Reusable — write once, use many times
  • Organized — split big problems into smaller, manageable pieces
  • Clear — give meaningful names to chunks of logic, so your code is easier to understand

Let’s look at a simple function:


function sayHello() { console.log('Hello, world!'); }


Let’s break this down:

  • function → This is the keyword that tells JavaScript you’re defining a function.
  • sayHello → This is the name of the function. You’ll use this name later to run (or "call") the function.
  • () → These parentheses can hold parameters (more on that soon), but here they’re empty.
  • { ... } → These curly braces contain the body of the function — the code that runs when the function is called.
  • console.log('Hello, world!'); → This is the task the function does: it prints "Hello, world!" to the console.

 

  



How Do Functions Work in JavaScript?

Let’s break it down step by step so you really understand what happens when you call a function.


Step-by-step: What really happens?

1) Your program starts running
JavaScript begins at the top of your code and runs everything line by line.

2) You call a function
When it sees something like sayHello();, JavaScript says:

“Okay, let’s pause here and jump into that function to run its code.”

3)  JavaScript remembers where it left off
Before jumping into the function, JavaScript leaves a “bookmark” so it knows where to return later.

4)  The function code runs
Now JavaScript goes inside the function and:

  • Sets up any inputs (parameters) you gave it
  • Runs each line of code inside the function from top to bottom

Example:


function greet(name) { let message = 'Hello, ' + name + '!'; console.log(message); } greet('Alok'); // prints "Hello, Alok!"


5) The function finishes
Once it’s done (or hits a return), JavaScript:

  • Closes the function
  • Goes back to where it left off in your main code
  • If you used return, the result goes back with it

6) Your program keeps going
Now JavaScript picks up where it paused and continues running the rest of your program.

 

   



What is a Function Parameter?

When you create a function, you can think of parameters as empty boxes inside the function, waiting to be filled with something when the function is called.
In other words, parameters are like placeholders that tell the function:

"Hey, I need something from you to get started."

Let’s look at an example to make this clearer:


function greet(name) { // "name" is the parameter console.log('Hello ' + name); // name is used inside the function } greet('Alok'); // "Alok" is the argument (the value we pass to the function)


Here’s what’s happening:

  • name is the parameter — it's the placeholder inside the function, waiting for something to be put into it.
  • 'Alok' is the argument — it's the actual value we give to the function when we call it.

So, when we run greet('Alok');, JavaScript says:

"Alright, I see 'Alok'. Let’s put that in the name parameter, and run the code inside the function."



Do Functions Always Need Parameters?

Nope!
You don’t always need parameters. Sometimes your function may just need to do something simple, and it doesn’t need any extra information.

Example:

  • No parameters:

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

This function doesn’t need anything — it just says "Hi!".


  • One parameter:


function greet(name) { console.log('Hello ' + name); }

This one needs one name to greet.


  • Two parameters:


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

This one needs two numbers to add together.

 



How to Write a Function in JavaScript?

Writing a function in JavaScript is simple and one of the core building blocks for writing clean, reusable code. Let’s break it down step by step, so you can understand the essentials and get comfortable creating functions yourself.


Two Ways to Write Functions in JavaScript

In JavaScript, you can write functions in two common ways: Function Declarations and Function Expressions. Both methods serve the same purpose, but there are some differences in how they work.

1. Function Declaration

A function declaration is the classic way to create a function. Here's how you write one:


function myFunction() { console.log('This is a function declaration'); }


In this example:

  • function is the keyword that tells JavaScript you're defining a function.
  • myFunction is the name of your function.
  • The code inside the curly braces {} is the task the function will perform.

2. Function Expression

A function expression is another way to define a function. In this case, the function is often assigned to a variable:


const myFunction = function() { console.log('This is a function expression'); };


In this example:

  • We’re assigning the function to the variable myFunction.
  • The syntax is a little different, but it works just like a function declaration.


Key Difference Between the Two


Function Declarations are hoisted. This means that JavaScript can "see" and use them even before they are written in the code. For example, you can call a function before it's defined in the code.

Example:


greet(); // This will work because function declarations are hoisted function greet() { console.log('Hello!'); }



Function Expressions, however, are not hoisted. You can only call them after they are defined in the code. This means the function won’t be available until JavaScript reaches that line of code.

Example:


myFunction(); // This will throw an error because it's not hoisted const myFunction = function() { console.log('This is a function expression'); };



How to name Functions in Javascript?

When it comes to naming your functions, it’s important to follow some best practices to keep your code clean and readable. Here's what you should keep in mind:


Be Descriptive:
Choose a function name that clearly describes what the function does. For example:
  1. getUserName()
  2. calculateSum()
Use CamelCase: 
This is the standard convention in JavaScript. The first word starts with a lowercase letter, and each subsequent word begins with a capital letter. For example:
  1. getUserInfo()
  2. processData()
Avoid Using Capital Letters for the First Word: 
This is considered bad practice in JavaScript and can lead to confusion. Stick to lowercase for the first word.
  1.  GetUsername() (not recommended)
  2.  getUsername() (good practice)


Why Follow These Rules?

  • Descriptive names make your code easier to understand.
  • CamelCase is the JavaScript convention, making your code consistent with the broader JavaScript community.
  • Good naming conventions help other developers (and your future self) easily figure out what your functions do without needing to dig into the code.

 



How to Call a Function in JavaScript?

In JavaScript, calling a function is a fundamental operation. To invoke a function, you simply use the function name followed by parentheses ().

When you define a function, you're essentially creating a block of reusable code. Calling the function executes that code.

Example:


function greet() { console.log('Hello!'); } greet(); // Calls the greet function and prints "Hello!"


What Happens When You Call a Function?

  • JavaScript looks for the function by its name.
  • It jumps to the function's block of code, runs the code inside, and completes the task.
  • It returns to the point where the function was called and continues with the rest of the program.

Even if the function doesn't take any input (no parameters), the parentheses are still necessary. They represent the action of invoking the function.



Can Functions Call Other Functions?

Absolutely! Functions can call other functions. This is not just allowed, but encouraged in real-world JavaScript code. The ability for functions to call each other allows for better code organization and reuse, which leads to cleaner, more efficient programs.

When one function calls another, it's often referred to as function composition. This technique involves breaking down larger tasks into smaller, focused tasks and combining them to achieve the final result.

Example of Function Composition:


function greet(name) { console.log('Hello ' + name); } function welcome() { greet('Alok'); // Calls the greet function inside welcome } welcome(); // Prints "Hello Alok"



Explanation:

  • greet(name) is a simple function that prints a greeting.
  • welcome() is another function that calls greet('Alok') inside it. This means welcome() will first invoke greet() with the argument 'Alok' and then print "Hello Alok" to the console.
  • The welcome() function is calling another function (greet()), which is a basic example of function composition.

 

Why Should Functions Call Other Functions?

  1. Modular Code: Functions that call other functions help break your program into smaller, manageable chunks. Each function can be responsible for a specific task.
  2. Reusability: Once you've defined a function, you can call it multiple times throughout your program. This avoids repeating code and makes the program more efficient.
  3. Better Organization: Functions that are responsible for specific actions (like greet()) can be combined in a sequence (like welcome()), keeping your code clean and organized.

Advanced Example of Calling Multiple Functions:


function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } function calculate() { let sum = add(2, 3); // Calls add function to get the sum let product = multiply(4, 5); // Calls multiply function to get the product console.log("Sum:", sum); console.log("Product:", product); } calculate(); // This will call add() and multiply() within the calculate function


In this example:

  • The calculate() function calls both add() and multiply() to perform different tasks.
  • The results of these function calls are then logged to the console.

 

 


 

Types of Functions in JavaScript ?

Not all functions in JavaScript are the same. In fact, JavaScript gives us multiple ways to define and use functions, each with its own purpose and behavior.

now, we’ll break down the most important types of functions in JavaScript, along with when and why you should use them.

  • Named Function
  •  Function Expression
  • Arrow Function
  • Anonymous Functions
  • callback function
  • constructor function
  • Immediately Invoked Function Expression (IIFE)
  • Generator Function


1) what is Named function?

A named function is a function that has a name. You can use that name to run (or call) the function whenever you want.


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


Key Features:

  • Named — It has a clear name (add) which helps with readability and debugging.
  • Hoisted — You can call this function before its definition in your code. JavaScript automatically moves it to the top during the compilation phase.


console.log(add(2, 3)); // Works even before the function is written function add(a, b) { return a + b; }


When to use:

 When you want a reusable function with a clear purpose
 When readability and hoisting matter


2️)  What is Function Expression?

A function expression is when you create a function and assign it to a variable. The function can be named or anonymous, but most commonly it’s anonymous.


const sayHi = function(name) { console.log('Hi ' + name); };


Key Features:

  • Can be anonymous (no name) or named (optional).
  • Not hoisted — You must define it before calling.


sayHi('Alok'); // Works here const sayHi = function(name) { ... }; sayHi('Alok'); // Won’t work if called before definition


When to use:

 When you need a function as a value (to pass around or assign)
 When hoisting isnt necessary


3) what is Arrow function?

An arrow function is a shorter way to write a function in JavaScript.
It uses => (called "arrow") instead of the word function.
It was introduced in ES6 (2015).


const add = (a, b) => a + b;


Key Features:

  • No this binding — It inherits this from its surrounding scope (lexical scope).
  • Great for small, one-liner functions.
  • Cannot be used as constructor functions.


const greet = name => console.log(`Hello ${name}`); greet('Alok');


When to use:

 When writing short, concise functions
 When you dont need your own this (like in event listeners or callbacks)

 Avoid using arrow functions when you need to work with this, like in object methods or constructors.


4️) what is Anonymous Function?

An anonymous function is a function without a nameIt’s usually used inside a function expression or as a callback.


setTimeout(function() { console.log('Hello after 1 second'); }, 1000);


Key Features:

  • Typically used when a function won’t be reused.
  • Less readable in long code if overused.

When to use:

 For short, one-off tasks (like callbacks)
 When you dont need to reuse the function elsewhere


5️) What is Callback Functions?

A callback is a function passed as an argument to another function. That function then calls (or "calls back") the passed function.


function processUserInput(callback) { const name = 'Alok'; callback(name); } processUserInput(function(name) { console.log('Hello ' + name); });


Key Features:

  • Used heavily in asynchronous code and event handling.
  • Helps in function composition and modular code.

When to use:

 When passing logic into another function (like .map(), .forEach(), etc.)
 For event listeners, API calls, and promises


6️) What is Constructor Functions?

A constructor function is a special type of function in JavaScript that is used to create and initialize objects.
You can think of it like a template or blueprint for making many objects that have the same properties and methods.

Instead of writing the same object structure again and again, you just create a constructor function once and use it to make many similar objects.


function Person(name, age) { this.name = name; this.age = age; } const user1 = new Person('Alok', 25);


Key Features:

  • Used with the new keyword.
  • The this keyword refers to the new object being created.

When to use:

 When building multiple similar objects
 When you want to create custom data structures


7️) What is Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that is defined and run immediately after it is created. It’s typically used to create a local scope so that variables inside the function don’t leak into the global scope.


(function() { console.log('This runs right away!'); })();


Key Features:

  • Runs once and is done.
  • Creates a private scope to avoid polluting global variables (was very useful before let/const and modules).

When to use:

For initialization code

To create private variables


8) what is Generator Functions?

A generator function is a special kind of function that can pause its execution at any point using the yield keyword and resume it later.
It allows you to generate a sequence of values on the fly, without having to return them all at once.


function* generatorFunc() { yield 1; yield 2; yield 3; } const gen = generatorFunc(); console.log(gen.next()); // { value: 1, done: false }


Key Features:

  • Can yield multiple values over time.
  • Great for iterators, lazy evaluation, and asynchronous workflows.

When to use:

 When working with streams of data
 When building custom iterators or handling complex asynchronous flows


 


 

How to Nest Functions in JavaScript?

In JavaScript, you can easily nest functions, meaning you can define a function inside another function. This allows you to organize your code better and limit the scope of certain functions to just where they're needed.

Example of Nesting Functions:


function outer() { function inner() { console.log('I am inside'); } inner(); // Calling the inner function from the outer function } outer(); // This will call outer() and, in turn, call inner() inside it


Explanation:

  • Outer Function: The outer() function is the main function that you call.
  • Inner Function: The inner() function is defined inside the outer() function. This makes inner() only accessible within the outer() function.
  • When outer() is called, it also calls the inner() function, which prints "I am inside" to the console.


Why Nest Functions?

Encapsulation: By nesting a function inside another, you make it private to the outer function. This means the inner function can only be accessed and used within the outer function, helping to keep your code organized and preventing unnecessary exposure.

Cleaner Code: Nesting functions allows you to break tasks down into smaller pieces that are only relevant in the context of the outer function. This helps avoid cluttering the global scope with too many unnecessary functions.

Example with Parameters and Return Values:


function outer(a, b) { function inner(x, y) { return x + y; } let result = inner(a, b); // Calls inner() with a and b as arguments console.log(result); // Logs the result of inner() to the console } outer(5, 3); // This will print 8


In this example, outer() takes parameters a and b. The inner function, inner(), is called with a and b, and the sum is logged to the console.


Key Points:

  • Nesting functions is a great way to structure your code in JavaScript.
  • Inner functions are only accessible within the outer function, helping to keep the code organized.
  • This method allows for cleaner, more modular code, especially when certain tasks are only relevant in a specific scope.




Conclusion & Recap

Functions in JavaScript are essential building blocks. Once you learn how to write them, call them, and choose the right type — your code will be cleaner, easier to read, and more powerful.

Quick recap:

  • Functions = reusable blocks of code
  • They may (or may not) take parameters
  • Learn regular, arrow, callback, and constructor functions
  • You can nest functions
  • Function overloading isnt natively supported, but you can work around it


 

Tags

Post a Comment

0 Comments
Post a Comment (0)
To Top