i want to concatenate two string in javascript i.e.
$('#bio').css('font-color', result.titlecolor);
but i want to put the character # before the result.titlecolor i.e.
$('#bio').css('font-color','#' result.titlecolor);
is this right or wrong? thanks
$('#bio').css('color','#' + result.titlecolor);
(Edited to reflect #BoltClock's comment about 'color' versus 'font-color'.)
This:
'#' result.titlecolor
needs to be:
'#'+ result.titlecolor
In javascript the + operator concatenates to strings together (but remember strings are immutable, so you are creating a new string when you use it). It will also allow you to contatenate a string and a non-string together into a string, such as a number and a string. So this "The answer is : " + 42 becomes "The answer is : 42" The tricky part comes in because if you try and concatenate to numbers together such as 14 + 08, you don't get "1408" it adds the two numbers together to become 22. Logically this makes sense on a simple example, but it can become troublesome when are concatenating variables together which are loosely typed.
$('#bio').css('font-color', '#' + result.titlecolor);
$('#bio').css('font-color','#' + result.titlecolor);
The + operator serves as both the addition operator and string concatenation operator in JavaScript. So:
1 + 1 // is 2
'The answer is: ' + 42 // is 'The answer is: 42'
'1' + '1' // is '11' (!!!)
'1' + 1
1 + '1' // are also '11' (!!!!!)
As for your code, the CSS specification defines color but not font-color, so this is what you want:
$('#bio').css('color', '#' + result.titlecolor);
As a side note, if you ever run into the '1' + '1' or 1 + '1' problem (e.g. you are taking a numeric value from a text box), you have to convert the operands to numbers using the unary plus operator or the parseFloat function:
+'1' + +'1' // is 2
Related
When I have one plus, I get the wrong answer e.g.
var b = [069];
var total = 0;
total = total + b
console.log(total) // total = 069
However, when I add a second plus so the equation looks like this
total = total + + b // total = 69
I get the correct answer of 69. The above is just a simplified example of my issue.
This works fine, however whilst using JSHint I get a warning saying
confusing pluses
How can I get the correct answer without using the + + ? Also, what is this operator called?
Javascript unfortunately does a lot of implicit conversions... with your code
b + [69]
what happens is that [69] (an array containing the number 69) is converted to a string, becoming "69". This is then concatenated to b that also is converted in this case to a string "0". Thus the result "069".
If however you add another unary + in front of the array the string gets converted back to a number and you get a numeric result added to b.
0 + [69] → 0 + "69" → "0" + "69" → "069"
0 + + [69] → 0 + + "69" → 0 + 69 → 69
Exact rules are quite complex, but you can be productive with Javascript just considering the simplified form that for binary +:
if both are numbers the result is numeric addition
otherwise they're converted both to string and result is concatenation
One thing that is somewhat surprising is that implicit conversion of an array to a string is just the conversion of elements to string adding "," between them as separator.
This means that the one-element array [1] is converted to "1"... and implies apparently crazy consequences like [1] == 1.
Posting my comment as an answer
+ in front of a variable would cast it to a number if I'm correct.
Try this in your console:
"5" would return "5" (string), where
+"5" would return 5 (number).
You could use total = parseInt(total) + parseInt(b); to get a correct result, as parseInt() would try to make a number out of any input parameter it gets.
Theoritecally, you could just parse the total as a number, but it would be prone to an error like "1" + "0" = "10" resulting in 10, which should mathematically be 1.
I tried something in my console that I don't quite comprehend.
If you add 2 + 3 + "hello" it concatenates to "5hello"
However, if you reserve this and add 'hello' + 2 + 3 it concatenates to 'hello23'
Why? My guess is because JavaScript looks at the first data type and tries to convert it to that type? Can someone elaborate on this?
Addition (and other associative operators) are processed in order, left-to-right. So
2 + 3 + "hello"
is like writing
(2 + 3) + "hello"
or
5 + "hello"
first the addition, then the conversion/concatenation. On the other hand,
"hello" + 2 + 3
is like:
("hello" + 2) + 3
which works out to
"hello2" + 3
or
"hello23"
Simple order of operations really:
2 + 2 + "hello" //2 + 2 is evaluated first, resulting in 4. 4 + "hello" results in "4hello";
"hello" + 2 + 3 //"hello" + 2 is evaluated first, turning the result to a string, and then "hello2" + 3 is done.
As I understand it, 2 + 2 + "hello" is evaluated this way:
Find any operators and push them on the operator stack: stack: +, +
Find any symbols and push them on the operand stack: stack: 2, 2, "hello"
Take the first operator from the operator stack and
the first 2 operands from the operands stack, do: 2 + 2 = 4
Take the first operator and the first 2 operands, do: 4 + "hello"
= "4hello"
Mind you, JS automatic type conversion works this way with the + operator (which is both addition and concatenation), it may (and does) work differently in other places. 4 - "hello" will make no sense and "0" == true will evaluate to false whereas 0 == '' stands. This is one of the reasons Javascript is one of the most beloved languages of today.
This occurs due to the coercion. Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand type. The operand to take into account depends on the hierarchy of "data-type" (though JavaScript is typeless) and the operations are executed from left-to-right. For instance:
//from left to right
2 + 3 + "hello"
//performs the addition, then does coercion to "string" and concatenates the text
(2 + 3) + "hello"
this results in "5hello"
In counterpart
//from left to right
'hello' + 2 + 3
//string concatenation is the first, all subsequent values will do coercion to string
"hello23"
Unless you use parentheses, which takes higher precedence
'hello' + (2 + 3)
It returns "hello5"
I am trying to alert the following,
1. alert(1+1+1+1+1);
//output: 5
2. alert('1'+1+1+1+1);
//output: 11111
3. alert(1+1+1+1+'1');
//output: 41
4. alert(1+1+'1'+1+1);
//output: 2111
Does anyone can explain about the type of message in alert ?
Thank you in Advance.
Alright so in javasciprt, number + number + number = number (Your case 1)
Whereas, a number after string concatenates with the String, and results in a string as output '1'+1 = '11' + 1 = '111' and so on. (Your case 2)
In the third case, the string just comes at the end of the number which get's casted to string and result will simply be number followed by string in string form.. 2+'432' = '2432'.
Last case is the mix of all the above 1+1 = 2 + '1' = '21'+1 = '211'+1 = '2111'.
Javascript is a weakly typed language with operator overloading. That is why you are getting those 'strange' behaviours.
Wow, operator overloading. huh?
The + in javascript has multiple functions. One being: adding up numbers and another one is concatenating strings together. this is called operator overloading. compared to PHP, adding up numbers is + but concatenating strings is .
The big problem with operator overloading is. What if we have String + Number. Or Number + String ?
Different rules apply:
1+1+1+1+1
This is easy, adding up 5 numbers.
'1'+1+1+1+1
This is harder one. What he sees is a String, so he concatenates it with the next part (the 2nd 1). Then he continues. String(11) + 1, gives String(111) and so on.
The 3rd example is fun. he starts adding up all the numbers, untill he reaches the last + sign. And it no has Number(4) + String(1). So he converts the Number to a string and Concatenates them together.
Same goes for the last example. If one of the two is a String, the + sign is interpreted as a Contatenation.
I was reading w3school's Automatic type conversion and I think this is relevant from your question.
It says:
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
It says that the result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 1 // returns "51" because 1 is converted to "1"
"5" - 1 // returns 4 because "5" is converted to 5
I need the two numbers to be added but somehow they are concatenated. Where am I doing it wrong?
var a;
var b;
var parsedInta;
var parsedIntb;
a=window.prompt("enter your first number");
b=window.prompt("enter your second number");
parsedInta=parseInt(a);
parsedIntb=parseInt(b);
alert("The Sum is" + parsedInta+parsedIntb);
It concatenates the result rather than addition.
You have to introduce parentheses to force the numeric addition to happen before the alert string is built:
alert("The Sum is " + (parsedInta + parsedIntb));
Without the parentheses, the + operator is naturally left-associative, so the first "addition" carried out is the string concatenation between "The Sum is" and the first value (which is treated as a string).
edit — note that the + operator prefers string concatenation over numeric addition. If either operand of + is a string, then the other operand is converted to a string and the two are concatenated.
This is beacuse the + operator is used also to do string concatenation. Since in your "The Sum is" + parsedInta+parsedIntb you are working with a string the language thinks you want to use parseinta and parseintb as strings.
You can solve by simply doing the sum before the string creation:
var sum = parseInta + parseIntb;
alert("The Sum is" + sum);
Or also by using parseInt directly in the sum line:
var sum = parseInt(a) + parseInt(b);
alert("The Sum is" + sum);
The probleme is that you are doing implicit type casting using "+" operator which will convert the number to string so your code will be like :
alert("the sum is "+number1+number2); //The number 1 will be converted to a string
,the same for the second number
So if i enter 10 in the first prompt and 10 in the second prompt the alert will show : the sum is 1010 because the first 10 is converted to a string and the second 10 will be converted to a string
But if i use parenthese like :
alert("the sum is "+(number1+number2));
Here the two number will be added and it will be coverted to a string after the addition.
P.S : don't use window object because it's a global object so you can ignore it
And sorry for my bad english i hope that you will understand
This is JavaScript. Don't expect the language to make sense.
This is because the + operator is overloaded for strings. If either of its operands is a string, + will turn the other operand into a string and concatenate them.
Since this awful operator is also left-associative, you will get
("The Sum is" + parseInta) + parsedIntb
which is a string plus a number (which is a string) plus a number, which is also a string.
Parenthesize the rightmost addition instead:
alert("The Sum is" + (parsedInta + parsedIntb));
And maybe consider starting to learn programming with a sane language.
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