HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Declaring JavaScript variable and then overwriting it multiple times

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
overwritingjavascriptdeclaringthenmultipleandtimesvariable

Problem

I'm wondering if I am doing this in the most efficient way.

So I'm declaring my function el which is equal to a macro (Google Tag Manager), then I reassign or overwrite that previously-defined var which grabs the innerText/textContent of the element. It then converts the string to lowerCase and then capitalizes the first letter of the string, before finally returning the 'cleaned-up' element.

function() {
      var el = {{element}}
      el = (el.innerText || el.textContent);
      el = el.toLowerCase();
      el = el.charAt(0).toUpperCase() + el.slice(1);

      return el;

    }

Solution

You can using chaining, move the toLowerCase() to simplify a little and return the last statement directly:

function() {
      var el = {{element}};
      el = (el.innerText || el.textContent);
      return el.charAt(0).toUpperCase() + el.slice(1).toLowerCase();
}


I'm personally not a fan of using a single variable for many purposes (I think it interferes with readability and maintainability) so I would probably do this:

function() {
      var el = {{element}};
      var text = (el.innerText || el.textContent);
      return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

Code Snippets

function() {
      var el = {{element}};
      el = (el.innerText || el.textContent);
      return el.charAt(0).toUpperCase() + el.slice(1).toLowerCase();
}
function() {
      var el = {{element}};
      var text = (el.innerText || el.textContent);
      return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

Context

StackExchange Code Review Q#44790, answer score: 7

Revisions (0)

No revisions yet.