0

The site https://ipenburg.home.xs4all.nl/atkinsome/ provides the following code fragment:

    var IMG = new String('img');
    var DOT = new String('.');
    var CLASS = new STRING('class');
    DOT.concat(CLASS_FILTER)

why not simply write 'img' each time, or '.class'?

1
  • Looks like it might be some kind of misguided attempt at optimization. Commented Jul 21, 2016 at 10:37

1 Answer 1

2

The code quoted in your question looks like it was written by someone who isn't particularly proficient with JavaScript, since it unnecessarily creates String objects. If it exists at all, it should simply be:

var IMG = 'img';
var DOT = '.';
var CLASS = 'class';

or in ES2015+

const IMG = 'img';
const DOT = '.';
const CLASS = 'class';

As for the "why do this," the best justification I can come up with is that it allows you to find all of the places you've used IMG for the purposes of the img tag without also finding places you've used 'img' for something else entirely.

What it isn't is future-proofing (or at least one hopes it's not meant to be). If you later changed IMG to be 'image' without changing its name, that would be actively misleading subsequent authors working in the code.

Sign up to request clarification or add additional context in comments.

2 Comments

Opinion: Using constants for magic numbers is reasonable and useful, but in general, using constants for literals doesn't make a lot of sense.
Clear answer, thanks. Makes me more aware of copy catting pitfalls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.