# regarding this expression in java script for webprogramming

Status
Not open for further replies.

#### softech2608

##### Newbie level 1
it will use alart to display square of number
n is the number eg 10 means alert will display 1....10 squares
var s=0;
for(i=1;i<=n;i++)
{
var s;
s=s+i+"-"+i*i+"\n";
}alert("the squares roots of number n are as follows \n"+s);

the bolded protion i could not understand plz help me

#### arthur0

##### Full Member level 2
Re: regarding this expression in java script for webprogramm

Hi.
The thing with JavaScript (as well as VBscript) is that is weakly-typed, so you can mix different types together without bothering too much about conversions and such, since that’s taken care of by the execution engine.

In this particular case, the variable s is not even typed until is assigned values. Depending on what values it takes, it will be promoted (converted) to more complex types (first integer, then string etc.) as the need arises. Since you have strings in the mix (such as "-" and "\n", as opposed to '-' and '\n', which are individual characters), s will be promoted to string in the first iteration, so the + operator will concatenate strings instead of adding numbers (being overloaded by the underlying string class to do just that).

Thus, the assignments in the first two iterations are equivalent to:
Code:
s = "\0" + "1" + "-" + "1" + "\n";		// or "1-1\n"
s = "1-1\n" + "2" + "-" + "4" + "\n";	// or "1-1\n2-4\n"
and so on.

(As a remark, note that the declaration of var s inside the for-loop is meaningless and you can remove it.)

Arthur

Status
Not open for further replies.