Should literal numbers not have quotes? - javascript

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

Related

Does JavaScript support automatic type conversion?

There are a few expressions that are commonly seen in JavaScript, but which some programming purists will tell you are never a good idea. What these expressions share is their reliance on automatic type conversion — a core feature of JavaScript which is both a strength and a weakness, depending on the circumstances and your point of view.
Type coercion and type conversion are similar except type coercion is when JavaScript automatically converts a value from one type to another (such as strings to numbers). It's also different in that it will decide how to coerce with its own set or rules. I found this example useful because it shows some interesting output behavior illustrating this coercive behavior:
const value1 = '5';
const value2 = 9;
let sum = value1 + value2;
console.log(sum);
In the above example, JavaScript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59. JavaScript had a choice between a string or a number and decided to use a string.
The compiler could have coerced the 5 into a number and returned a sum of 14, but it did not. To return this result, you'd have to explicitly convert the 5 to a number using the Number() method:
sum = Number(value1) + value2;
From an MDN glossary entry I wrote here: https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion edited by chrisdavidmills
Does JavaScript support automatic type conversion?
Yes. It's usually called type coercion, but conversion is perfectly accurate.
For instance:
console.log("Example " + 42);
"automatically" converts 42 (a number) to string. I put "automatically" in quotes because it's done by the + operator, in a clearly-defined way.
Another example is that various operations expecting numbers will convert from string (or even from object). For instance:
const obj = {
valueOf() {
return 2;
}
};
const str = "10";
console.log(Math.max(obj, str)); // 10
console.log(Math.min(obj, str)); // 2
The rules JavaScript uses are clearly and completely defined in the specification. That doesn't prevent people from frequently being surprised by some of them, such as that +"" is 0.

Is using parseInt extraenous if unnecessary?

I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.
var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;
I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?
Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.

Why is number + string a string in javascript?

Sort of trying out some quirks in javascript:
First I did
console.log("5" + 1);
This prints 51, this is normal right, both number and string have a + operator, but since string is the first variable it will convert 1 to a string.
Now when I did this:
console.log(1 + "5")
I expected output to be 6, as I thought it would convert string to a number.
However, the magic output was 15.
Could anyone more experienced in javascript brighten this up for me?
Quoting ECMAScript spec The Addition operator ( + ) section:
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)
So the order doesn't matter here.
console.log(1 + "5")
I expected output to be 6, as I thought it would convert string to a number. ...
But then what would you expect if you had written the following?
console.log(1 + " fine day")
or
console.log(1 + " answer(s) to my question")
There can be no assurance as a general rule that a string is convertible to a number. But any number can be converted to a string. That's why the conversion rules are written to move toward a type that is compatible. (In contexts where you as a programmer know that a string can be safely converted to a number, then you can do so explicitly so that the + operation is between two numbers. But that is not true in general for strings.)
In other contexts, this is also why small ints and low precision floats would be converted to large ints or double precision floats when operating on mixed types that the latter types. You can safely convert the limited forms into the larger forms, but you cannot safely go in the other direction in general. A small int can be represented as a big int or a double, but the other direction is not generally a safe conversion.
So conversion rules for operation on mixed types are written as much as is feasible to move toward mutually compatible types that are safe common types. It is left to the programmer to write explicit conversions for the special cases where a more general type can be safely converted to a more limited type.
In both cases the value will be converted to a string.
When you add a number to a string or a string to a number, the result is a string.
Simply use parseInt(value) or toString(value) to force the conversion.
You can try code :
console.log(1 + parseInt("5"))
=> 6
Concatenation also uses + in Javascript.
var result = "String" + number + obj;
// is equivalent to
string result = "String" + number.ToString() + obj.ToString();
However thing is, in C# / .net you could do the same thing, and you will get the same result - System.Console.WriteLine("result is " + 10 + 20);.
In JavaScript (and C# for that matter) strings are immutable. They can never be changed, only replaced with other strings. You're probably aware that combined + "String" doesn't directly modify the combined variable - the operation creates a new string that is the result of concatenating the two strings together, but you must then assign that new string to the combined variable if you want it to be changed.
The argument about using mathematical operators to do string concatenation is arguably an "incorrect" argument, but there's also an argument to be made that using + to do a lot of string concatenation can be very slow.

Getting the numeric value after the hyphen in a string

How can I extract and get just the numeric value after the hyphen in a string?
Here is the input string:
var x = "-2147467259"
After some processing.... return:
alert(2147467259)
How do I accomplish this?
You could replace away the hyphen:
alert(+x.replace("-", ""));
And yes, the + is important. It converts a string to a number; so you're removing the hypen by replacing it with nothing, and then essentially casting the result of that operation into a number. This operation will also work if no hyphen is present.
You could also use substr to achieve this:
alert(+x.substr(1));
You could also use parseInt to convert the string to a number (which will end up negative if a hyphen is persent), and then find its absolute value:
alert(Math.abs(parseInt(x, 10));
As Bergi notes, if you can be sure that the first character in the string is always a hyphen, you can simple return its negative, which will by default cast the value into a number and then perform the negative operation on it:
alert(-x);
You could also check to see if the number is negative or positive via a tertiary operator and then perform the respective operation on it to ensure that it is a positive Number:
x = x >= 0 ? +x : -x;
This may be cheaper in terms of performance than using Math.abs, but the difference will be minuscule either way.
As you can see, there really are a variety of ways to achieve this. I'd recommend reading up on JavaScript string functions and number manipulation in general, as well as examining JavaScript's Math object to get a feel for what tools are available to you when you go to solve a problem.
How about:
Math.abs(parseInt("-2147467259"))
Or
"-2147467259".replace('-','')
or
"-2147467259".replace(/\-/,'')
#1 option is converting the string to numbers. The #2 approach is removing all - from the string and the #3 option even though it will not be necessary on this example uses Regular Expression but I wanted to show the possibility of using RegEx in replace situations.
If you need a number as the final value #1 is your choice if you need strings #2 is your choice.

why is 10 * (7/10) = 7 in JavaScript?

7 and 10 in the expression (7/10) are integers, so the result 0.7 should be integer as well, which is 0, and the result for the entire expression should be 0 too. However, it's giving me the result of 7, why? Is it ignoring the parentheses or converts to double automatically?
JavaScript doesn't distinguish between integers and floating point numbers, everything I believe is considered a double so that is just why you get the result.
Take a look at the details on the Number property on MDN.
JavaScript doesn't have an integer type, or a double, or a float... it just has 1 type for all numbers: the helpfuly called Number type (try var foo = new Number(7);, or var foo = Number('123string');
Now, I know I said that JS doesn't know of floats, but that's not entirely true. All Number type vars/values are, essentially 64 bit floats, as defined by the IEEE 754 standard (which are, indeed, as Jan Dvorak kindly pointed out to me, double's in most staticly typed languages), with all the caveats that brings with it:
(.1 + .2);//0.30000000000000004
But that's not the point. The point is that, in JS you can perform float + int arithmatic without there ever being a need for internal casts, or conversions. That's why 10*(7/10) will always be 7
There is no int and double in JavaScript
In JavaScript, both int, flot, and double are normalized to work together. They are treated as 1 (They're treated as as Number, which is an IEEE 754 float. Thanks #Elias Van Ootegem). Equality, Liberty and Fraternity. and thus;
10*0.7 = 7
JavaScript is not like C.
Javascript doesn't have integers, and even if it did, there's nothing that says that / needs to return an integer (just because another language may do that doesn't mean every language has to). The operation results in a float/Number, just like all Javascript numbers are, period.
try this
10*parseInt(7/10)
hope this will help you
If you try to follow the rules, then
10 * (7/10) --> 10 * .7 --> 7
You cannot change the way its gonna result into.
so the result 0.7 should be integer as well, which is 0
If you want this, then try using
Math.Floor();
This would change the decimals to the nearest int! Or try out parse()
JavaScript uses dynamic types. That means that a variable like this:
var str = "hi";
Can later become:
str = 123; //now we have an 'int'
str += 0.35; //now str is 123.35, a 'float'
So JavaScript doesn't cast floats to ints for example.
If you want to force a "cast" then you have to do:
var integer = parseInt( 3.14*9.0291+23, 10 ); //the second parameter (10) is the 'base'
But remember, Javascript will not take care of types, that's your problem.

Categories

Resources