Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand.

const symbol = Symbol.for('symbolname');

class Something { 

    public get [symbol]() {
        return true;
    }
...
}

I am confused about how the get function works in this context. Is symbol being used as an argument here?

Answer №1

Unique Identifier

As per information provided by Mozilla Developer Network

Each call to Symbol() guarantees the return of a distinct Symbol. On the other hand, calling Symbol.for("key") will consistently return the same Symbol for a specific "key". When Symbol.for("key") is invoked, if an existing Symbol with the specified key exists in the global registry, that Symbol will be returned. Otherwise, a new Symbol is generated, added to the global registry under the given key, and then returned.

To put it simply, you can think of Symbol as similar to object[key] in Javascript.

Sometimes, we use keys in scenarios like this

const key = "keyname"
const object = {
   [key]: "value"
}

We can now switch to using symbols instead

const symbol = Symbol.for('symbolname');
const object = {
   [symbol]: "value" //the key is represented by a symbol
}

Additionally, one notable advantage of utilizing Symbols is that

Symbols used as keys will not be included when JSON.stringify() is employed:

This proves helpful when serializing JSON data while excluding specific fields within your code.

If you wish to delve deeper into some features of Symbols, I recommend reading this article

Getter Function (also known as get)

Referencing once again the details from Mozilla Developer Network

The get syntax links an object property to a function that is triggered whenever that property is accessed.

But why would we require this functionality?

To illustrate, consider one of my favorite examples

class Person {
    public firstName: string;
    public lastName: string;
    public fullName: string; //imagine assigning a value for `fullName` like this `${firstName} ${lastName}`?
}

The assignment of fullName could become repetitive despite setting values for both firstName and lastName

To address this issue, we introduce a getter function

class Person {
    public firstName: string;
    public lastName: string;
    
    //introducing the getter!
    public get fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}

Following this modification, you only need to assign values to firstName and lastName. Accessing person.fullName will automatically populate the full name!

The question arises, "Can getters be used with Symbols?" The answer is affirmative!

By referring to the preceding documentation on getters, you'll come across this segment

const expr = 'foo';

const obj = {
  get [expr]() { return 'bar'; }
};

console.log(obj.foo); // "bar"

In Conclusion

In response to your query

const symbol = Symbol.for('symbolname');

class Something { 

    public get [symbol]() {
        return true;
    }
}

This approach seems geared towards avoiding unintended data inclusion during JSON serialization via that getter function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Jquery Regex to Validate Numeric Range Input on KeyUp Event in an Input Field

I have been spending quite a few hours attempting to figure out a solution for this issue, but unfortunately, I haven't had much success. My goal is to add a Keyup/KeyPress event that only allows values between 2 and 1827. I am using an aspx inputbox ...

Providing static content within the generated code structure by Yeoman for the Angular Fullstack framework

I'm sticking to the code structure generated by Yeoman for an Angular fullstack application. The issue I'm facing is how to include a script called core.js in a file named app.html. <script src="core.js"></script> I can't fi ...

Passing a JavaScript variable to PHP resulted in the output being displayed as "Array"

After sending a JavaScript variable with the innerHTML "Basic" to PHP via Ajax and then sending an email with that variable, I received "Array" instead of "Basic". This situation has left me puzzled. HTML: <label class="plan-name">Plan name: <b ...

A demonstration of VueJS Nested Builder functionality

I am currently exploring VueJS and working on a project to create a simple page builder application that allows users to add sections and subsections. I am seeking guidance on how to properly set up the Vue data property for this functionality. Any advice ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

Next.js optimizes the page loading process by preloading every function on the page as soon as it loads, rather than waiting for them to

My functions are all loading onload three times instead of when they should be called. The most frustrating issue is with an onClick event of a button, where it is supposed to open a new page but instead opens multiple new pages in a loop. This creates a c ...

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

What causes objects to be added to an array even when the condition is not met?

In the process of creating a terminal game using node.js, I am developing a random field consisting of different elements such as hats, holes, and pathways. The player's objective is to navigate through the maze and locate their hat within the field. ...

The issue with Postman Express.js Response Body not displaying any content is quite common

I've been struggling with this issue for a whole day and I just can't seem to find a solution. My node app is extremely simple. const express = require("express"); const port = 3001; const app = express(); app.use(express.json()); app.pos ...

Tag in HTML not being replaced

Within my HTML snippet, I have encountered some <br> tags <div id="reading-project"> <p>The next morning, as soon as the sun was up, they started on their way, and soon saw a beautiful green glow in the sky just before them."That must b ...

Development with Node JS, express, Mongoose, and intricate nested queries

I'm struggling with a group of interconnected queries using express/mongoose, structured like this: app.get(..., function(...) { Schema1.query(..., function(..., res1) { for ( var key in res1 ) { Schema2.query(..., function(..., ...

Troubleshooting: jQuery AJAX .done() function failing to execute

Currently, I have a piece of code that is being utilized to dynamically load HTML into a CodeIgniter view: $.ajax({ type:"POST", url: "Ajax/getHtml", data: { u : conten ...

Disrupting methods on a dependency within QUnit can cause tests against that dependency to fail

Currently, in my Google Apps Script project, I am unit-testing an application using QUnit for test-driven development purposes. Code Under Test The function I am currently focusing on testing and developing is the creation of a Sheet from a long string o ...

Do not engage with the website while animations are running

I'm working on a JavaScript project where I want to create textareas that grow and center in the window when clicked, and shrink back down when not focused. However, I ran into some issues with the .animate() function that are causing bugs. During QA ...

What is the best way to toggle the enablement of a textbox with jQuery?

Welcome all! Initially, all controls are disabled. Upon clicking the Add or New button, I want to enable textboxes and the Save button while keeping the Edit and Delete buttons disabled. Once the Save button is clicked, I wish to disable all textboxes and ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Using Websockets in combination with AngularJS and Asp.net

While working on my application that uses AngularJS with Websocket, I encountered a specific issue. The WebSocket communication with the server works fine as users navigate through different pages in Angular. However, when a user decides to refresh the p ...

utilizing vueJS for global notifications

It may sound like a cliché question, but I still haven't grasped it. I have a primary component that is always loaded in the application. Let's refer to it as DefaultContainer.vue <template> <div class="app"> .... Notifi ...