Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to write a function in JavaScript ?
Next article icon

Pure Functions in JavaScript

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed.

  • Pure functions return consistent results for identical inputs.
  • They do not modify external states or depend on mutable data.
  • Often used with immutable data structures to ensure reliability.
  • Their independence from external states makes them highly reusable.
JavaScript
function add(a, b) {     return a + b; } console.log(add(2, 3));  console.log(add(2, 3));  

Output
5 5 
  • It always returns the same result for the same input.
  • It does not modify any external variables or state.

Note: Generally, we use the Pure function in JavaScript for any purpose.

Characteristics of Pure Functions

  • Deterministic Output: For a given set of inputs, the output is always the same.
  • No Side Effects: The function does not:
    • Modify variables outside its scope.
    • Interact with external systems like APIs, databases, or DOM manipulation.
    • Change mutable data.
  • Immutability: Pure functions do not change the input values; instead, they return a new value or object.

Example of a Function with Side Effects

Here, increment is not a pure function because it modifies the external variable count.

JavaScript
let c = 0;  function inc() {     c++;     return c; } console.log(inc()); console.log(inc()); 

Output
1 2 

Impure Functions: What to Avoid

Impure functions produce unpredictable results or affect external states, which can lead to bugs and make your code harder to test.

JavaScript
let user = { name: "Meeta", age: 25 };  function updated(newAge) {     user.age = newAge;     return user; }  console.log(updated(26));  // Alters the global `user` object console.log(user.age);  

Output
{ name: 'Meeta', age: 26 } 26 

Real-World Applications of Pure Functions

  • Data Transformation: Use pure functions in map, filter, and reduce operations for processing data.
  • State Management: Libraries like Redux emphasize pure functions for state updates.
  • Unit Testing: Pure functions are ideal for unit tests because they have predictable outputs.
  • Performance Optimization: Pure functions are easily memoized, as their outputs depend solely on inputs.

Next Article
How to write a function in JavaScript ?

G

geek5177
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-functions

Similar Reads

  • Functions in JavaScript
    Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output1
    5 min read
  • Arrow functions in JavaScript
    An arrow function is a shorter syntax for writing functions in JavaScript. Introduced in ES6, arrow functions allow for a more concise and readable code, especially in cases of small functions. Unlike regular functions, arrow functions don't have their own this, but instead, inherit it from the surr
    5 min read
  • JavaScript get Function
    JavaScript get function is used to access the properties of an object using dot notation or square brackets. It allows you to retrieve the value associated with a particular property key and the get function is often used when working with objects that implement JavaScript's getter function. The get
    3 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • Abstraction in JavaScript
    In JavaScript, Abstraction can be defined as the concept of hiding the inner complex workings of an object and exposing only the essential features to the user. Hiding Complexity: Implementation is hidden, it shows only the necessary details.Modularity: Code is organized in a reusable form, which im
    4 min read
  • All about Functions and Scopes in JavaScript
    In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to - understand different types of function declarations.make better use of functions.understand how different scopes and scope chain works in JS.learn about closures and
    10 min read
  • Why learn JavaScript Foundations ?
    JavaScript is like a cornerstone in the world of programming languages. It's famous for being adaptable and everywhere. No matter if you're into making websites, or mobile apps, or diving into server stuff, understanding the basics of JavaScript is super important. Let's talk about why it's so cruci
    4 min read
  • What is the inline function in JavaScript ?
    In JavaScript, an inline function is a special type of anonymous function that is assigned to a variable, or in other words, an anonymous function with a name. JavaScript does not support the traditional concept of inline functions like C or C++. Thus anonymous function and inline function is practi
    2 min read
  • Must use JavaScript Array Functions – Part 3
    Previous articles: Must use JavaScript Array Functions -Part 1 Must use JavaScript Array Functions -Part 2 In this article, we are going to discuss the following JavaScript array functions prototype.reduce()prototype.concat()prototype.sort()prototype.reverse() JavaScript Array.Prototype.reduce(): Ar
    5 min read
  • Integer Range in JavaScript
    In this article, we will know the different ranges of an integer variable in JavaScript. To get the ranges, we will use the MAX_VALUE and MIN_VALUE properties of ES5 JavaScript and the MAX_SAFE_INTEGER and MIN_SAFE_INTEGER properties of ES6 JavaScript. The MAX_VALUE represents the biggest possible n
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences