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

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Nested Promise.all within another Promise.all appears to terminate prematurely, triggering a warning indicating failure to return from a promise

I am utilizing this function to be invoked within another Promise.all. However, I consistently encounter a warning message: Caution: a promise was generated in a handler but was not returned from it. Additionally, the function deleteFutureAppointments() ap ...

HTML Tutorial: A Beginner's Guide to Invoking REST API

Hi there! I'm new to APIs and struggling to grasp the concept. The tutorials online seem more complex than necessary. Here's what I need help with: I want to create a basic webpage that allows me to search for information using the Pokemon API a ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...

What is the best way to access an item within an item using HTML and AngularJS?

I attempted to retrieve a value from two dynamic objects using AngularJS. <div ng-controller="SampleController"> <div> {{item['111']['price']}} </div> within the SampleController $scope.item={111:{price:"232"},112:{ ...

Solving the puzzle of complex polymorphic object model deserialization in Java Jackson: Facing the JsonMappingException error – Unexpected token (START_OBJECT) instead

I am working with a hierarchy of objects described as follows: A B extends A C extends B D extends B E extends C F extends A and contains a reference to A The annotation for class A is defined as: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=Jso ...

Unable to display bar chart on PHP webpage showing database number volumes using JavaScript

I'm currently working on generating a bar chart to show the number of bookings per month. I have two separate SQL queries that retrieve the data correctly, as confirmed by testing. However, when I try to run the file in my browser, nothing is displaye ...

Uh oh, it looks like there's an issue! The function getCoordinates is not recognized for this.locations

Whenever I attempt to execute the method in my class (getCoordinates()), an Error is thrown: ERROR TypeError: this.locations[0].getCoordinates is not a function What am I doing wrong? The service method I'm using: getLocations(){ return this ...

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

The best approach for sending parameters to the parent class in TypeScript for optimal efficiency

What's the optimal solution to this problem? I really appreciate how we can specify attributes in the constructor and TypeScript takes care of handling everything to assign values to the props in JavaScript - like I did with 'department' her ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

Braintree drop-in feature now allows for automatic disabling of the submit button while the transaction

I've been struggling with a seemingly simple task that I just can't seem to figure out. I'm using Braintree's dropin UI and I have a submit button that I need to disable while the processing is happening, but I can't seem to find t ...

Calculating the duration of time using JQuery with provided start and end times

I am currently utilizing a jQuery time picker to gather start and end times in a 12hr format. My goal is to calculate the time duration between the start and end times in HH:MM:SS format. The code snippet I have below is providing me with a duration like ...