understanding javascript typeof date behaviour - javascript

Here's the code :
var d = new Date();
console.log(typeof(d+1)); //string
console.log(typeof(d-1)); // number
why does it produce different results?

(date + 1) returns a string, because of string concatenation
(date - 1) returns a number because of type conversion
Basically, a string plus a number returns a string with a number appended to the end. This is because the + operator is used to concatenate strings.
On the other hand, when you subtract a number from a string, JavaScript performs automatic type conversion.
Form more information, look here
http://www.w3schools.com/js/js_type_conversion.asp

Related

Javascript - parsing a hex value

I am trying to parse a hex value to decode a card
The hex data I receive from the card is f8b2d501f8ff12e0056281ed55
First I am converting this to an integer with parseInt()
var parseData = parseInt('f8b2d501f8ff12e0056281ed55', 16);
The value recieved is 1.9703930145800871e+31
When I try to decode this using the bitwise operator in Javascript
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
I received a 0 value.
What am I doing wrong here, how can I parse the value of such large integer number?
There are two ways to do it:
First, notice that & 0xFFFFF operation in your code is just equivalent to getting a substring of a string (the last 5 characters).
So, you can just do a substring from the end of your number, and then do the rest:
var data = 'b543e1987aac6762f22ccaadd';
var substring = data.substr(-5);
var parseData = parseInt(substring, 16);
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
document.write(cardNumber);
The second way is to use any big integer library, which I recommend to you if you do any operations on the large integers.
Since the number integer is so big you should use any bigNum library for js.
I recommend BigInteger, since you are working only with integers and it supports bitwise operations, however you can also check this answer for more options.

Javascript adding numbers as if they were a string [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.
Example:
I have a cookie called value, and when I want this value I use a script I found by Jeffery To that looks like this:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this: value + 1 = 10. Simple math. However it gives me this 91. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?
Solution
After reading the comments I learned that i needed to put my value inside a parseInt(). So i simply modified the funtion to say:
function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);
}
The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.
The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.
To force a string containing a number character into a number, you can use parseInt() and parseFloat():
var result = parseInt(value, 10) + 1;
Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.
Also note that both parseInt() and parseFloat() stop after finding the first non-valid characters that can't be treated as numbers. So, in a string like this: "Scott7Marcy9", you would get NaN.
Cookies are saved as string values as you guessed. To get your desired effect, you're going to need to parse your value. If you are absolutely sure it will be an integer, use:
parseInt(value) + 1

Unexpected Javascript Date object implicit conversion

Why Javascript's Date object returns different value for implicit conversions?
Number conversion:
+new Date()
// returns 1456293356618 as expected
String conversion:
''+new Date()
// returns "Wed Feb 24 2016 09:26:28 GMT+0" but "1456293356618" as a string was expected
Where can I find the documentation on ECMAScript and the implementation on v8's source?
Edit: I'm not looking for the solution for the expected result. I want to find the documentation in the specs.
The + operator is overloaded. In:
+new Date()
it is treated as the unary + operator and coerces the value to Number. In:
'' + new Date() // note one value is a string
it is treated as the string concatenation operator and coerces the values to String. In:
5 + 6 // note both values are number
it is treated as the addition operator. Since the values are numbers, no coercion is necessary.
Note that whether + does addition or concatenation depends on the values and is described in ECMAScript 2015 ยง12.7.3.1 step 11.
I think you are refering to this Overview of Date Objects and Definitions of Abstract Operators, specifically Section 20.3.1.1
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.
This means that using math operations on a Date object will extract its Number value to work. That's why statements like +new Date() and Math.floor(new Date()) returns a Number.
As for '' + new Date(), the Date object returns its String value perhaps using its toString() function.

Typeof Expressions (Number )

The following expressions give peculiar result in JavaScript.
typeof (5 + "7") // Gives string
typeof (5 - "7") // Gives number
How do I get the result of the first expression as a number type?
Is there any way to do that without explicitly converting 7 to a number?
Please clarify.
Try this way parsing string to integer first. You can parse string implicitly with + or parse to integer with parseInt.
typeof (5 + +"7")
or
typeof (5 + parseInt("7"))
Yes, there is a way to do that without explicitly converting the string to a number, and that is by implicitly converting the string. You can for example use the + operator, which will cause an implicit conversion of the string to a number, as it can only be applied to a number:
typeof (5 + +"7")
That's not very readable code, though. You are better off with an explicit conversion:
typeof (5 + parseFloat("7"))
The only way you'd be able to so that is by converting the string to a number
typeof (5 + parseInt("7"))
N.b. that's if you are using the plus operator, multiply/divide/minus work differently and will convert the string type to a number (unless NaN)
The plus sign in javascript adds numbers together, but it also concatenates strings, and when one of the values being added together is a string, the latter is done, regardless of what the other values are.
The minus sign subtracts, and you can't subtract a string from a string, so it's only meaning is to subtract numbers
So in other words
5 + "7" === "57" // string
5 + 7 === 12 // number
5 - "7" === -2 // number
so no, you'd have to convert the string to a number to be able to add it to another number
5 - ( parseInt("7", 10) ) === -2 // number
5 - ( +"7" ) === -2 // number

JS documentation of numerical syntax

I have seen a syntax such as the following before:
var mynum = new Number();
var temp = (+mynum); //this line is what i am curious about
var text = temp.toPrecision(3);
Can anyone tell me what this + syntax means?
What I have found is that in some JS implementations, it is somehow necessary as it ensures that the number defined in mynum is valid.
Thanks,
jml
+ is a unary operator which is used to coerce data types into numbers. Unary meaning it only needs one operand.
new Date returns an object, applying + coerces it into a timestamp eg 1277504628812
new Number returns an object, applying + coerces it into the numeric literal 0.
See: http://bclary.com/2004/11/07/#a-11.4.6
This is the ECMAScript documentation, which is the subset of Javascript, in HTML format.

Categories