Java Script?
Java Script?
Java Script is used in millions of web pages to improve the design, validate forms, detect browsers, create cookies, and much more. Java Script is the most popular scripting language on the internet, and works in all major browsers, such as Java Script is used in millions of web pages to improve the design, validate forms, detect browsers, create cookies, and much more. Java Script is the most popular scripting language on the Internet, and works in all major browsers, such as Internet explorer, fire fox, and opera.
itself does offer a few built*in elements and features that enable 0eb developers to implement interactive functionality in a 0eb page, these features revolve around form submission, and do not, by themselves, offer much opportunity for creating exciting web applications. (n the other end of the spectrum from H !"4s standard text box and radio button, Java and #ctive5 both offer ways to embed small, full*featured programs in the browser window, providing a richer user experience $see sidebar entitled -#n #lternative/ &mbedded objects on the client.%. 6nfortunately, this power comes at the expense of relatively complex programming and heavy re7uirements for memory and processing power on the client. +lient*side script occupy a middle ground between these two extremes, offering a web application with mor functionality than pure H !", but with less complexity and a lower processing load than embedded Java or #ctive5 controls. he next few articles in this series explore the role of client*side scripting in web application introduce some of client*side scripting.
#s an alternative to client*side scripting, modern browsers also support the capability to embed references to precompile software components in a web page. he two primary technologies for this are Java and #ctive5. In both cases, the browser downloads the component to the client computer, where the underlying operating system*or, in the case of Java applets, a runtime environment called Java 8irtual !achine*executes the code. #n additional benefit is that the compiled nature of the components means that the source code is never downloaded to client. his makes it far easier to protect the developer4s intellectual property. 9inally, these components offe increased cross*browser compatibility. he same component should work the same way on any manufacturer4s browser. (n the other hand, this approach suffers from several drawbacks. 9irst, while it was noted that embedded components offer increased cross*browser compatibility, they can exhibit problems with cross*platform compatibility. he same component often works 7uite differently in the same brand or version of browser running on different operating system architectures. In addition, this approach is noted for having performance issues. he additional overhead associated with running components embedded in a web page means that the code might run more slowly.
DA!A !"#ES
DA!A !"#ES Numbers- are values that can be processed and calculated. :ou don4t enclose them in 7uotation marks. he numbers can be either positive or negative. Strings*are a series of letters and numbers enclosed in 7uotation marks. Java Script uses the strings literally; it doesn4t process it. :ou4ll use strings for text you want displayed or values you want passed along. <oolean $true3false%*lets you evaluate whether a condition meets or does not meet specified criteria. 'ull*is an empty value. 'ull is not the same as =>= is a real, calculable number, whereas null is the absence of any value.
E)A*#+E #ny number, such as ?B,C?,or DIeB -Mreetings). or -9un. &ither true or false # special keyword for exactly that*the null value $that is, nothing%
In Java Script, you can express integers in three different bases/ <ase ?= <ase @ $octal%, and <ase ?A $hexadecimal% <ase @ numbers can have digits only up to B, so a decimal value of ?@ would be an octal value of CC. Similarly, hexadecimal allows digits up to 9, where # is e7uivalent to decimal ?= and 9 is ?D. So, a decimal value of ?@ would be ?C in hexadecimal notation. +onverting numbers to different bases table In order to distinguish between these three bases, java script uses the following notation. Speci'(ing bases in a Java Script '6!<&E S:S &! Fecimal $base ?=% (ctal $base @% Hexadecimal $base ?A% 9loating*point values 9loating point values can include a fractional component. # floating*point literal includes a decimal integer plus either a decimal and a fraction expressed as another decimal number or an expression indicator and a type suffix. B.CHID *JI.C CeJ means CK?===LC=== C&*J means CK?3?===L. ==C 9loating*point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator $-e. or -&.%. #s with integers, floating point values can be positive or negative. Strings echnically, a string literal contains Gero or more characters enclosed, as you know, in single or double 7uotes/ -Hello). '( # I(' # normal integer without a leading = $Gero% $i.e., BDC% #n integer with a leading = $Gero% $i.e., =DA% #n integer with a leading =x or =5 $i.e., =xD9 or =5+BC%
$ote: the empty string is distinct from the null value in java script.
$ote: strings are different from other data types in java script. Strings are actually objects. his
will be covered later on. <oolean # <oolean value is either true or false.
$ote: unlike Java, + and other languages, in Java script <oolean values can only be represented
with true or false. 8alues of ? and = are not considered <oolean values in Java Script. 'ull value/ he null value is a special value in java Script. he null value represents just that*'othing. If you try to reference a variable that isn4t defined and therefore has no value, the value returned is the '6"" value. "ikewise, with the prompt $% dialog box, if the user selects the +ancel button, a null is returned. $&xample%
$ote: his is distinct from a value of Gero or an empty string where there is an -actual. value.
he '6"" is indicated in java script by the term null. 'a' $'ot a number% In addition to these values, some functions return a special value called 'a'*which means that the value is not a number, parseInt $% and parse9loat $% are an examples of functions that return 'a' when the argument passed to them cannot be evaluated to a number.
$ote: values can be tested to see if they are 'a' by using the is'a' $% function which returns
true or false based on the nature of the argument passed to the function. +reating 8alues/ In order to make working with the data types useful, you need ways to store values for later use. his is where variables come in. I$!&OD,C!IO$ !O SC&I#!S # client*side script is a program that may accompany an H !" document or be embedded directly in it. he program executes on the client4s machine when the document loads, or at some other time such as when a link is activated. H !"4s support for script is independent of the scripting language. Scripts offer authors a means to extend H !" documents in highly active and interactive ways. 9or example/ Scripts may be evaluated as a document loads to modify the contents of the document dynamically.
Scripts may accompany a form to process input as it is entered. Fesigners may dynamically fill out parts of a form based on the values of other fields. hey may also ensure that input data conforms to predetermined ranges of values, that fields are mutually consistent, etc. Scripts may be triggered by events that affect the document, such as loading, unloading, element focus, mouse movement etc. Scripts may be linked to form controls $e.g., buttons% to produce graphical user interface elements.
here are two types of scripts authors may attach to an H !" document/ hose that are executed one time when the document is loaded by the user agent. Scripts that appear within a S+EIO element are executed when the document is loaded. 9or user agents that cannot or will not handle scripts, authors may include alternate content via the '(S+EIO element. hose that are executed every time a specific event occurs. hese scripts may be assigned to a number of elements via the intrinsic event attributes.
If you are accepting3using this page4s +SS style suggestions the type of the values at various stages is illustrated by the colour of the text used. he following key shows those type3colour relationships, they are derived from the string values returned by the typeof operator $which returns -object. for the null type when in reality null is distinct from objects%.
.E"
String 'umber <oolean (bject 9unction 'ull 6ndefined Converting to String: #s mentioned above, type conversion to a string most often results from the action of the , operator whenever one of its operator is not a number. he easiest way of getting the string that results from type*conversion is to concatenate a value to an empty string. hat techni7ue has been used to generate the following tables. #n alternative method of converting a value into a string is to pass it as an argument to the string constructor called as a function/* 8ar stringvalueLstring $x%; ype*convert to string $- - , col%/ numeric values. - - , +ol *?.A *= *?.A = ,= ? = ? ?.A ?.A @ ?A ?A.@ @ ?A ?A.@ ?CJe*C *infinity ?.CJ *infinity ,infinity 'a' ,infinity 'a'
'otice that the number generated from the source code ?CJe*C has resulted in the string -?.CJ. because that is the string representation of the internal number created from the source code. However, Java Script4s internal number representations take the form of I&&& double precision floating point numbers and that means that they cannot represent all numbers with precision. he results of mathematical operations may only produce close numbers with precision. he results of mathematical operations may only produce close approximations and when they are converted
to strings the string represents the approximation and may be unexpected and undesirable. It is often necessary to use custom functions to generate string representations numbers in an acceptable format, the type*conversion mechanism is rarely suited to generating numeric output intended for presentation. ype*convert to string $- - , col%/ other values. - - , +ol 6ndefined undefined null null true true false false new object $% Robject objectS function return $% Preturn;Q function return $% Preturn;Q
0hen objects or functions are type*converted to strings their tostring method is called. hese default to object.prototype.tostring and function.prototype.tostring but may be overloaded with a function assigned to a -tostring. property of the object3function. ype*converting a function to a string does not necessarily results in the function4s source code. he behavior of function.prototype.tostring is implementation depended and varies 7uite a lot, as do the results from -host objects. and methods $the objects and methods provided by the environment, such as F(! elements%. Converting to $-mber: +onverting values to numbers, especially strings to numbers, is an extremely common re7uirement and many methods can be used. #ny mathematical operator except the concatenation3addition operator will force type*conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting Gero or multiplying by ?. 8ar numvalue L stringvalue * =; 3K or K3 8ar numvalue L stringvalue K ?; 3K or K3 8ar numvalue L stringvalue 3?; However, the unary , operator also type*converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type*converting a string into a number. Incidentally, the unary* $minus% operator also type*converts its operand $if necessary% in addition to subse7uently negating its value. 8ar numvalue L $, stringvalue%; 3K he preceding unary , expression has been parenthesiGed. hat is unnecessary but is often felt to make the code easier to comprehend and make it clear which operations are being applied. &specially avoiding confusion with pre and post increment and addition operations. +ompare/ * 8ar n L any'um8ar,, , ,stringvar , ,,another'um8ar; * with T 8ar n L $any'um8ar,,% , $,stringvar% , $,,another'um8ar%; $Oost increment% , $unary plus% , $pre increment%
K3 0hile unary , is the fastest method for converting a string to a number a final method is available that uses the java Script type*conversion algorithms. he number constructor can be called with the string value as its argument and its return value is a number representing the result of the type*conversion. 8ar numvalue L number $stringvalue%; he number constructor is the slowest of the type*converting methods but when speed is not an overriding consideration its use does produce the same results as they all use exactly the same algorithm to do the conversion. ype*convert to number $,col%/ string values. --* -= -? -?.A -@ -?A -xx $empty ?.A. string% , col = 'a' *?.A = ? ?.A @ ?A -=K?= -=?=. $(ctal% $Hex% -=K9 9. $Hex% =?=.
-?A.@ -
-?CJe* C.
-*
-* =K?=. -
?A.@
?.CJ
?=
?A
CDD
*?=
'a'
he important considerations when converting strings to numbers with the type*converting methods is the results from the strings that do not represent numbers. he empty string is converted into the number Gero, depending on the application this can be harmless or disastrous, but it is important to be aware that it is going to happen. In other context the string that follow the java Script format for octal number $leading Gero% can be problematic but type*conversion treats them as base ?= anyway. However, strings that follow the format for hexadecimal numbers $leading =x or =5% are read as hexadecimal. Strings that cannot be read as number type* convert to 'a', which can be tested for with the is'a' function. Strings representing numbers in an exponential format $-?CJe*C.% are understood along with leading minus signs. ype*convert to number $,col%/ other values. ,nde'ined n-ll tr-e 'alse new ob ect /0 '-nction /0 1ret-rn23
(bjects and functions always type*convert to 'a' numbers, as do undefined values but it is worth nothing that null type*converts to Gero. Orobably it is being type*converted to <oolean first and then to number and, as is clear from the <oolean results above, null would become <oolean false which would then become numeric Gero. here is almost no need to type*convert these types of values into numbers. How they convert is only really relevant to a consideration of the accidental result of converting a value that is expected to be a string but actually turns out to be one of these $and3or performing a mathematical operation with one of these as an operand%. #arsing to $-mber: #n alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number. he parsefloat function accepts a string argument and returns a floating point number resulting from parsing that string. 'on*string arguments are first type*converted to a string as described above.
he string parsing functions read the string character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the character that they have seen that can be part of the number. #arse4loat: 0ith parsefloat empty strings return 'a' along with strings that cannot be subject to numeric interpretation. he exponential format is understood and the leading Gero in the octal format does not hinder the string4s interpretation as a decimal number. 'on*string values are first converted into a string that is employed by parsefloat. #s that type*conversion to a string would normally result in a string that could be interpreted as a number the result is 'a'. #arseInt: he parseint function works in a similar way to parsefloat except that it is trying to interpret its string argument into an integer and as a result recogniGes fewer character as parseint is occasionally used as a means of turning a floating point number into an integer. #lso, because of the number format used by java script, numbers are often represented by near approximations. So, for example, ?KC,?KJ,?KJL=.HHHHHHHHHHHHHHHHH, which isn4t 7uite one and parseint would return Gero if asked to act on the result of the operation. 9or rounding numbers to integers one of math.round, math.ceil and math.floor are preferable, and for a desired result that can be expressed as a JC bit signed integer the bitwise operation described below might suit. Oarseint$col%/ other values parseInt $col% 6ndefined 'a' null true 'a' false 'a' new object $% 'a' function $% P return;Q 'a'
#s parseInt type*converts its non*string arguments to strings it always produces the same results for <oolean, null, undefined, object and function arguments as parse9loat $assuming objects and functions do not have custom tostring methods%.
JavaScript #rrays/
6sing arrays in javascript #rrays are one way of keeping a program more organiGed. hey allow you to do some things that are difficult without them. #rrays are usually a group of the same variable type that uses an index number to distinguish them from each other. Suppose you wanted to write out D 7uotes, and use variables for each one of the 7uotes. :ou could define D variables/ 7uote ? L -I like JavaScript..; 7uote C L -I used to like JavaScript..; 7uote J L -JavaScript rules..; 7uote I L -Help) JavaScript &rror)..; 7uote D L -Just Uidding..; However, a better way may be to use an array. o define an array, we need to follow the following form/ 8ar 'ameVofV#rrayL new #rray $numberVofVelements%; 'maeVofV#rray would be the name you want to give the #rray variable, the numberVofVelements is the number of variables you want the #rray to store. So, far our 7uotes, we could write/ 8ar 7uoteL new #rray $D%