Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Object Get And Set in JavaScript

Object Get And Set in JavaScript

Object Getters and Setters in JavaScript


What Are Getters and Setters?

  • Getters: Special methods to access (get) the value of an object property.

  • Setters: Special methods to modify (set) the value of an object property.

  • They allow control over how properties are accessed or changed.


Syntax

Using Object Literal

const person = {  firstName: "John",  lastName: "Doe",    // Getter  get fullName() {    return this.firstName + " " + this.lastName;  },    // Setter  set fullName(name) {    const parts = name.split(" ");    this.firstName = parts[0];    this.lastName = parts[1];  }};console.log(person.fullName); // John Doeperson.fullName = "Jane Smith";console.log(person.firstName); // Janeconsole.log(person.lastName);  // Smith

Using Object.defineProperty

const person = {  firstName: "John",  lastName: "Doe"};Object.defineProperty(person, 'fullName', {  get: function() {    return this.firstName + " " + this.lastName;  },  set: function(name) {    const parts = name.split(" ");    this.firstName = parts[0];    this.lastName = parts[1];  }});console.log(person.fullName); // John Doeperson.fullName = "Jane Smith";console.log(person.firstName); // Janeconsole.log(person.lastName);  // Smith

Why Use Getters and Setters?

  • Encapsulation: Hide internal representation.

  • Validation: Validate data before setting.

  • Computed properties: Dynamically calculate property values.


Summary

FeaturePurposeExample Usage
GetterAccess property value via methodobj.prop calls getter
SetterModify property value with controlobj.prop = value calls setter

Want a demo with validation or computed values?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql