what is the output of console.log(+32)? - javascript

Does javascript skips "+" symbol for certain functions?
Please find the below code
console.log(+32)
Why do we get the output from console as 32?

+ will try parse your variable/value into the number.
So if you want to get +32 in the console, you need to work with strings.
See an example
In the first case variables are concatenated, because one of them is a string.
In the second case, I first parse a into the number with + operator and get the sum of two numbers.
var a = '1';
var b = 2;
console.log(a + b);
console.log( (+a) + b);

Related

JavaScript - Printing two numbers (Not a string) in a single line. Not do the conversion

if I have these variables:
var a = 5
var b = 10
How can I return it in single line with console.log ?
Like this:
5 10
IMPORTANT: But the types must remain as Numbers NOT a String. It is mandatory to have white-spaces between the numbers.
How can I solve it?
If you insist:
console.log(a, b);
Will print your desired output:
5 10
(no explicit string conversion involved)
Not sure what you mean by 'the types must remain numbers' if you are printing to the console...I would just do:
console.log(a + ' ' + b)

how to print "a/b" where a and b are numeric value in JavaScript. I dont want to print the resultant value

how to print "a/b" where a and b are numeric value in JavaScript. I dont want to print the resultant value
if a=5,b=10
Output: 5/10
I know how to solve in Java but in JavaScript the var datatype automatically detect the type of value and perform calculation. Removing the decimal points from the number.
So just add them as strings.
var out = a + "/" + b;
or use toString()
var out = a.toString() + b.toString();

Google Scripts Concatenating rather than adding

When I run my script rather than adding what I think should be two numbers, it concatenates...
I feel like I'm watching that Abbot and Costello bit. https://www.youtube.com/watch?v=9o1SAS8KyMs
var weekNum = e.parameter.weekListBox;
weekNum = weekNum + 3;
weekListBox has the values from 1 to 15.
I am trying to offset it by 3.
However 1 + 3 yields 13, not 4 as I was expecting. Drove me nuts till I realized why this was happening.
So how do I get it to add?
Thanks
It turns out, this is the only solution that worked for me... Very strange problem.
Google Spreadsheet Script getValues - Force int instead of string
Answered by hoogamaphone
You can do this easily using the unary '+' operator as follows:
First get your values from your spreadsheet using getValue() or
getValues(). Suppose you get two such values, and store them in A = 1
and B = 2. You can force them to be recognized as numbers by using any
math binary operator except for +, which concatenates strings, so A -
B = -1, while A + B will return '12'.
You can force the variables to be numbers simply by using the + unary
operator with any variable that might be interpreted as a string. For
example, +A + +B will return the correct value of 3.
The answer above explains the issue but does not provide a solution (except in comments but parseInt() is not the only/best solution).
The reason you have that issue is that the value returned by e.parameter.weekListBox; is actually a string (it is actually always the case except for dates which are date objects) so the result you get is the normal string concatenation (string+number=new string).
One simple solution is to change your code as follows :
var weekNum = Number(e.parameter.weekListBox);// make it a number
weekNum = weekNum + 3;// and the result will be a sum
See
function myFunction() {
var aa = 1;
var ab = aa + 3;
var ba = "1";
var bb = ba + 3;
}
ab = 4
but
bb = "13"

Javascript (+) sign concatenates instead of giving sum of variables

Why when I use this: (assuming i = 1)
divID = "question-" + i+1;
I get question-11 and not question-2?
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
"question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
"question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".
With "question-" + (i+1) it's different:
since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
i is numeric, 1 is numeric, so we'll do addition, resulting in 2
"question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
You may also use this
divID = "question-" + (i*1+1);
to be sure that i is converted to integer.
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;
Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:
i = i + 1;
divID = "question-" + i;
Or you need to specify the number addition like this:
divID = "question-" + Number(i+1);
EDIT
I should have added this long ago, but based on the comments, this works as well:
divID = "question-" + (i+1);
divID = "question-" + parseInt(i+1,10);
check it here, it's a JSFiddle
Another alternative could be using:
divID = "question-" + (i - -1);
Subtracting a negative is the same as adding, and a minus cannot be used for concatenation
Edit: Forgot that brackets are still necessary since code is read from left to right.
Add brackets
divID = "question-" + (i+1);
using braces surrounding the numbers will treat as addition instead of concat.
divID = "question-" + (i+1)
The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
var divID = "question-" + (parseInt(i)+1);
Use this + operator behave as concat that's why it showing 11.
Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
In case of integers, var num = 0;
In case of strings, var str = "";
Even if your i variable is integer, + operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.
- (minus operator) cannot be misunderstood and you will not get unexpected result/s.
One place the parentheses suggestion fails is if say both numbers are HTML input variables.
Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.
Use parseInt(i) than the value of "i" will be casted to Integer.
Than the "+" operator will work like addition.
In your case do this :-
divID = "question-" + parseInt(i)+1;

why do I get 24 when adding 2 + 4 in javascript

I am trying this:
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
But it gives me 24 instead of 6, what am I doing wrong?
You're concatenating two strings with the + operator. Try either:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
or
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
or
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.
Try this:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).
That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.
JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.
Basically there are three primitive data types:
boolean
number
string
null and undefined are two special cases, everything else are just variations of the object type.
JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).
In your example were trying to add two objects of type string, so a concatenation occur.
You can "cast" or type convert the variables to number in many ways to avoid this problem:
var a = "2";
var b = "4";
// a and b are strings!
var sum = Number(a) + Number(b); // Number constructor.
sum = +a + +b; // Unary plus.
sum = parseInt(a, 10) + parseInt(b, 10); // parseInt.
sum = parseFloat(a) + parseFloat(b); // parseFloat.
This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).
The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.
The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.
The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.
You could also force the interpreter to perform arithmetic when dealing with numbers in string forms by multiplying the string by 1 (since multiplication can't be done on a string, it'll convert to a number if it can):
// fun with Javascript...
alert(first * 1 + second * 1);
But it's probably best to go with CMS's suggestion of using Number() to force the conversion, since someone will probably come along later and optimize the expression by removing the 'apparently unnecessary' multiply-by-one operations.

Categories

Resources