what the meaning of plus operator in this JQUERY scripts - javascript

I want to ask mean of plus operator in this script +i+ in the follow:
i=0;
// next line in scripts write this code :
$('.container[data-id='+i+']').hide(); // +i+ what the meaning of it
Need Help thanks a TON

+ is used to concatenate strings
In this case, it is used to concatenate the value of ibetween .container[data-id= and ]
Assuming that i is storing some value eg 0, then this will be evaluated to
$('.container[data-id=0]').hide();

This will concatenate the value in the variable i with the remaining string.
See Concatenating strings

+ is used for string concantination
var test= "hello" + "world";// gives helloworld
it is used for adding values also
var c= a+ b// if a=10 and b=20 it gives 30

The + operator in JavaScript is used for both Arithmetic and String operations.
If both operands are of Number type, the result is the sum. If either of the operands is not a number, then both will be converted to String and concatenated. It should be used with care.

Related

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

What does "= +" do in JavaScript?

Was reading through Douglas Crockford's code here and saw a line
var value = +node.getValue();
but I don't see anything at http://www.w3schools.com/js/js_operators.asp which corresponds to an = + or a way that + can be used as a unary operator. So what does this mean?
The - and + operators are both unary in JS and, before forcing the value's sign, must convert the value to a number.
Obviously - will convert to a number and invert the sign, but + only does the first part. Running +"100" will return the number 100.
This behavior is explicitly stated in the spec at 11.4.6, where the unary + operator is defined:
The unary + operator converts its operand to Number type.
It's just a quick way to make sure the variable is an INT, (vs. a STR or BOOL, e.g.).
Just to add on to what's been said do the following:
var a = +'4';
var b = '4';
console.log(typeof(a));//Number
console.log(typeof(b));//String

JavaScript concating with number as string

Why does x = "1"- -"1" work and set the value of x to 2?
Why doesn't x = "1"--"1" works?
This expression...
"1"- -"1"
... is processed as ...
"1"- (-"1")
... that is, substract result of unary minus operation applied to "1" from "1". Now, both unary and binary minus operations make sense to be applied for Numbers only - so JS converts its operands to Numbers first. So that'll essentially becomes:
Number("1") - (-(Number("1"))
... that'll eventually becomes evaluated to 2, as Number("1"), as you probably expect, evaluates to 1.
When trying to understand "1"--"1" expression, JS parser attempts to consume as many characters as possible. That's why this expression "1"-- is processed first.
But it makes no sense, as auto-increment/decrement operations are not defined for literals. Both ++ and -- (both in postfix and prefix forms) should change the value of some assignable ('left-value') expression - variable name, object property etc.
In this case, however, there's nothing to change: "1" literal is always "1". )
Actually, I got a bit different errors (for x = "1"--"1") both in Firefox:
SyntaxError: invalid decrement operand
... and Chrome Canary:
ReferenceError: Invalid left-hand side expression in postfix operation
And I think these messages actually show the reason of that error quite clearly. )
Because -- is an operator in JavaScript.
When you separate the - characters in the first expression, it's unambiguous what you mean. When you put them together, JavaScript interprets them as one operator, and the following "1" as an unexpected string. (Or maybe it's the preceding "1"? I'm honestly not sure.)
"-1" = -1 (unary minus converts it to int)
So. "1" - (-1)
now, "+" is thje concatenation operator. not -. so JS returns the result 2 (instead of string concat).
also, "1"--"1" => here "--" is the decrement operator, for which the syntax is wrong as strings will not get converted automatically in this case.
because -- is an operator for decrement and cannot be applied on constant values.

How are JavaScript expression evaluated?

In JavaScript, can someone explain the results of the 2 following expressions:
"4" + 4 and 4 + "4"
Thanks!
Both will result in the String:
"44"
This is because the + operator serves 2 purposes -- addition and concatenation. And, if either operand is a String (or is cast to a String by the internal ToPrimitive()) they'll be concatenated.
This is described in the specification as:
7) If Type(lprim) is String or Type(rprim) is String, then
a) Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8) Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
If you want to ensure addition, you can use parseFloat() or the unary + on each:
var a = "4", b = 4;
console.log(parseFloat(a) + parseFloat(b)); // 8;
console.log((+a) + (+b)); // 8, extra parenthesis for clarity
1+'1'+1 = '111'
1+1+'1' = '21'
'1'+(1+1) = '12'
'1'+1+1 = '111'
Javascript performs math until it hits a string and then switches to concatenation, and it also follows regular formula rules run () operations first.
they'll both be '44'. The presence of the '4' as a string casts the whole operation to a string, so the two characters are concatenated.
Cited from: http://javascript.about.com/od/variablesandoperators/a/vop10.htm
One thing that can be confusing to beginners is that JavaScript uses +
with text strings to mean something completely different from what it
means with numbers. While with numbers + means add the numbers
together with text + means concatenate them together. Concatenation
basically means joining one text string onto the end of the first so
that "my"+"book" gives "mybook" as a result. Where beginners tend to
get confused is that while 3+3 gives 6, "3"+"3" gives "33".
You can also use += with text strings to directly add the variable or
text on the right onto the end of the text string variable on the
left.
Mixing Data Types
Additional confusion can arise when you are working with variables
that are of different types. All operations require that the variables
that they are operating on both be of the same type. Before JavaScript
is able to perform any operations that involve two different data
types, it must first convert one of the variables from one type to the
other. You can't add a number to a text string without first either
converting the number to text or the text to a number.
When converting between data types we have two choices. We can allow
JavaScript to do the conversion for us automatically or we can tell
JavaScript which variable that we want to convert.
JavaScript will attempt to convert any text string into the number
equivalent when performing subtraction, multiplication, division, and
taking remainders. Your text string will actually need to contain
something that JavaScript can convert to a number (i.e., a string like
"10") in order for the conversion to work.
If we use + then this could either mean that we want to convert the
string to a number and add then or that we want to convert the number
to a string and concatenate them. JavaScript can only perform one of
these two alternatives. It always converts numbers to strings (since
that will work whether the string contains a number or not).
Here are some examples.
"5" - 3 = 2;
"5" + 3 = "53"
2 + "7" = "27"
5 + 9 + "1" = "141"
Since subtraction only works with numbers 1 converts the text string
into a number before doing the subtraction.
In 2 and 3 the number is converted to a text string before being
concatenated (joined) to the other text string.
In 4 the leftmost addition is done first. Since these are both numbers
they are actually added together and not treated as text. The result
of this first addition leaves us with a similar situation to the third
example and so the result of that addition is converted to text and
concatenated.
To actually force JavaScript to convert a text string to a number we
can use Number("3") or alternatively to force JavaScript to convert a
number to a text string we can use String(5).
Expressions in JS work on two prime principles.
B O D M A(includes concat) S
Left to right order of execution
However, its not straight forward
for + operator
as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.
//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")
console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"
console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.
for all other operators such as -,*,/,^...
if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.
console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000
if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN
console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN

Javascript + operator vs - operator

I am puzzled by this snippet:
var n1 = 5-"4";
var n2 = 5+"4";
alert(n1);
alert(n2);
​I understand that n1 is 1. That is because a minus operator would convert the string "4" into number and subtract it from 5.
But why do we get 54 in case of + operator?
Can someone explain this difference between + and = operators to me?
By type conversion any + expression, that contains a strings, will result in a string. Thus all operands (in your case 5) will be converted to a string, before executing the concatenation.
- on the other hand is just an arithmetic operand, thus "4" is converted to an integer and the calculation is performed as you expect.
It's because in n2, + is being treated as concatenation, not addition. So 5 is converted to the string "5" and "4" is concatenated, giving "54".
When there's a string in either side of +, the + will be considered as a string concatenating operator, the other side will be converted to string and then do the concatenating.
And be careful of something like 1+2+'3', the result is '33' rather than '123'.
- operator has only one meaning - numbers subtraction (or negation and in that case, also conversion to number). In case of + operator, however, there are two: number addition and strings concatenation. When one of the operands of + operator is a string it does string concatenation instead of numbers addition.
The entire process is a bit more complicated than that though and involves an algorithm that you can learn a bit more here, for example.
The + operator is also a string operator. Quite every basic type variable in javascript can be interpreted also in its string representation. You are just attaching 5 to 4 getting 54.
The - operator is not a string operator so the compiler tries to interpret "4" as a number, thus getting 1
Javascript takes 5 as a number and "4" as string.
The javascript + operator use to concat two things.
If you want to addition please use parseInt.
var n1 = 5-"4";
var n2 = parseInt(5)+parseInt("4");
alert(n1);
alert(n2);

Categories