Are there more efficient methods for utilizing local scope when defining a variable?

Having experience in the ML world, I'm used to creating variables with limited scope like this:

let myVar =
    let result1 = doSomething()
    let result2 = doSomethingElse()
    result1 + result2

In TypeScript, it seems you can achieve similar scoping using anonymous functions:

const myVar = 
    function() {
        const result1 = doSomething();
        const result2 = doSomethingElse();
        return result1 + result2;        
    }();

The issue is that this method adds extra indentation and may confuse the purpose of the code. Is there a more streamlined approach to handle this situation?

Answer №1

One option is to utilize a fat-arrow function as an IIFE:

const myVar = (() => {
  const result1 = doSomething();
  const result2 = doSomethingElse();
  return result1 + result2;
})();

However, another simpler approach would be:

const myVar = doSomething() + doSomethingElse();

If the code for doSomething() and doSomethingElse() is too long in the above example, it might be worth considering transforming them into separate functions.

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

Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app: import * as firebase from "firebase/app"; import { collection, getDocs } from "fir ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...

Guide to creating animations with javascript/react js

My attempt at altering the opacity of an element every 100 milliseconds following a click event has not been successful. The function change is triggered by a click, yet the code does not work as intended. Here's what I have so far: function change (i ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Fill a dynamic form with a date sourced from the ngrx storage

How can I populate a form with data from the store if setValue and patchValue methods are not working? export class MyComponent implements OnInit, OnDestroy { public newsletterToEdit$: Observable<NewNewsletter> = this.store.selectNewsletterToEdi ...

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

Is there a way to view the type signature of the resulting intersection type (type C = A & B) in IDE hints, rather than just seeing the components?

When analyzing types defined by intersection in Typescript, I notice that the hint remains identical to the original definition: https://i.stack.imgur.com/mjvI8.png However, what I actually want is to visualize the resulting shape, similar to this: http ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Ways to dynamically display components in React Native

In my React Native app, I have a custom tab control that is rendered dynamically using the following configuration: const TABS = [ { title: 'Tab 1', component: MyComponentOne }, { title: 'Tab 2', component: MyComponentTwo } ]; T ...

Manipulate the elements within an array, make changes, and then insert

In the array called newData, I am trying to add one more element with Rank 1. However, the issue is that the Rank value is getting updated for both records. The desired behavior is to have Rank set to 1 for the second record and have the first record' ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

What is the best way to assign an index signature to a plain object?

Currently, I have this object: const events = { i: 'insert', u: 'update', d: 'delete' }; I am struggling to assign an index signature to the object. When I try the following: export interface EventsSignature { [key: ...

Techniques for importing esm libraries without requiring the "type": "module" declaration in the package.json configuration file

I have successfully implemented a TypeScript Node project but now I am facing an issue while trying to integrate the VineJS library into the project. The problem arises because VineJS is exclusively an ESM (ECMAScript Module) package, and when adding it to ...

Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfo ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

Using $gte and $lt to search within a range in mongoDB can be tricky when dealing with data types in typescript

Whenever I try to search by range of dates using $gte and $lt, I encounter issues with types. The types for my model are as follows: export interface IOneStoreCa { magId: number, caTtc?: number, marge?: number, } export interface ICa { _id: string ...