Javascript: concatenation with "," doesn't work - javascript

<button onclick="rzut()" />
<div id="wynik" />
<script type="text/javascript">
function rzut() {
document.getElementById("wynik").innerHTML = "Wynik to",Math.floor(Math.random()*6)+1;
}
</script>
For an unknown reason my script show only "Wynik to" and it skips the next part (math.floor etc)

Okay, let's go over some basics.
The first thing I would like to bring up is the concept of an Overloaded Operator. An overloaded operator, in short, is an operator that has different behaviour for different operands. An example of an overloaded operator in Javascript is +. For example:
var x = 4 + 4;
// x = 8
As you can see, adding two numeric values has the effect of summing the fields. But what about..
var x = "4" + "4";
// x = "44";
Well, because the types are strings, it behaves differently, hence it has an overloaded behaviour.
The + symbol will summate numeric values, but concatenate string values.
Bringing this forward to your example, you want to end up with a string value like..
"Wynik to,3"
Where 3 can vary. So let's look at it like this..
"Wynik to,X"
where X is some variable. Well.. this means you've got to build the string on the fly.. So following your approach (and not using some of the nice ES6 features that have been introduced), you can use our friendly overloaded + to accomplish this..
"Wynik to," + X
Where X is some random number between 1 and 6 therefore..
"Wynik to " + (Math.floor(Math.random()*6)+1);
So you'll see here, we've got a numeric value on the right hand side and a string value on the left hand side.
What Javascript does in this situation is what's known as arithmetic promotion, where all operands are promoted to the precision of the highest operand.
In this case, the right hand side of the equation is promoted to a string. Then, as we've seen above, our overloaded operator knows what to do with two strings.

Related

What does JavaScript interpret `+ +i` as?

An interesting thing I've never seen before was posted in another question. They had something like:
var i = + +1;
They thought the extra + converted it to a string, but they were simply adding to a string which is what caused it to convert.
This, however, lead me to the question: what is going on here?
I would have actually expected that to be a compiler error, but JavaScript (at least in Chrome) is just fine with it... it just basically does nothing.
I created a little JSFiddle to demonstrate: Demo
var i = 5;
var j = + +i;
document.body.innerHTML = i === j ? 'Same' : 'Different';
Anyone know what's actually occurring and what JavaScript is doing with this process?
I thought maybe it would treat it like ++i, but i doesn't increment, and you can even do it with a value (e.g., + +5), which you can't do with ++ (e.g., ++5 is a reference error).
Spacing also doesn't affect it (e.g., + + 1 and + +1 are the same).
My best guess is it's essentially treating them as positive/negative signs and putting them together. It looks like 1 == - -1 and -1 == + -1, but that is just so weird.
Is this just a quirky behavior, or is it documented in a standard somewhere?
Putting your the statement through the AST Explorer, we can see that what we get here is two nested Unary Expressions, with the unary + operator.
It's a unary expression consisting of + and +i, and +i is itself a unary expression consisting of + and i.
The unary expression with the unary + operator, will convert the expression portion into a number. So you're essentially converting i to a number, then converting the result of that to a number, again (which is a no-op).
For the sake of completion, it works on as many levels as you add:
var i = 5;
console.log(+ + + + + +i); // 5
console.log(i); // still 5
It's in the specification.
Digging through, we can see from §14.6.2.2 that the increment and decrement operators are listed before (and should be preferred) over the unary operators. So precedence alone won't explain this.
Looking up the the punctuation table in §11.7, we can see that every single instance of ++ (the operator) in the spec shows the two together, without whitespace. That's not conclusive, until you check...
The whitespace rules in §11.2, specifically:
White space code points may occur within a StringLiteral, a RegularExpressionLiteral, a Template, or a TemplateSubstitutionTail where they are considered significant code points forming part of a literal value. They may also occur within a Comment, but cannot appear within any other kind of token.
JS does not allow arbitrary whitespace mid-operator.
The JS syntax in both PegJS and Esprima corroborate this, matching on the literal two-character string ++.
For me it's very clear;
var a = +3;
var b = +a; // same as a, could be -a, for instance
var c = + +a; // same as above, same as +(+a)
If you do ++variable the javascript interpreter sees it as the increment operator.
If you do + +variable the javascript interpreter sees it as Unary plus, coercing the value to a number, twice.
So
var a = 1;
var b = +a;
var c = +b;
console.log(c);// still 1
is the same as
var c = + +1;
So the simple answer is that two plus signs can not be separated by a space to be interpreted as incrementation, the space makes it so the interpreter sees two seperate spaces, which is what it really is
The + operators converts into a number, two + operators with a space in between does nothing additional.
Even though it might look very similar, + + and ++ are not at all the same thing for an AST interpreter. The same applies to token separation: varfoo is not the same as var foo.
In the expression + + +i, each + is considered as distinct unary operator, which simply convert your variable to a number. For the incrementation operation, which is ++, no spaces are allowed, neither between the + and the variable token. In the example below, the last line is not valid:
var x = "4";
console.log(+ + +x);
console.log(+ + ++x);
console.log(+ ++ +x);

Should literal numbers not have quotes?

I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
That being said, is there anything wrong with quoting a literal number?
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
It isn't a number. Quoting a number makes it a string, which can make for some differences in the way they're handled. For example:
var a = 1;
var b = '33';
console.log(a + b === 34); // false
console.log(a + b === '34'); // true
Strings also have different types and methods for manipulating them. However, for most of the numeric operators (-, /, *, and other bitwise operators), they convert the string form to its numeric equivalent before performing the operation.
There are also a few differences where numbers are not stored with their exact value in some cases, due to the nature of the floating point format JavaScript numbers are stored in. Strings avoid this problem, though it is much harder to manipulate them. Converting these back to numbers reintroduces these issues. For example, see this:
var recordID = 9007199254740992;
var previousID = recordID;
recordID += 1;
console.log(recordID === previousID); // true
Adding quotes makes the number a string literal and so serves a different purpose than the Number literal defined without quotes.
JavaScript has the concept of type coercion which might have confused you.
Quoting makes a string of a number. It means that for example + operation will concatenate instead of add:
var a = 'asdf';
var b = '20';
var c = a + b; // asdf20
Here is a great explanation of what is going on.
I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
It's not a matter of required Vs not required (optional)
Using quotes (single or double) you state that it is a string (a sequence of characters - no matter if they're all digits)
If you don't place quotes you state it is a number.
That being said, is there anything wrong with quoting a literal number?
No if the entity it represents is not actually a number but a string. So...
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
If the number is a zipcode it may make sense to put quotes, because it is a "code", not a number and is not subject to arithmetics operations.
You're not going to divide a zipcode by 2 or sum two zipcodes because that would not make sense.
But instead of deciding to use quotes or not based on what the value represents I suggest you to consider the problem from the language perspective
You should understand and keep always in mind how do the language's operators behave when you use a string instead of a number in an expression (assignment or comparison).

What is the purpose for multiple comma-separated expressions in a WHILE condition?

I stumbled over the following JavaScript:
Code:
var x="", i=0;
while (i<4, i<7, i<5, i<6)
{
x=x + "The number is " + i + "<br>";
i++;
}
document.write(x);
I never know that it is possible to use multiple comma-separated expression in one WHILE statement.
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
What is the reason for this and what is the behavior (only the last expression is evaluated for the while-exit)?
Is the behavior standardize in all Javascript/C/Java languages?
Only the last result is kept in result of the comma operator, so
while (i<4, i<7, i<5, i<6)
is really equivalent to
while (i<6)
That's the reason why you don't see this more often : it's useless if your comparisons don't have side effects.
This is a special operator in JavaScript which is called comma operator;
so when JavaScript comes across this line
(i<4, i<7, i<5, i<6)
it will evaluate one by one all the operands in the parenthesis and will return the evaluation of the last item i.e. i < 6
It is rarely used; One occasion that I remember to have used it was for indirect call to eval.
(0, eval)(src)
But again in you example the use of it is redundant.

New to Javascript calculations

I'm BRAND new to javascript so this is probably an easy fix I can't figure out.
I'm writing a easy script to calculate age Leapyear, Dog years and plus Five.
var age = prompt ("what's your age?");
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);
JS isn't calculating age + 7. It's writing the age + 7. So if I write 15 in the age prompt it will print in the browser 157.(15) and (7) Which i understand and know why. but how do I get it to compute the math.
It's actually returning 1573.75155
thanks
Like what everyone's been saying, prompt returns a string so it needs to be converted. There are a number of ways to do this, some of which have already been mentioned:
parseInt('123')
parseFloat('123')
Number('123')
These are probably the most common and depending on context also quite possibly the most clear and intuitive ways of doing it. There are also a couple of very terse and interesting ways of converting strings to numbers, depending on which kind of number you'd like. For instance, to convert a number in a string to a float, you can prefix it with the + operator:
+'1.23'
This can seem really counter intuitive, particularly since 4 + '1.23' will actually return 41.23. So what's going on? Well, the + operator, when used as a unary operator (that is, it only has one operand on the right hand side) will always convert the operand value to a number. Compare these two (try them in a javascript console):
4 + '1.23' // returns 41.23
4 + +'1.23' // returns 5.23; the second + is a unary operator
In contrived examples such as this, it really reads rather badly so you might not want to use this trick everywhere. But in your code, it reads quite well:
var age = +prompt("What's your age?")
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
If you understand the workings of the unary plus operator (it really isn't rocket surgery) then you can get some nice terse but quite comprehensible results.
The unary + operator will always convert the value to a Number, i.e. floating point. Now, you might want an integer instead, in which case you can use the bitwise not operator twice, like so:
4 + ~~'1.23' // returns 5; note the double operator
This operator first converts the value to an integer, and then returns the bitwise complement of the value, meaning all the bits are inverted. Using it twice will mean that we get the complement's complement, i.e. the original value but this time as an integer instead of a float.
Hope this was informative!
Right now Javascript handles the input as a string, so age is a string. You're gonna want to convert that to an int using the function parseInt(age).
Official documentation
Also, I'd suggest you read this about types in JS
Use either parseInt(age) or parseFloat(age) depending on whether you want to accept non-integer ages.
Your prompt is returning your number as a string, so when you calculate 15 + 7 it's actually just concatenating "7" on to "15".
You need to convert your string to an number:
var age = prompt ("what's your age?");
age = parseInt(age,10); // Converts to an integer
// parseFloat(age) will allow fractional ages
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);
the age is going to be treated as string so string plus int result in string you have to convert age to int :
var age= parseInt(prompt("what's your age"));
updated...

Preventing concatenation

I've been writing JavaScript on and off for 13 years, but I sort of rediscovered it in the past few months as a way of writing programs that can be used by anyone visiting a web page without installing anything. See for example.
The showstopper I've recently discovered is that because JavaScript is loosely typed by design, it keeps concatenating strings when I want it to add numbers. And it's unpredictable. One routine worked fine for several days then when I fed different data into it the problem hit and I ended up with an impossibly big number.
Sometimes I've had luck preventing this by putting ( ) around one term, sometimes I've had to resort to parseInt() or parseFloat() on one term. It reminds me a little of trying to force a float result in C by putting a .00 on one (constant) term. I just had it happen when trying to += something from an array that I was already loading by doing parseFloat() on everything.
Does this only happen in addition? If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it? I'm using Firefox 6 under Linux to write with, but portability across browsers is also a concern.
The specification says about the addition operator:
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
Which means that if at least one operator is a string, string concatenation will take place.
If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it?
No, all operands have to be numbers.
You can easily convert any numerical string into a number using the unary plus operator (it won't change the value if you are already dealing with a number):
var c = +a + +b;
I normally do this:
var x = 2;
var t = "12";
var q = t+x; // q == "122"
var w = t*1+x; // *1 forces conversion to number w == 14
If t isn't a number then you'll get NaN.
If you multiply by 1 variables you don't know what type they are. They will be converted to a number. I find this method better than doing int and float casts, because *1 works with every kind of numbers.
The problem you are having is that the functions which fetch values from the DOM normally return strings. And even if it is a number it will be represented as a string when you fetch it.
You can use + operator to convert a string to number.
var x = '111'
+x === 111
Rest assured it is very predictable, you just need to be familiar with the operators and the data types of your input.
In short, evaluation is left-to-right, and concatenation will occur whenever in the presence of a string, no matter what side of the operation.
So for example:
9 + 9 // 18
9 + '9' // '99'
'9' + 9 // '99'
+ '9' + 9 // 18 - unary plus
- '9' + 9 // 0 - unary minus
Some ternary expressions:
9 + '9' + 9 // '999'
9 + 9 + '9' // '189'

Categories

Resources