Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #27965

Re: Style: new String( "abc" )

From Thomas 'PointedEars' Lahn <PointedEars@web.de>
Newsgroups comp.lang.javascript
Subject Re: Style: new String( "abc" )
Date 2015-06-02 22:39 +0200
Organization PointedEars Software (PES)
Message-ID <28669564.qu1ylNz8U2@PointedEars.de> (permalink)
References <new-style-20150602185946@ram.dialup.fu-berlin.de>

Show all headers | View raw


Stefan Ram wrote:

>   IIRC, I read somewhere that one should prefer to use
>   primitives such as "abc"; one should not create objects
>   via »new String ( "abc )« (or, »new Number( 7 )«).
> 
>   I am not sure why »new String( "abc" )« should be bad style.

Certainly there is nothing wrong per se in having objects that are 
“instanceof String”, see e.g. 
<http://PointedEars.de/wsvn/JSX/string/unicode.js>.

But consider, for example, what

  var b = new Boolean(false);
  var b = new Number(0);
  var s = new String("");

would do in

  if (b && n && s)

when used instead of

  var b = false;
  var n = 0;
  var s = "";

>   For example, I consider the following piece of code:
> 
> { "abc".charAt( 0 );
>   "abc".charAt( 1 );
>   "abc".charAt( 2 ); }
> 
>   (Of course, the example with »"abc".charAt( 0 );« is nonsense.)

Why is it nonsense?

>   . Above, AFAIK, the primitve "abc" was implicitly converted
>   into an object /three times/.

Not necessarily as *these* expressions can be optimized by a compiler to

  "a"
  "b"
  "c"

respectively.

>   If one would have written:
> 
> { let abc = new String( "abc" );
>   abc.charAt( 0 );
>   abc.charAt( 1 );
>   abc.charAt( 2 ); }
> 
>   only one object would have been created.

Not necessarily.  In fact, that you are declaring the variable in block 
scope using “let” makes it possible to optimize here easily as there is no 
code outside of the block that could change the value of *that* “abc”.  
Assuming, of course, that “String” still has its initial value.

-- 
PointedEars
FAQ: <http://PointedEars.de/faq> | SVN: <http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-matrix>
Please do not cc me. / Bitte keine Kopien per E-Mail.

Back to comp.lang.javascript | Previous | Next | Find similar | Unroll thread


Thread

Re: Style: new String( "abc" ) Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-06-02 22:39 +0200

csiph-web