Which is more efficient: Using TypeScript's Object.assign() or creating a new object?

Seeking advice on two different approaches to implementing a method with a constant. Unsure about the better option. Can someone provide guidance? Thank you!

Approach 1: Declaring the constant outside of the class, causing it to be invoked only once but requiring the return of a new variable.

const X = {a: 0, b: 1, c: 2}
export class A{
   private method a (val: any) { 
       return {...X, ...val}
}}

Approach 2: Placing the constant within the method, resulting in the invocation of the constant every time the method is called (twice in this scenario) but eliminating the need for creating a new object.

export class A{
   private method a (val: any) { 
       const x = {a: 0, b: 1, c: 2}
       return Object.assign(x, val)
}}

Answer №1

In my opinion, there is no one-size-fits-all solution to this issue. It's important to consider the scope of variables rather than just how often they are called or created. When declaring a constant outside the scope of a class, any other class or function within that scope can access and potentially modify it, leading to unexpected bugs in your code.

Let's imagine you have a variable x set to 5

function isEven(value: number) {
    // Here I'm changing the value of x
    x = 2

    return value % 2 === 0;
}

function destroyTheWorldIfEven(value: number) {
  if(isEven(value)){
      console.log("x is", x)
      console.log("your world has been destroyed")
      return
  }
  
  return console.log("you are safe")
}

// Initially x is 5
destroyTheWorldIfEven(x)

// In the next call x becomes 2 due to the reassignment in isEven function
destroyTheWorldIfEven(x)

If you don't need to share the constant variable among functions or classes, it's best to keep it within the scope of class A. Here are some suggestions:

  1. If const x is only used in one method of class A, keep it within that method.
  2. If const x is used by multiple methods from class A, make it a private attribute.
  3. If const x belongs to class A but needs to be accessed by other classes, make it a public attribute but avoid defining a setter method for it.

Here are some helpful resources for further reading:

JavaScript scope

JavaScript hoisting

JavaScript closure

SOLID principles

The SOLID principles are particularly crucial when working with Object-Oriented Programming, so be sure to give them a thorough read.

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 error occurred while attempting to set up Next-auth in the process of developing

In my Next.js app, I have implemented next-auth for authentication. During local development, everything works fine with 'npm install' and 'npm run dev', but when I try to build the project, I encounter this error message: ./node_modul ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

In Typescript, encountering a member of a union type with an incompatible signature while utilizing the find method on an array of

I need to verify if a specific value exists within an array of objects. The structure of my array is as follows: [ 0: { id: 'unique_obj_id', item: { id: 'unique_item_id', ... }, ... }, 1: {...} ] The objects in the ar ...

Angular index.html file can include a conditional script

I am currently working on an Angular project, where the index.html serves as the main entry point for the application, just like in any other Angular project. This file contains important links and configurations. Within the HTML code snippet below, you w ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

What are some ways to enhance this TypeScript code using Functional Programming with the FP-TS library?

i am struggling to write some typescript code using fp-ts Below are the tasks that i want the algorithm to carry out: Once a path is received from the command line, it should check if the given path exists search for all files in the directory and locat ...

Why are my variables resetting in Angular after ngAfterViewInit?

There seems to be an issue with my variables resetting after successfully using them in ngAfterViewInit(). I have a few @ViewChild and regular variables that are utilized or set in ngAfterViewInit. However, when certain events that I added post-initializa ...

In TypeScript, the catch block does not get triggered

I created a custom pipe in Angular that is supposed to format passed parameters to date format. The pipe contains a try-catch block to handle any errors, but surprisingly the catch block never seems to be executed even when an invalid date is passed. impo ...

Passing Angular/Electron service output to a variable results in it being undefined

I am encountering a problem with my service. When I run the code marked #1, it successfully displays data in the console. However, when I attempt to assign it to a variable, I receive an undefined value. Here is the code snippet: Service: executeShell(c ...

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

When it comes to passing prop values through functions, TypeScript types do not provide suggestions

I'm struggling to find a way to ensure that developers have suggested types for specific props in my component, regardless of how they pass data to the prop. For example, when I directly pass an array of values to the prop: <Component someProp={[{ ...

Interacting with the Dropdown feature on the page causes the body of the page to shift

I am encountering an issue with 2 dropdowns in Datatables used to filter content. The problem arises when a dropdown is positioned on the right side of the page, causing a shift to the left by approximately 10px. Conversely, if the dropdown is placed on th ...

What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conve ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Adding an object with a composite key to an IndexedDB object store is not permitted as the key already exists within the store. This limitation occurs when attempting to add an entry

I am facing an issue with my objectStore where adding an object with the same productId but a different shopName triggers an error in the transaction showing: ConstraintError: Key already exists in the object store.. This is how I initialized the objectSto ...

Adding a dynamic component to a directive in Angular 2.1

As a newcomer to Angular 2.1, I am looking to spruce up some elements for automatic translation using a custom directive. The syntax I have in mind is: <span customDirectiveTranslation="translateble">{{translateble}}</span> or simply <spa ...

The issue arises when attempting to invoke a method from a global mixin in a Vue3 TypeScript component

I've been working on this challenge for the past week, and I would appreciate any help or insights from those who may have experience in this area. Currently, I am in the process of converting vue2-based code to vue3 for a new project. Instead of usi ...

Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance ...

Guide on building an npm package that seamlessly allows for installation both locally and globally (-g) using webpack and typescript

As I work on developing an npm package with options for both local and global (-g) installations, I find myself puzzled by the distinctions between the src and lib directories and the purpose of the bin directory. In my previous projects, I typically util ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...