JavaScript Functions Explained : The Secret Sauce of Coding Efficiency


Ever wondered how JavaScript makes websites interactive? Whether it’s handling button clicks, fetching data, or creating animations — functions are at the heart of it all! Functions in JavaScript allow us to write clean, reusable, and efficient code. But what exactly are they, and how do they work? In this guide, we’ll break down JavaScript functions step by step, making them easy to understand — even if you’re just starting out!
Introduction to JavaScript Functions
What are functions in JavaScript?
In JavaScript, functions are pieces of code that can be reused to perform specific tasks when called. Let's take an example to understand this.
function greet() {
console.log("Hello viewer, Welcome to Himanshu-Sharma Blogs")
}
This is the greet()
function, which is used to print "Hello viewer, Welcome to Himanshu-Sharma Blogs."
Why use functions?
Imagine a scenario, where you have to write a code to add two numbers (number1 and number2). What will the code to write two numbers?
const number1 = 3;
const number2 = 4;
const sum = number1 + number2;
console.log(`The sum of ${number1} and ${number2} is ${sum}`)
// output : The sum of 3 and 4 is 7
This will be the code, right? Now imagine you have to write the code 50 or 100 times. Can you do it? Surely to can write the code again for like 4 or 5 times but you can’t write the code 50 or 100 times. To solve this problem, programmers introduce function. When you write one function (like for adding two numbers), you can use the same function 100 times or more without write the code many times.
function addTwoNumbers(number1, number2) {
const sum = number1 + number2
console.log(`The sum of ${number1} and ${number2} is ${sum}`)
}
This function can be used many times and for different numbers. Lets run this code.
addTwoNumbers(1,2) // output : The sum of 1 and 2 is 3
addTwoNumbers(1,4) // output : The sum of 1 and 4 is 5
addTwoNumbers(1,9) // output : The sum of 1 and 9 is 10
See how we can call the function many times with different numbers.
This is why we need functions. They make our code reusable, like in this example where we can use the addTwoNumbers
function as many times as we want. Functions also make our code more readable, so if someone else tries to read it, they can understand it easily. Additionally, functions make the code modular, meaning the code is organized into modules. This way, if a problem occurs in a function, we know exactly where to address it.
Declaring Functions
Function Declaration
We can declare a function using function
keyword, followed by
name of the function
a list of parameters separated by commas (,)
JavaScript statements enclosed in curly braces
{ //statements }
Syntax :
function functionName(parameter1, parameter2, ...) {
// statement1
// statement2
// statement3
}
Example :
function square(number) {
const result = number ** 2
console.log(result)
}
square(3) // output : 9
The square function takes one parameter number
. It calculates square of number (store it in result
) and print the result
.
Function Expression
Function Expression involve defining the function within an expression. The function expression can be assigned to a variable. The function expressions can be anonymous or named functions. Lets understand both.
Anonymous Function Expression
const square = function(number) {
const result = number ** 2
console.log(result)
}
This type of function is called anonymous because no name is given to function. You might be wondering but you have given the name square
. But this is not the name of the function, this is only the name of the variable.
The rest syntax is same for calling the function.
square(4) // output : 16
Named Function Expression
const greeting = function sayHello(Username) {
console.log(`Hello ${Username}`)
}
This is Named Function Expression. We have function sayHello()
which prints “Hello Username“.
The syntax to call is same as before.
greeting("Sunil") // output : Hello Sunil
Why use Function Expression?
Function Expression are convenient when we want to pass the function as an argument to another function. Lets take an example to better understand this
const num = [1,2,3,4,5]
const callbackfn = function(element) {
return element ** 2
}
const squaredNum = num.map(callbackfn)
console.log(squaredNum)
// output : [1,4,9,16,25]
In this map()
method of array, we passed a function callbackfn
as an argument.
Arrow Function
Arrow functions provide smaller syntax for writing functions. This function is introduced in ES6.
Syntax :
() => // statement
In this, no function
keyword and curly braces are used. Here, ()
takes parameters and by using =>
symbol, arrow function automatically assumes that you want to return the value.
Example :
Lets take an example to understand this,
const sum = (num1, num2) => num1 + num2
console.log(sum(5,5)) // output : 10
In this code, sum
variable saves the function which takes two parameters num1
and num2
and returns num1 + num2
.
Lets take another example, you might be familiar with.
const num = [1,2,3,4,5,6]
console.log( num.filter( (element) => element % 2 === 0 ) )
// output : [2, 4, 6]
In this code, we used filter()
method of array which takes an element as an argument and return a array of even numbers.
Function Parameters
There are two special kinds of parameters syntax : default parameters and rest parameters.
Default parameters
Default function parameters allow named parameters to be initialized with the default values if no value or undefined is passed. Lets understand this with example
function greeting(username) {
console.log(`Hello ${username}, Welcome!`)
}
When we pass any value of username as an argument then it will print it. But what if you didn’t pass the value of username as an argument, what will it print.
greeting()
// output : Hello undefined, Welcome
You see how it print undefined
when we don’t give the value of username
.
To solve this, we can assign default values directly to function parameters. This way, if we forget to provide a value for a parameter, it will print something else instead of undefined
.
Lets take a look,
function greeting(username = "Viewer") {
console.log(`Hello ${username}, Welcome!`)
}
greeting()
// output : Hello Viewer, Welcome!
In this code, even when we didn't provide a value, it printed "Viewer
" instead of "undefined
" because we assigned "Viewer
" as the default value for the username parameter.
Rest Parameter
The rest parameter syntax allow a function to accept an indefinite number of arguments as an array. These are used when we have to pass many arguments, so that we don’t have to write all the parameters. This accepts the parameter as an array. Lets take an example,
function sum(...theArgs) {
let total = 0
for (const arg of theArgs) {
total += arg
}
return total
}
console.log(sum(1,2,3,4,5,6))
// output : 21
In this code, we take the parameter …theArgs
, which acts as an array.
Remember: The
...theArgs
can only be used once in a function because it represents all the parameters. Therefore, it doesn't make sense to use...theArgs
twice.
Return Statement and Function Output
When working with JavaScript functions, understanding how values are returned and how outputs are displayed is crucial. Many beginners confuse return
with console.log
, but they serve different purposes. Lets understand it.
What is the return
Statement?
The return
statement in JavaScript is used to send a value back to the function caller. When a function executes a return
statement, the function immediately stops execution and provides the specified value as the result.
Syntax :
function functionName() {
return value
}
Example :
function add(num1, num2) {
return num1 + num2
}
const result = add(2,3)
console.log(result) // output : 5
💡 If a function does not have a return
statement, it returns undefined
by default.
function greet(name) {
console.log("Hello, " + name);
}
let message = greet("John");
console.log(message);
// Output: Hello, John
// Output: undefined (because no return statement)
Difference between return
and console.log
Feature | return | console.log |
Purpose | Sends a value back to the caller | Displays output in the console |
Stops Execution? | Yes, it exists the function | No, execution continues |
Stores Value? | Yes, it can be stored in variables | No, it only prints to console |
Used in Expressions? | Yes, its value can be used later | No, it just logs data |
Why is return
More useful?
Using return
is essential when you need to:
✅ Use the function’s result later (e.g., in another function).
✅ Store the result in a variable for further calculations.
✅ Perform operations on the returned value.
For example, let’s say you have a function that calculates the square of a number :
function square(num) {
return num * num;
}
let x = square(3) + square(4); // 9 + 16 = 25
console.log(x); // Output: 25
🔹 Here, the returned values (9
and 16
) are used in an arithmetic expression.
Closures in JavaScript
What is a Closure?
A closure in JavaScript is when a function remembers the variables from its outer function, even after the outer function has finished running.
In simple terms :
A function inside another function can still use the variables of the outer function, even when the outer function is no longer active.
Real Life Analogy
Think of a bank locker where :
The main function is the back
The inner function is you, the account holder
The locker key (variables) belongs to the account holder (inner function)
Even if the bank closes for the day (outer function ends), you still have the key and can access your locker (variable inside the closure).
Example
function outerFunction() {
let outerVariable = "I am from outer"
function innerFunction() {
console.log(outerVariable) // can access the outerVariable
}
return innerFunction()
}
const myClosure = outerFunction()
myClosure() // output : I am from outer
Here, innerFunction
remembers outerVariable
, even though outerFunction
has finished running.
Best Practices for Writing JavaScript Functions
Writing clean and efficient JavaScript functions makes your code easier to understand, maintain, and debug. Here are the some the best practices to follow when working with functions in JavaScript.
Use Meaningful and Descriptive Function Names
✔ Function names should describe what they do.
✔ Use camelCase for naming functions.
❌ Bad Example:
function doSomething(a,b) {
return a * b
}
✅ Good Example:
function multiplyNumbers(num1, num2) {
return num1 * num2
}
Keep function Small and Focused
✔ A function should do one thing only and do it well.
✔ If a function is doing too much, break it into smaller functions.
❌ Bad Example (Too much in one function):
function processUser(name, age, email) {
console.log("Saving user to database")
console.log(`Nmae: ${name}, Age: ${age}, Email: ${email}`)
}
✅ Good Example (Separate Responsibilities):
function saveUserToDatabase(user) {
console.log("Saving user to database...");
}
function displayUserDetails(user) {
console.log(`Name: ${user.name}, Age: ${user.age}, Email: ${user.email}`);
}
Always use return
When a Function Needs to Provide a Value
✔ If a function performs a calculation, always use return
to send back the result.
❌ Bad Example (No return, just logs the value):
jsCopy codefunction add(a, b) {
console.log(a + b);
}
let result = add(5, 3); // result is undefined
✅ Good Example (Returns the value so it can be used later):
jsCopy codefunction add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
Avoid Modifying Global Variables Inside Functions
✔ Functions should only use local variables or explicitly passed parameters.
✔ Changing global variables can lead to unexpected behavior in other parts of the code.
❌ Bad Example (Modifying a global variable inside a function):
jsCopy codelet count = 0;
function increment() {
count++; // Changes the global variable
}
increment();
console.log(count); // Output: 1 (May cause problems in large projects)
✅ Good Example (Using local variables or returning values):
jsCopy codefunction increment(count) {
return count + 1;
}
let newCount = increment(0);
console.log(newCount); // Output: 1
Conclusion
JavaScript functions are a fundamental aspect of coding that enhance efficiency, readability, and modularity. By understanding how to declare, use, and optimize functions, developers can create clean and reusable code. Functions allow for the encapsulation of tasks, making it easier to manage and debug code. With the introduction of features like arrow functions, default parameters, and closures, JavaScript continues to evolve, offering more powerful tools for developers. By adhering to best practices, such as using meaningful names and keeping functions focused, programmers can ensure their code is both effective and maintainable. Embracing these concepts will undoubtedly lead to more robust and scalable web applications.
To read more about functions. Visit : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Subscribe to my newsletter
Read articles from himanshu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
