Reputation: 69
What is the difference between ''
and ('')
let n = 'a' + 1
let n = ('a') + 1
let n = ('a') + (1)
what is the difference?
Upvotes: 5
Views: 137
Reputation: 23778
Grouping Operator ()
Grouping operator implies the precedence of evaluation of an expression or subexpression.
With the grouping operator, it is possible to override the normal precedence of evaluation by telling the compiler an expression with lower precedence should be evaluated before an expression with higher priority.
console.log(3 + 4 * 5); // 3 + 20 // expected output: 23 console.log(4 * 3 ** 2); // 4 * 9 // expected output: 36 let a; let b; console.log(a = b = 5); // expected output: 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Upvotes: 0
Reputation: 29282
There’s no difference between ''
and ('')
. Parentheses make no difference in your code examples.
Parentheses ()
, known as the Grouping Operator, are used to change the order of evaluation of an expression. Consider the following expression:
1 + 2 * 3
As the *
operator has higher precedence, first 2 * 3
will be evaluated and then the result of multiplication will be added to 1
.
const result = 1 + 2 * 3;
console.log(result);
If you want to do addition first, then you can use ()
.
(1 + 2) * 3
Adding parentheses will change how the expression is evaluated. Instead of multiplication, now 1 + 2
will be evaluated first and then the result of addition will be multiplied with 3
.
const result = (1 + 2) * 3;
console.log(result);
Upvotes: 3
Reputation: 386560
Taking a property from an object works without parentheses.
var value = { x: 1 }.x;
console.log(value);
Basically the only need for parenthesis is to destructure the item ouside of a declaration.
Does not work
var foo;
{ foo } = { foo: 1 }; // assigment to a block statement
console.log(foo);
Works
var foo;
({ foo } = { foo: 1 });
console.log(foo);
Another use case for parentheses, is by takeing an arrow function which returns an object.
var fn = foo => ({ foo });
console.log(fn(1));
Upvotes: 5
Reputation: 17590
They are same both.
()
is important for precedence especially if there is math operations and concat with string together. Read this info
var example1='x' + (1+2); console.log(example1);
var example2='x'+1+2; console.log(example2);
var example3=("x"+4)/2; console.log(example3);
var example4=("x")+(4/2); console.log(example4);
Upvotes: 8