JavaScript difference between ' ' and (' ') - javascript

What is the difference between '' and ('')
let n = 'a' + 1
let n = ('a') + 1
let n = ('a') + (1)
what is the difference?

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);

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));

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);

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

Related

JavaScript commutative behavior for function call. Needed pointers for what exactly happens behind scenes

I have following code and want to check commutative property with impure functions. Can anyone explain why the first two console log print 3, 3 and why the direct function call print 3 and -3?
var multi = 1;
const f = x =>{
multi = -multi;
return x * multi;
}
let a = f(2);
let b = f(5);
console.log("a+b:: ",a+b);
console.log("a+b:: ",b+a);
console.log("a+b:: ",f(2) + f(5));
console.log("a+b:: ",f(5) + f(2));
Any suggestions/explanation is appreciated.
For the first two logs, you're only invoking the functions twice - in these lines:
let a = f(2);
let b = f(5);
after which a and b don't change. 5 + -3 is the same as -3 + 5.
For the last two logs, you invoke the functions four times, and the signs invert each time the function is called, resulting in
f(2) + f(5) // -2 + 5
f(5) + f(2) // -5 + 2

what's the differences between (variable).toFixed(2) and +(variable).toFixed(2)?

I'm wondering what's the main differences between
(2.3444).toFixed(2) ==> 2.34
Also
+(2.3444).toFixed(2) ==> 2.34
Both of them giving the same results. Can any one explain when I need to use that + sign?
The first gives you a string, the second gives you a (now truncated) number.
var x = 2.344;
var a = x.toFixed(2);
var b = +x.toFixed(2);
console.log(a, typeof a);
console.log(b, typeof b);
A unary plus will attempt to convert it's operand to a number.
The reason this matters is because the first one will lead to string concatenation if you "add" a number to it.
var x = 2.344;
var strNumber = x.toFixed(2);
console.log(strNumber);
console.log(strNumber + 5); // Expected: 7.34, actual: 2.345

JavaScript ++ operator not working correctly

Why is it that when I run the JavaScript code below, it alerts 10? I would expect it to alert 11. I tried this in multiple browsers.
var t=5;
t+=t++;
alert(t);
Let's rewrite it a couple times to expand out each step, assuming t = 5
t += t++;
// same as
t = t + t++;
// same as
t = 5 + t++;
// same as
t = 5 + (t = t + 1, 5); // the second 5 here is the old `t` value
// same as
t = 5 + 5; // the `t = t + 1` becomes obsoleted by the other `t =`
// same as
t = 10;
So what have we learnt? Write it longhand,
t = t + t + 1;
// or
t = 2 * t + 1;
// or if you really like +=
t += t + 1;
If you're wondering why t++ is the same as (t = t + 1, 5), it is because of how foo++ is defined, it means
Remember the value of foo, lets call this old_foo
Increment foo by 1
Return old_foo
If we were to write it as a function, pseudocode
function (foo) { // passing foo by reference
var old_foo = foo;
foo = foo + 1; // imaging this is a reference set
return old_foo;
}
Or, using the comma operator,
foo = foo + 1, old_foo;
// i.e. if `foo` was `5`
foo = foo + 1, 5;
It's because you used t++ instead of ++t
The first one evaluates the number first then increments, whereas the second does the opposite.
t = 5; t += ++t // => 11
You seem to assume that given left += right, right is evaluated first and then added to left. However, that is not the case.
From the spec:
12.14.4 Runtime Semantics: Evaluation
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
Let lref be the result of evaluating LeftHandSideExpression.
Let lval be GetValue(lref).
...
As you can see, the left side is evaluated before the right side, i.e. t is evaluated before t++, and at that point t is still 5.

Explain +var and -var unary operator in javascript

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:
+a;
-a;
To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:
a = -10;
a = +a;
document.writeln(a);
And the output is still -10;
I've also tried:
a = false;
a = +a;
document.writeln(a);
And the output is 0;
What is a practical code example of these unary operators?
The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.
var a = 4;
a = -a; // -4
a = +a; // -4
The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.
var a =-4;
a = Math.abs(a); // 4
Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.
var a = "5";
a = +a; // 5
The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.
var a = "5";
a = parseInt(a, 10); //5
One example is that they can be used to convert a string to a number,
var threeStr = '3.0'
var three = +threeStr
console.log(threeStr + 3) // '3.03'
console.log(three + 3) //6
I would like to explain this from basic mathematical point:
The multiplying rules:
Positive x Positive = Positive: 3 x 2 = 6
Negative x Negative = Positive: (-2) x (-8) = 16
Negative x Positive = Negative: (-3) x 4 = -12
Positive x Negative = Negative: 3 x (-4) = -12
Considering you example:
a = -10;
a = +a
document.writeln(a);
+a = +(-10) = Positive x Negative = Negative = -10
a = false;
a = +a;
document.writeln(a);
false == 0, +a = +(+0) = Positive * Positive = Positive = 0 (maybe use true is a better example)
a = 1
b = -a
console.log(b)
output
-1
'+' operator in a variable 'a' simply means : a
'-' operator in a variable 'a' simply means : -a
Since, in above example
a=-10;
a= +a; // means a, ie, +(-10) which is -10
but,
a= -a; // means -a, ie, -(-10) which is +10
+a means a*1
and
-a means a*(-1)
Thats it!!!!!!
Try this
false == 0 // returns true
So,
a = false
a = +a //a * 1
console.log(a) // prints 0 as expected

Difference between += and =+ in javascript

I want to know why after running the third line of code the result of a is 5?
a = 10;
b = 5;
a =+ b;
Awkward formatting:
a =+ b;
is equivalent to:
a = +b;
And +b is just a fancy way of casting b to number, like here:
var str = "123";
var num = +str;
You probably wanted:
a += b;
being equivalent to:
a = a + b;
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands.
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.

Categories