JavaScript get / set

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

Use get name() and set name(v) to run code when a property is read or written, while callers still use normal property syntax.

JavaScript Syntax

JavaScript
class Temp {
  constructor(c) { this._c = c; }
  get f() { return this._c * 1.8 + 32; }
}
console.log(new Temp(0).f);
Try it Editor

How It Works

  1. Read .f. Getter computes Fahrenheit.
  2. No parentheses. Looks like a field.

Examples

Example 1 — Setter

Validate on write.

JavaScript
class T { set n(v){ if (v < 0) throw new Error("neg"); this._n = v; } get n(){ return this._n; } }
const t = new T(); t.n = 3; console.log(t.n);
Try it Editor

How It Works

  1. Setter stores _n.

Example 2 — On the prototype

Defined once for all instances.

JavaScript
class A { get ok(){ return true; } }
console.log(new A().ok);
Try it Editor

How It Works

  1. Getter shared via prototype.

Example 3 — Also on object literals

Same get/set keywords.

JavaScript
const o = { get x(){ return 1; } }; console.log(o.x);
Try it Editor

How It Works

  1. Works outside classes too.

Frequently Asked Questions

They run code on each read—avoid heavy work in hot paths.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful