Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript difference between ' ' and (' ')

Tags:

javascript

What is the difference between '' and ('')

let n = 'a' + 1

let n = ('a') + 1

let n = ('a') + (1)

what is the difference?

like image 430
Pakuhashi Avatar asked Jun 07 '20 08:06

Pakuhashi


3 Answers

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);
like image 143
mr. pc_coder Avatar answered Oct 21 '22 02:10

mr. pc_coder


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));
like image 29
Nina Scholz Avatar answered Oct 21 '22 04:10

Nina Scholz


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);
like image 31
Yousaf Avatar answered Oct 21 '22 04:10

Yousaf