Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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:
Getters and Setters in Scala
Next article icon

JavaScript Getters and Setters

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, getter and setter are the special methods introduced in ECMAScript 5 (ES5 2009) that allow us to retrieve and modify the values directly without directly changing the object property. The getter uses the get keyword and the setter uses the set keyword to modify and retrieve the values.

JavaScript Getter (The get Keyword)

In JavaScript, the getter is the method that is used to get the value of the property. We can use the get keyword to get the value of the property.

  • Getters are automatically called when the property is accessed.
  • Getters help us in getting the value of the property.
JavaScript
class P {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }
}

const res = new P('Anjali');
console.log(res.name);

Output
Anjali

In this example

  • The Person class has a constructor that sets the _name property
  • get method used to retrieve the value of _name when a name is accessed.
  • When person.name is accessed, the getter name is automatically called, returning the value of _name.

Getter vs Regular Function

In JavaScript, the getter and the regular functions both are used for the accessing the object properties but in the different ways. Getters allow properties to be accessed like regular object attributes while still executing logic in the background. On the other hand, regular functions require explicit method calls and do not provide direct property-like access.

Feature

Getter (get)

Regular Function

Syntax

Accessed like a property (obj.prop)

Called explicitly (obj.method())

Readability

Improves readability & simplicity

equires () which makes it look like a method call

Encapsulation

Can restrict direct access to properties

Properties can be easily accessed

JavaScript Setter (The set Keyword)

In JavaScript, the setter is the method that is used for setting the value of the property with the help of the set keyword.

  • The setter allows us to set the value of the object in a controlled way.
  • Setters provide a way to control how data is stored by using internal variables, keeping the object's state secure.
JavaScript
class P {
    constructor(name) {
        this._name = name;
    }

    set name(newName) {
        this._name = newName;
    }
}

const res = new P('Anjali');
res.name = 'Ayushi'; // Using the setter to change the name
console.log(res._name); // Output: Ayushi

Output
Ayushi

In this example

  • The setter name is used to update the _name property when res.name = 'Ayushi' is called.
  • The value of _name is updated to 'Ayushi'.

Implementing Getters and Setters in JavaScript

Using Getters and Setters in Objects

In objects, we can use the get and set keywords for defining the getter and setter in objects.

JavaScript
const p= {
    n1: "Anurag",
    n2: "Das",
    get Name() {
        return `${this.n1} ${this.n2}`;
    },
    set Name(name) {
        [this.n1, this.n2] = name.split(" ");
    }
};

console.log(p.Name);
p.Name = "Anuj Jain";
console.log(p.Name); 

Output
Anurag Das
Anuj Jain

Getters and Setters with Classes

Getters and setters are commonly used in ES6 classes to control access to private properties.

JavaScript
class R {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    get a() {
        return this.width * this.height;
    }

    set a(value) {
        console.log("Area cannot be set directly.");
    }
}

const rect = new R(10, 5);
console.log(rect.a);
rect.a = 60; 

Output
50
Area cannot be set directly.

The getter computes the area dynamically, and the setter prevents modification, enforcing encapsulation.

Using Getters and Setters with Private Fields

With ES2020, JavaScript introduced private fields (prefix _ is just a convention; # makes it truly private).

JavaScript
class B {
    #balance; // Private property

    constructor(balance) {
        this.#balance = balance;
    }

    get balance() {
        return this.#balance;
    }

    set balance(amount) {
        if (amount < 0) {
            console.log("Balance cannot be negative!");
        } else {
            this.#balance = amount;
        }
    }
}

const acc = new B(1000);
console.log(acc.balance);
acc.balance = -500;  // "Balance cannot be negative!"

Output
1000
Balance cannot be negative!

The #balance field is private, ensuring external code cannot modify it directly.

Using Object.defineProperty() for Accessors

The Object.defineProperty() method can define getters and setters dynamically.

JavaScript
const u = { name: "Anjali" };

Object.defineProperty(u, "greeting", {
    get: function () {
        return `Hello, ${this.name}!`;
    },
    set: function (newName) {
        this.name = newName;
    }
});

console.log(u.greeting);
u.greeting = "Ayushi";
console.log(u.greeting);

Output
Hello, Anjali!
Hello, Ayushi!

This approach allows defining dynamic properties with controlled access.

Use Cases of Getters and Setters

  • Data Validation: Ensures only valid data is assigned to a variable, preventing errors.
  • Lazy Computation: Delays the calculation of a value until it's actually needed, improving efficiency.
  • Encapsulation: Hides direct access to sensitive data, allowing controlled modifications through methods.
  • Debugging & Logging: Helps track when and how a variable changes, making it easier to find bugs.

When to Use Getters and Setters?

When you need to validate input before assigning a value.

set age(value) {
    if (value < 0) throw new Error("Age cannot be negative!");
    this._age = value;
}

When properties depend on other properties (computed properties).

get fullName() {  
    return `${this.firstName} ${this.lastName}`;
}

When working with private fields in classes.

class Person {
    #secret = "Hidden Data";
    get secret() {
        return "Access Denied";
    }
}

When debugging changes in properties.

set value(newValue) {
    console.log(`Value changed to: ${newValue}`);
    this._value = newValue;
}

Getters and Setters vs. Direct Property Access

Feature

Getters & Setters

Direct Property Access

Definition

Special methods used to control the access and modification of object properties.

Directly assigning and retrieving values from an object's properties without any additional control.

Use Cases

Used when validation, computed properties, encapsulation, or logging is required.

Used for simple data storage where additional logic is not needed.

Performance

Slightly slower due to method calls.

Faster since it directly accesses properties.

Encapsulation

Provides encapsulation by restricting direct access to internal data.

No encapsulation; data can be freely modified.

Simplicity

More complex as it requires defining getter/setter methods.

Easier to use since properties can be accessed directly.


Next Article
Getters and Setters in Scala

N

nishth7hs8
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-object

Similar Reads

    JavaScript Object Accessors
    There are two keywords that define the accessors functions: a getter and a setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set. JavaScript Getter (The get Keyword)Exampl
    2 min read
    How to use getters/setters in TypeScript ?
    In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
    5 min read
    TypeScript Accessor
    TypeScript accessors, through get and set methods, offer controlled access to object properties, enhancing encapsulation, validation, and custom logic. By using accessors, you can manage how properties are accessed and modified, supporting a more robust object-oriented design in your classes.Getters
    3 min read
    Getter and Setter in Java
    In Java, Getter and Setter are methods used to protect your data and make your code more secure. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. Getter in Java: Getter returns the value (accessors), it returns the value of data type int,
    3 min read
    Getters and Setters in Scala
    Getter and Setter in Scala are methods that helps us to get the value of variables and instantiate variables of class/trait respectively. Scala generates a class for the JVM with a private variable field and getter and setter methods. In Scala, the getters and setters are not named getXxx and setXxx
    4 min read
    Advantages of getter and setter Over Public Fields in Java with Examples
    Providing getter and setter methods to access any class field in Java can at first look pointless and meaningless, simply because you can make the field public, and it is available in Java programs from anywhere. In reality, many programmers do this in the early days, but once you start thinking in
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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
  • DSA Tutorial
  • 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