Why the following JavaScript code is not valid? - javascript

When the following code is executed in chrome console
let a, b, c;
b = 2;
a = b+1 = c = 2+3;
It says an error 'Invalid left-hand side assignment' for the last statement.
But when we execute the below-given code it accepts it and does not show any error.
let a, b, c;
a = b = c = 2+3;
assignment '=' is an operator so according to operator precedence in javascript, it should work fine. what do you guys think, what is the problem?

for the first code you would need to do
let a,b,c;
b=2;
a=b+1;
c=5;
doing
a=b=c=2+3
works because you arent altering a value to the left of the last equal

the = operator calculate first the right side and require the left side to be lvalue.
In your second example for every assignment operator the left side is always a variable, so it works fine. but in the first example:
let a, b, c;
b = 2;
a = b+1 = c = 2+3;
you trying to assign 5 into b+1, its simply not a variable.

You just need some parenthesis to make it clear what you mean:
a = 1 + (b = c = 2+3);

Related

Is parseInt doesn't needed for '*' in JavaScript? [duplicate]

This question already has answers here:
What exactly is Type Coercion in Javascript?
(9 answers)
Closed 2 years ago.
I have array, by which at some point am mapping the array and calculating sum and percentages. So while implementing the logic i saw that, when i use '*' directly its working but when i use '+' it just adds the two string
For example:
const a = '100';
const b = '10';
const c = a * b;
const d = a + b;
console.log(d)
When i checked the d , it gives '10010' and when c it gives '1000' ! How is this ?
But when i use parseInt(a) + parseInt(b) it works perfectly with 110 as output
In JavaScript there are no primitive datatypes like int, float etc. There are only variables which can be initialized with everything you need. For your example
const a = 100;
const b = 10;
const c = a * b;
const d = a + b;
console.log(d);
should work perfectly, because I removed ''. With '' the constant thinks it is a string provided. Without '' there are just the numbers saved in the constants. Also + doesn't work in your example, because as I said the constants think the numbers are a string due to ''. So it just puts this two "strings" together and not summing them up.

Find a value such that the equation is true

I want to find a value of a numerical variable such that it makes the equation true. Example:
var a = random number;
var b = random number;
function (find var c such that a = b + c;) {
console.log(c);
}
Is it possible to make the computer search for the answer of c? and not such that you undo the equation where c = a - b, but such that as it checks answers it gets closer to the value of c.
I would do z-z, and then that's your number. But that's probably not what you are asking.

Javascript Unwanted Data Type Switching

I have set a number variable under c. After running it through local storage and a couple functions, the variable has turned into a string. Instead of x adding to c , x adds a digit to c. Can anyone see the problem?
function hi() {
c += x;
document.getElementById("paragraph").textContent = "This is a string" + c;
localStorage.clocal = c;
}
function resetvar() {
c = localStorage.clocal;
}
function bla() {
if (localStorage.getItem("clocal") === "null") {
document.getElementById("parargraph").textContent = "This Works Okay";
} else {
document.getElementById("parargraph").textContent = "This is a string" + localStorage.credits;
}
}
the data put in localStorage always as string.
If you wanna to get as number that you have to parse it
like this
c = parseInt(localStorage.clocal);
That's the nature of JS. You can use parseInt(c, 10) + x or x + 1 * c to over come this.
It's a little bit difficult to follow the flow of these methods, but one glaring issue I see is this line:
c += x
In this situation, you're saying that you want to set c equal to the result of c + x where x is a string, instead of setting x equal to x + c? By making this assignment, you are converting c to a string. Then after that point is doesn't matter what else you do -- it will still be a string unless you re-assign it explicitly as an integer.
I hope I understand your intention correctly.. It is a bit unclear.

JavaScript Logical OR invalid assignment

I'm trying to understand how JavaScript's logical OR operator works and I am trying to recreate a code I read in a book but with my own twist to it but I keep getting a reference error when I try to run the code.
function add(a,b) {
b || b = 1;
return a+b;
}
My understanding is that if the left operand is false then the right operand is evaluated then the right operand's value is returned or used. With the code above, what I am trying to do is when the function is invoked and the second parameter is omitted, it would use a default value of 1 as the second value to the equation, but I keep getting a reference error that states invalid left hand assignment.
Probably you wanna achieve this:
b = b || 1;
Try b || (b = 1) instead. That's also exactly what CoffeeScript generates for its ||= operator.
The problem is with operator precedence. Assignment = has lower precedence than boolean or ||, therefore this
b || b = 1
is interpreted as
(b || b) = 1
which is invalid, because you cannot assign to an expression. To achieve what you want you have to tell JS you want || first and then =:
b || (b = 1)
but a more common way to express this would be
b = b || 1
In the context of your function this might not work as expected, since 0 is a valid integer value, and your code will treat it as false and substitute it with 1. So, the correct, although more verbose, way to write your function is
function add(a, b) {
b = (typeof b == "undefined") ? 1 : b;
return a + b;
}

JS Vars - Adding

I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)

Categories