Tips for utilizing temporary variables in JavaScript

Is there a way to set a variable based on the result of a function call without calling the function multiple times or adding unnecessary temporary variables? Even though it might be seen as premature optimization, I prefer to avoid that.

One approach is to use a block scope with a temporary variable obj:

function foo(){
    let output;
    calculate_output: {
        const obj = get_object();
        if(obj.x > obj.y){
            output = "x is greater than y";
        }else if(obj.x < obj.y){
            output = "x is less than y";
        }else{
            output = "x is equal to y";
        }
    }
    console.log(output);
    // more code that uses [output] below, so I don't want an unnecessary [obj] cluttering the function scope here..
}

But in this case, making output a let might not be ideal since it won't change value. It should ideally be a const.

However, trying to achieve this usually involves calling the function multiple times:

const output = get_object().x > get_object().y ? "x is greater than y" : get_object().x < get_object().y ? "etc";

So, is there a better way to calculate the value of output with temporary variables without compromising on performance?

const output = (const obj = get_object(); obj.x > obj.y ? "x is greater than y" : obj.x < obj.y ? "etc");

Answer №1

Using let is my preferred way to handle this situation. Unfortunately, there is no built-in method to declare a variable that can only be assigned once and then remains read-only.

Alternatively, if you insist on using const, you could achieve it with ternaries in the initialization expression.

function bar() {
  const obj = get_object();
  const result = obj.x > obj.y ?
    "x is greater than y" : (obj.x < obj.y ? "x is less than y" : "x is equal to y");
  console.log(result);
}

If the initialization process requires even more complex logic, an IIFE (Immediately Invoked Function Expression) could be used.

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

What causes AsyncStorage to lose one value while another value remains intact?

My last session id is stored using AsyncStorage, but for some reason it loses a specific value and I can't figure out why. I created an app that should automatically select the last chosen group on startup. However, after restarting the app, AsyncSto ...

What's causing the malfunction in this JavaScript function for capitalizing the first letter?

My React component includes a select box where users can choose one of four "severity" labels, all of which must be in lowercase due to API requirements. Here is the select box... <select id="logs-select" onChange={this.handleSeverityChange} value={thi ...

Defining global 'require' scripts in Node.js

Seeking a solution to a slightly unusual problem. I hope that using simple examples will clarify my query, as explaining my complex usage can be challenging. I am incorporating my custom modules into the routes.coffee file for an Express server. My goal i ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

requesting data and receiving a promise object

I developed a function called getCartItems that invokes getSingleItems with the ID as an argument. When I log the JSON result in getSingleItem, it correctly displays the product object. However, when I try to access the function call value, I am getting a ...

Using the entire row as a toggle mechanism to select items in an office-ui-fabric detailslist, instead of relying on a small checkbox for selection

Currently, I am utilizing Office UI Fabric React components and I am aiming to enhance the default selection behavior for a DetailsList. At present, there is a difference in functionality between clicking on a row and clicking on the small checkbox located ...

Ways to create an angularJS $watch function that is able to recognize modifications in styling

I have a rich text box equipped with all the necessary style controls. If I input new text, it saves without any issue. Whenever I modify the content (text) and add styles like color highlighting or bold formatting, the changes are saved successfully. H ...

Utilizing Angular's binding feature with objects

Clarifying the question for better understanding. Plunkr Preview: <input type="text" ng-model="form['data']['sampleData']"> <input type="text" ng-model="form[bindingPrefix][bindingSuffix]"> <input type="text ...

How about: "Is there a way to show items in a list without using

I have removed the bullet points from an unordered list, but I am having trouble displaying Log with every message. The code I have doesn't seem to be working as expected. I want users to be able to differentiate between messages easily, without seein ...

Error encountered: Could not execute 'getComputedStyle' on the 'Window' object - the first parameter is not considered an 'Element' within the JavaScript map function

I've been searching for a solution to my problem both on StackOverflow and Google, but haven't been able to find one yet. So, here's my issue. I have an array of DOM elements that I retrieve using the @ViewChildren('labelSquare') ...

Fill out the form field using an AJAX request

Whenever a specific business is selected from a dropdown list, I want to automatically populate a Django form field. For example: I have a list of businesses (business A, business B, ...) and corresponding countries where each business is located. Busin ...

Angular 7 three-dimensional model display technology

Looking for advice on creating a 3D model viewer within an Angular 7 project. Currently using the model-viewer web component in JavaScript with success. How can I replicate this functionality and viewer within my Angular 7 application? ...

Transcode Byte Array into Base64 String Using AngularJS

I am receiving a byte array in the service response, and I need to display that image in an image field on my HTML page. Can anyone provide guidance on how to implement this? I have searched for solutions on Stack Overflow but have not found a valid soluti ...

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

Creating a dynamic chart on the fly with the power of chart.js

Currently in the process of building a data dashboard and have hit a roadblock that I can't seem to navigate. Utilizing chart.js for rendering charts and jquery/js for dashboard control, I aim to allow users to add new charts with a simple button clic ...

How do I navigate back to show the initial parent component instead of the nested child component in ReactJS?

The data flow in my React app goes like this: SubmitForm -parent-> Results -parent-> Presentation -parent-> ButtonBackToSearch I am delving into ReactJS and trying to adopt the right mindset for creating single-page applications. Currently, I am ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Sequential invocations to console.log yield varying outcomes

So, I'm feeling a bit perplexed by this situation. (and maybe I'm missing something obvious but...) I have 2 consecutive calls to console.log. There is nothing else between them console.log($state); console.log($state.current); and here's ...

How can you transfer data from a Writable Buffer to a ReadStream efficiently?

How do I convert a writable stream into a readable stream using a buffer? This is my code to store data from an ftp server in an array of chunks: let chunks = [] let writable = new Writable writable._write = (chunk, encoding, callback) => { chunks.p ...