Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

role of parentheses in javascript

Tags:

javascript

I'd like to know the difference between the following and the role of the parentheses:

foo.bar.replace(a,b)

and

(foo.bar).replace(a,b)

do the parentheses require the contained expression to be evaluated first before moving on to the replace method? I have seen this in code I am maintaining and am curious as to why it would be neccessary? E.G.

location.hash.replace(a,b)

and

(location.hash).replace(a,b)
like image 680
njorlsaga Avatar asked Jan 14 '13 14:01

njorlsaga


1 Answers

It is not required in your examples.

The idea is indeed that the block inside the parenthesis must be evaluated before continuing..

It is needed in cases like

(new Date()).getMilliseconds()

(not really needed in this case as noted by @Teemu)


In general use this syntax to avoid using a temporary variable..

var result = 5.3 + 2.9;
console.log( result.toFixed(1) );

can become

console.log( (5.3 +2.9).toFixed(1) );

If you were to use 5.3 + 2.9.toFixed(1) the toFixed(1) would get applied to 2.9 only, return a string and then concatenate it with 5.3 The result would be 5.32.9

like image 175
Gabriele Petrioli Avatar answered Sep 21 '22 20:09

Gabriele Petrioli