Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Javascript: Advantages

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Javascript

Advantages:
JavaScript effects are also much faster to download than some other front-end technologies like Flash and Java applets. In fact, unless you're writing a massive JavaScript application, it's quite likely that no significant extra download time will be added to a page by using JavaScript on it. Nor do users need to download a plugin before they can view your JavaScript, as they would with Flash for example, they simply need a browser that supports it - and, of course, most modern browsers do. Other advantages include the fact that you don't need any extra tools to write JavaScript, any plain text or HTML editor will do, so there's no expensive development software to buy. It's also an easy language to learn, and there's a thriving and supportive online community of JavaScript developers and information resources.

Disadvantages:
While the advances in browser programmability we've seen over recent years are, generally speaking, a good thing, if you don't implement them with care you can create a lot of inconsistencies and broken pages quite unintentionally using JavaScript. Code that works just great on IE4 might not work at all on Netscape 4, what works in NN6 doesn't always work in NN 4, and so on. In essence, there are two main problems with JavaScript and browsers: The different JavaScript versions in different browsers. Browser programmability: the HTML elements and features of the browser that can be accessed through any scripting language. (IE4 , for example, makes most of the page and HTML accessible to scripts, but Navigator 4 limits what can be accessed and manipulated.)

Features:
Handles Dynamic Effects: JavaScript is such a powerful scripting language which has features to achieve dynamic effects in web pages. Using the features available in JavaScript, the designer can decide to have dynamically placed text at run time.

Saves Time: JavaScript also has the feature of validating data submitted at the client level. This helps in saving the processing time of the server because JavaScript initially creates the validation on the client side.

DOM: Client side JavaScript is embedded inside HTML This embedded JavaScript is used along with DOM (Document Object Model) for control over the browser by means of objects.

Popular Scripting language: JavaScript has simple rules and procedures that make it easier to use and learn for programmers. This has made JavaScript a popular client-side scripting language.

Interpreted Language: It is an interpreted language, meaning that it can be used or executed with ease without precompilation.

Javascript syntax: <script type=text/javascript> Document.write(Hello javascript); </script>

Data types:
The JavaScript language provides a handful of primitive data types. Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries.

Null

Unlike undefined, null is often set to indicate that something has been declared but has been defined to be empty. In a Boolean context, the value of null is considered a false value in JavaScript. alert(null == undefined); // unenforced type during check, displays true alert(null === undefined); // enforce type during check, displays false

Number Numbers provides an accuracy to about 14 or 15 significant digits JavaScript, Numbers. Because they are floating point numbers, they do not always exactly represent real numbers, including fractions. alert(0.94 - 0.01); // displays 0.9299999999999999 345; // an "integer", although there is only one numeric type in JavaScript 34.5; // a floating-point number 3.45e2; // another floating-point, equivalent to 345 0377; // an octal integer equal to 255 String A String in Javascript is a sequence of characters. Strings in JavaScript can be created directly by placing the series of characters between double or single quotes.
var greeting = "Hello, world!"; var another_greeting = 'Greetings, people of Earth.';

Boolean JavaScript provides a Boolean data type with true and false literals. The typeof operator returns the string "boolean" for these primitives.
/ Automatic type coercion alert(true == 1); // true.... Only 0 and NaN are false Numbers. alert(true == "0"); // true.... Only the empty String is false.

Operators
The '+' operator is overloaded; it is used for string concatenation and arithmetic addition and also to convert strings to numbers. It also has special meaning when used in a regular expression.

// Concatenate 2 strings var a = 'This'; var b = ' and that'; alert(a + b); // displays 'This and that' Arithmetic JavaScript supports the following binary arithmetic operators: + * / % Addition Subtraction Multiplication Division (returns a floating-point value) Modulus (returns the integer remainder)

JavaScript supports the following unary arithmetic operators: + Unary conversion of string to number - Unary negation (reverses the sign) ++ Increment (can be prefix or postfix) -- Decrement (can be prefix or postfix) var x = 1; alert( ++x ); // displays: 2 alert( x++ ); // displays: 2 alert( x ); // displays: 3 alert( x-- ); // displays: 3 alert( x ); // displays: 2 alert( --x ); // displays: 1 Assignment = += -= *= /= %= Assign Add and assign Subtract and assign Multiply and assign Divide and assign Modulus and assign

var x = 1; x *= 3; alert( x ); // displays: 3 x /= 3; alert( x ); // displays: 1 x -= 1; alert( x ); // displays: 0

Comparison == Equal != Not equal > Greater than >= Greater than or equal to < Less than <= Less than or equal to === Identical (equal and of the same type) !== Not identical Logical JavaScript provides four logical operators: * unary negation (NOT = !a) * binary disjunction (OR = a || b) and conjunction (AND = a && b) * ternary conditional (c ? t : f) In the context of a logical operation, any expression evaluate to true except the following: * Strings: "", '', * Numbers: 0, NaN, * Special: null, undefined, * Boolean: false, !true. The Boolean function can be used to explicitly convert to a primitive of type Boolean: // Only empty strings return false alert( Boolean( "" ) === false ); alert( Boolean( "false" ) === true ); alert( Boolean( "0" ) === true ); alert( Boolean( null ) === false ); alert( Boolean( undefined ) === false ); // equivalent to Boolean() The NOT operator evaluates its operand in as a Boolean, and returns the negation. Using the operator twice in a row, as a double negative, explicitly converts an expression to a primitive of type Boolean: alert( !0 === Boolean( !0 ) === !!1 === Boolean( 1 ) === true ); alert( !!0 === Boolean( 0 ) === !1 === Boolean( !1 ) === false ); alert( !"" === Boolean( !"" ) === !!"s" === Boolean( "s" ) === true ); alert( !!"" === Boolean( "" ) === !"s" === Boolean( !"s" ) === false );

Bitwise JavaScript supports the following binary bitwise operators: & And | Or ^ Xor << Shift left (zero fill) >> Shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left. >>> Shift right (zero fill) For positive numbers, >> and >>> yield the same result. JavaScript supports the following unary bitwise operators: ~ Not (inverts the bits)

String = Assignment + Concatenation += Concatenate and assign Examples str = "ab" + "cd"; // "abcd" str += "e"; // "abcde" str2 = "2"+2 Variables Variables in standard JavaScript have no type attached, and any value can be stored in any variable. Variables can be declared with a var statement. An identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
x = 0; // A global variable var y = 'Hello!'; // Another global variable function f(){ var z = 'foxes'; // A local variable twenty = 20; // Global because keyword var is not used

// "22", not "4" or 4.

return x; // We can use x here because it is global }

Functions
A function is a block with a (possibly empty) parameter list that is normally given a name. A function may utilize local variables. If you exit the function without a return statement, the value undefined is returned.
function gcd(segmentA, segmentB) { var diff = segmentA - segmentB if (diff == 0) return segmentA if (diff > 0) return gcd(segmentB, diff) else return gcd(segmentA, -diff) } alert(gcd(60, 40)); // 20

The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined. Within the function, the arguments may also be accessed through the arguments object.

Conditional statement
Compound statements A pair of curly brackets { } and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
If ... else
if (expr) { //statements; } else if (expr2) { //statements; } else { //statements; }

Conditional operator The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the if statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what if is to statements.
var result = (condition) ? expression : alternative;

is the same as:


if (condition) { result = expression; } else { result = alternative; }

Unlike the if statement, the conditional operator cannot omit its "else-branch". Switch statement The syntax of the JavaScript Switch statement is as follows: switch (expr) { case SOMEVALUE: //statements; break; case ANOTHERVALUE: //statements; break; default: //statements; break; } break; is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block. Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later. Strings literal values can also be used for the case values. case default: is optional Braces are required.

Loops
For loop The syntax of the JavaScript for loop is as follows:
for (initial;condition;loop statement) { /* statements will be executed every time the for{} loop cycles, while the condition is satisfied */ }

or
for (initial;condition;loop statement) // one statement

For ... in loop The syntax of the JavaScript For ... in loop is as follows: for (var property_name in some_object) { //statements using some_object[property_name]; } Iterates through all enumerable properties of an object. Sources differ on whether this is usable for arrays. There are differences between the various web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using if (some_object.hasOwnProperty(property_name)) { ... } While loop The syntax of the JavaScript while loop is as follows:
while (condition) { statement1; statement2; statement3; ... }

Do ... while loop The syntax of the JavaScript do ... while loop is as follows:

do { statement1; statement2; statement3; ... } while (condition);

With The with statement sets the default object for the set of statements that follow.
with(document) { var a = getElementById('a'); var b = getElementById('b'); var c = getElementById('c'); };

Array
An Array is a native JavaScript type specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (e.g., join, slice, and push).

myArray = [0,1,,,4,5]; // array with length 6 and 6 elements, ... // ... including 2 undefined elements myArray = new Array(0,1,2,3,4,5); // array with length 6 and 6 elements myArray = new Array(365); // an empty array with length 365

properties of array object: constructor -Refers to the constructor function used to create an instance of an object index -Used when an array is created by a regular expression match input -Used when an array is created by a regular expression match length- Contains a numeric value equal to the number of elements in an array prototype- Allows the addition of properties and methods to objects such as the JavaScript Array object Methods of array object: concat() - Combines the elements of two or more arrays into one new array join() - Combines the elements of an array into a single string with a separator character pop() - Removes the last element from an array and then returns the removed element if needed push() - Adds elements to the end of an array and then returns the numeric value of the new length of the array if needed reverse()- Reverses the direction of the elements in an array: the first element is moved to the last slot and the last element is moved to the first slot, and so on

Document Object Model (DOM)


The document object is an object that is created by the browser for each new HTML page (document) that is viewed. By doing this, JavaScript gives you access to a number of properties and methods that can affect the document in various ways Properties of DOM: activeElement - Returns a string holding the value of the active element in the document alinkColor - Returns the hexadecimal value of the active link color of the document anchors - An array of all the named anchors in the document async - Used to tell the browser whether to load a document with an asynchronous request or a synchronous request applets - An array of all the Java applets in a document bgColor - Returns the hexadecimal value of the background color of the document body Returns the body or frameset element of the document characterSet - Returns a string value that represents the character set used to encode the document Methods of DOM: attachEvent() - Attaches a function to an event, so that the function runs when the event occurs (Internet Explorer only) createAttribute() - Creates an attribute with a name that is sent to it as a parameter createAttributeNS() - Creates a new attribute in a particular namespace createCDATASection() - Creates a new CDATA section createComment() - Creates a comment with the value that is sent to it as a parameter createDocumentFragment() - Creates a new document fragment createElement() - Creates an element of the type sent to it as a parameter createElementNS() - Creates an element in a particular URI and a particular type sent to it as parameters

Browser object or Navigator object


The navigator object gives you access to various properties of the viewers browser, such as its name, version number, and more. It got its name from the Netscape Navigator browser, which preceded Mozilla/Firefox. Properties of Navigator object: appCodeName - The code name of the browser appName - The name of the browser appMinorVersion - A string representing the minor version of the browser (Internet Explorer only) appVersion - The version of the browser and some other information browserLanguage - The language of the browser being used (Internet Explorer and Opera)

Methods of Navigator object javaEnabled() - Used to test whether or not Java is enabled in the browser mozIsLocallyAvailable() - Checks to see if a file at a certain address is available locally (Firefox only) preference() - Allows certain browser preferences to be set (requires signed script).

Events of javascript
Definition: An event handler is a predefined JavaScript property of an object (in most cases an element in the document) that is used to handle an event on a Web page. onabort() - An image is stopped from loading before loading has completed onblur() - Viewer removes focus from an element onchange() - Viewer changes the contents of a form element onclick() - Viewer clicks an element oncontextmenu() - Viewer opens the context menu oncopy() - Viewer uses the copy command on part of a page oncut() - Viewer uses the cut command on part of a page ondblclick() - Viewer double-clicks the mouse onerror() - Viewers browser gets a JavaScript error or an image that does not exist onfocus() - Viewer gives focus to an element onkeydown() - Viewer presses down a key on the keyboard onkeypress() - Viewer presses a key on the keyboard, and releases or holds the key down onkeyup() - Viewer releases a key on the keyboard onload() - Web page finishes loading

Form Object
The JavaScript form object will help you when you need to access certain elements or attributes of the form in a script properties of form object: action - The value of the action attribute in the HTML form tag elements - An array that includes an array element for each form element in an HTML form encoding - The value of the enctype attribute, which varies with different browsers length - The value of the total number of elements in an HTML form method - The value of the method attribute in an HTML form tag name - The value of the name attribute in an HTML form tag target - The value of the target attribute in an HTML form tag

Methods of form object: reset() This method enables you to reset a form using your script, allowing you to reset the form on any event you like. So, if you want to reset a form after the viewer removes focus from an element, you could use the following: <body> <form> Your Favorite Food <input type="text" name="fav_food" onblur="this.form.reset();" /><br /> Drink <input type="text" /> <br /><br /> <input type="reset" value="Reset Form" /> <input type="submit" value="Submit Form" /> </form> </body> submit() This method allows you to submit a form without the viewer clicking the submit button. The following code shows how to do this when the viewer removes focus from an element. <body> <form action="http://site.com/php/form.php"> Your Favorite Food <input type="text" name="fav_food" onblur="this.form.submit();" /><br /> Drink <input type="text" /> <br /><br /> <input type="submit" value="Submit Form" /> </form> </body>

Math and date object


The Math object is a predefined JavaScript object. Like the other predefined objects you have studied in this book, the Math object gives you properties and methods to use. The Math object is used for mathematical purposes to give you the values of certain mathematical constants or to perform certain operations when you use a method function. Properties of math object: E - Value of Eulers constant (E), which is about 2.71828 LN10 - Value of the natural logarithm of 10, which is about 2.302585 LN2 - Value of the natural logarithm of 2, which is about 0.693147 LOG10E - Value of the base 10 logarithm of E, which is about 0.43429

LOG2E - Value of the base 2 logarithm of E, which is about 1.442695 PI - Value of pi, often used with circles, which is about 3.14159 SQRT2 - Value of the square root of 2, which is about 1.4142 SQRT1_2 - Value of the square root of one half, which is about 0.7071 Methods of math object: abs() - Returns the absolute value of the number sent as a parameter acos() - Returns the arccosine of the number sent as a parameter, in radians asin() - Returns the arcsine of the number sent as a parameter, in radians atan() - Returns the arctangent of the number sent as a parameter, in radians atan2() - Returns the arctangent of the quotient of two numbers sent as parameters, in radians ceil() - Returns the smallest integer greater than or equal to the number sent as a parameter cos() - Returns the cosine of the number sent as a parameter, in radians exp() - Returns the value of E to the power of the number sent to the method as a parameter floor() - Returns the largest integer less than or equal to the number sent as a parameter log() - Returns the natural logarithm of the number sent as a parameter

Date object
The Date object is another predefined JavaScript object. It enables you to set certain time values and to get certain time values that you can use in your scripts. Properties of date object: Constructor - Holds the value of the constructor function that created the object prototype - Enables you to add properties to the object if you wish Methods of date object: getDate() - Returns the day of the month based on the viewers local time getDay() - Returns the number of days into the week based on the viewers local time (06) getHours() - Returns the number of hours into the day based on the viewers local time (023) getMilliseconds() - Returns the number of milliseconds into the second based on the viewers local time (0-999) getMinutes() - Returns the number of minutes into the hour based on the viewers local time (059) getMonth() - Returns the number of months into the year based on the viewers local time (011) getSeconds() - Returns the seconds into the minute based on the viewers local time (059) getTime() - Returns the number of milliseconds since 1/1/1970 for the Date object getTimezoneOffset() - Returns the time-zone offset (from Greenwich Mean Time) in minutes based on the viewers local time zone getYear() - Returns the year based on the viewers local time (two digits)

getFullYear() Returns the full year based on the viewers local time (four digits)

String object
The String object provides properties and methods to get information about strings or to modify strings. Properties of string object Constructor - Holds the value of the constructor function for an instance of the object Length - Holds the numeric value of the length of the string (its number of characters) Prototype - Allows you to add properties to the object. Methods of string object concat() - Adds two or more strings together and returns the new combined string value match() - Compares a regular expression and a string to see if they match replace() - Finds out if a regular expression matches a string and then replaces a matched string with a new string search() - Executes the search for a match between a regular expression and a specified string slice() - Pulls out a specified section of a string value and returns a new string small() - Adds <small> and </small> tags around a string value split() - Separates a string into bold() - Adds <b> and </b> tags around a string value

You might also like