computer project on music website.website made using asp,html,css and vbscript......database connectivity using asp is also included in it......Full description
Full description
Full description
Gate Software Engineering & web Technology book is very useful for student who want to prepare for GATE. This book is part of GATE correspondence course study material by THE GATE ACADEMY. http:/...
Full description
Full description
B.E web technology notes
MultimediaDeskripsi lengkap
Deskripsi lengkap
Full description
IOTFull description
SJRYEFHANKARAGTST
dfghjk
http://www.eiriindia.org/Adhesive_Technology_Formulations_Hand_Book_Hand_Book_Of_Adhesives.html The book Adhesive Technology and Formulations Hand Book covers almost all the basic and advanced d...Full description
RPP kur 2013
http://www.eiriindia.org/Adhesive_Technology_Formulations_Hand_Book_Hand_Book_Of_Adhesives.html The book Adhesive Technology and Formulations Hand Book covers almost all the basic and advanced d...
RPP kur 2013Full description
program tahunanFull description
http://www.eiriindia.org/Adhesive_Technology_Formulations_Hand_Book_Hand_Book_Of_Adhesives.html The book Adhesive Technology and Formulations Hand Book covers almost all the basic and adv…Full description
http://www.eiriindia.org/Adhesive_Technology_Formulations_Hand_Book_Hand_Book_Of_Adhesives.html The book Adhesive Technology and Formulations Hand Book covers almost all the basic and adv…Full description
Strictly in accordance with the latest syllabus
S araswati
MULTIMEDIA & WEB TECHNOLOGY Supplementary Reading Material for UNIT 3: WEB SCRIPTING
[FOR CLASS XI] By Gagan Sahoo M.C.A.
New Ne w Saraswa wat ti Ho Hous use e (I (India ndia) ) Pvt Pvt.. Ltd. New Delhi-110002, INDIA Date: 27-04-2015
S
Y L L A B U S
UNIT 3: WEB SCRIPTING JavaScript: Introduction to client side scripting using Java Script, Using Java Script in HTML page with <SCRIPT> tag, external Java Script; JavaScript Variables: Declaring variable, assigning values to variables, Java Script literals; Data types in Java Script – String, Number, Boolean, Object, Function, Null; Type casting in Java Script; JavaScript Operators Operators:: Arithmetic Operators: Operators: +, -, *, /, % , ++, - - ; Assignment Operators : =, +=, - =, *=, /=, %= ; Comparison Operators: <, >, <=, >=, !=, == ; Logical Operators: &&, ||, !; String Operator: + (for concatenation); Bitwise Operators : &, |, ~, ^, <<, >> ; Unary + operator; typeof operator; Conditional operator : (?:) JavaScript Popup Boxes: Alert, Confirm and Prompt box Comments in JavaScript: Single line and multiline; Control Structures in JavaScript: Conditional statements: If, Else, Else If.., switch case; break and default statement; Loops: For, While, Do While loops; continue statement; JavaScript Functions: Define a function, execute a function, return statement, function using arguments, Scope of variables; Objects in JavaScript: Window object, document object, location object, form object, working with control objects(Button, reset and submit objects, checkbox objects, and radio objects, select objects, password, text, textarea object), date object, Creating Dynamic Interface with HTML form controls and JavaScript; Array object in Java Script: length property, join(), sort(), sort() , for in loop; Responding to events: onLoad, onUnload, onFocus, onBlur, onChange, onMouseOver, Timing Events – setTimeout( ) and clearTimeout();
C O N T E N T S Chapter–1 Introduc Introduction tion to Java JavaScript Script .......................... ..................................................... .................................................. ....................... 3.1 3.1–3. –3.38 38 Chapter– 2 JavaS JavaScript cript Funct Functions ions ....................... ................................................ .................................................. .................................. ......... 3. 3.39– 39–3.6 3.64 4 Chapter– 3 Branch Branching ing in JavaS JavaScript cript ........................ ................................................ ................................................. .............................. ..... 3. 3.65– 65–3.8 3.88 8 Chapter– 4 Looping in JavaScript ......................... .................................................. .................................................. ............................ ... 3.8 3.89– 9–3.1 3.138 38 Chapter– 5 Objects in JavaSc JavaScript ript ...................... ............................................... ................................................. ............................... ....... 3.1 3.139 39–3. –3.154 154 Chapter–6 Working with Control Object Objects s ........................ ............................................... ......................................... .................. 3.1 3.155– 55–3.1 3.198 98
(2)
Introduction to JavaScript
3.1
Introduct ctiion to JavaScr criipt
U N II T — — 3
1
1.1 INTRODUCTION The World World Wide Web Web (WWW) began as a text-only medium—the first browsers did not even support images within web pages. Today’s websites can include a lot of features: graphics, sounds, animation, video, and occasionally useful content. Web Web scripting languages also, known as client-side scripting languages, such as JavaScript, are one of the easiest ways to add dynamic state to a Web Web page and to interact with users in new ways. Client-side scripts can control browser actions associated with a Web Web page. Scripts are programs written in a simple and easy-to-use language to specify control of other programs. Client-side scripts are almost always written in the JavaScript language to control browser actions. Tasks Tas ks performed with client-side scripts include:
Asking the browser to display information Making the Web Web page different depending on the browser and browser features Monitoring user events and specifying reactions Generating HTML code for parts of the page Modifying a page in response to events Checking correctness of user input Replacing and updating parts of a page Changing the style and position of displayed elements dynamically
Client-side scripting can make Web pages more dynamic and more responsive.
1.2 SCRIPTING LANGUAGE Scripting languages are becoming more popular due to the emergence of web-based applications. Specialised scripting languages include: Perl (Practical
Extraction and Report Language). This is a popular string processing language for writing small scripts for system administrators and website maintainers. Much web development is now done using Perl. Hypertalk is another example. It is the underlying scripting language of HyperCard. Lingo is the scripting language of Macromedia Director, an authoring system for developing high performance multimedia content and applications for CDs, DVDs and the Internet. AppleScript, a scripting language for the Macintosh allows the user to send commands to the operating system, for example open applications, to carry out complex data operations. JavaScript, perhaps the most publicised and well-known scripting language was initially developed
3.1
3.2 3. 2
S araswati Multimedia and Web Technology (XI) Sa
by Netscape as LiveScript to allow more functionality and enhancement to web page authoring that raw HTML could not accommodate. A standard version of JavaScript was later developed to work in both Netscape and Microsoft’ Microsoft’ss Internet Explorer Explorer,, thus thus making the language to a large extent, universal. This means that JavaScript code can run on any platform that has a JavaScript interpreter. interpr eter. VBScript, a cut-down version of Visual Basic, used to enhance the features f eatures of web pages in Internet Explorer. PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely used open source general purpose scripting language that is especially suited for web development development and can be embedded into HTML. Major advantages of scripting languages include:
easy to learn and use. minimum programming knowledge or experience required. allow complex tasks to be performed in relatively few f ew steps. allow simple creation and editing in a variety of text editors. allow the addition of dynamic and interactive activities to web pages. editing and running code is fast.
The major disadvantage of scripting languages is that executable code can inadvertently be downloaded from a remote server to a web browser’s machine, installed and run using the local browser’s interpreter. interpreter. This is easily done by visiting dubious web sites or downloading programs without valid authenticity. The user is probably unaware of anything devious occurring. This is a weakness and major drawback in the formal rules defining scripting languages langu ages like JavaScript and VBScript.
1.3 JAVASCRIPT JavaScript (originally called LiveScript) is a widely used scripting language originally developed by Netscape Communications Corporation for both client-side and server-side scripting. JavaScript is a lightweight programming language that is interpreted by the browser engine when the web page is loaded. JavaScript is a widely supported language and it is available in the following browsers:
Netscape Navigator Navigator (beginning with version 2.0) Microsoft Internet Explorer (beginning with version 3.0) Firefox Safari Opera Google Chrome
Wh a t is J a va S c r ip Wha iptt ? J a vaS cr cript ipt is a cro cross s -plat -platform form,, obb je c t -o r ie n t e d s c r ip t in g o la n g u a g e d e ve lo p e d b y Ne t s c a p e . J a va S c r ip t wa wa s crr e a t e d c by Ne t s c a p e progra prog rammer mmer Bre Brenda ndann Ei Eich. ch.
Thus, most Internet users today have browsers that support JavaScript. That T hat is why JavaScript is one of the most popular tools in the Web developer's arsenal. Client=Side Scripting. JavaScript code is executed/interpreted when an event is triggered.
When the code is executed, it is interpreted one line at a time. There are number of events that will trigger the execution of a JavaScript, like clicking on a form button or the completion of a web page loading. Server-Side Scripting. When the web server loads an .html page from the disk into the memory, it automatically knows how to interpret the code in this document. Once the code has been interpreted, the resulting HTML page is sent to the browser (client) making the request.
Introduction to JavaScript
3.3
It was the first web scripting language to be supported by browsers, and it is still by far the most popular. JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents. It is a less complex, interpreted scripting language similar to AppleScript. JavaScript is similar in some ways to Java, but it does not require the programmer to understand or implement the complicated object-oriented object-oriented syntax or worry about programming issues like variable typing and object hierarchies. Thus, JavaScript is a programming language that allows scripting of events, objects and actions to create Internet applications. In fact, Java and JavaScript are so different that you can think of them with different dif ferent titles depending on your ability. It is convenient to think of creating programs of Java as programming and you can call creating scripts in JavaScript authoring. Here are a few of the things you can do with JavaScript:
Display messages to the user as part of a web page, in the browser’s status line, or in alert boxes. Validate the contents of a form and make calculations (for example, an order form can automatically display a running total as you enter item quantities). Animate images or create images that change when you move the mouse over them. Create ad banners that interact with the user, rather than simply displaying a graphic. Detect the browser in use or its features and perform advanced functions only on browsers that support them. Detect installed plug-ins and notify the user if a plug-in is required. Modify all or part of a web page without requiring the user to reload it. Display or interact with data retrieved r etrieved from a remote server.
JavaScript is an object-oriented language and many constructs are similar to
those in C++ or Java. It is an interpreted programming language that can be embedded into an HTML web page or used in server side scripting language. The following are the major advantages of JavaScript:
JavaScript is no more difficult to learn than HTML. It allows people with little or no programming
experience who are daunted by Java’s complexity to create interactive and Web based applications. JavaScript can be used to solve common problems, such as validating forms input and can also be used to create dramatic and visually appealing content, which would be impossible with HTML. JavaScript is the one of the Dyn Dynami amic c HTM HTML L available in both Netscape Navigator and Internet Explorer. As JavaScript lives inside the HTML document, it can either exist as a complete script that is embedded in the or elements or it can consist of event handlers that are written directly into the HTML code.
1.4 1. 4 JA JAVAS VASCR CRIPT IPT SYNT SYNTAX AX JavaScript is based on
an action-oriented model of the World World Wide Web. Web. Elements of a Web Web page, such as a button or a checkbox may trigger actions or events. When one of these events occurs, a corresponding piece of JavaScript code, usually a JavaScript function, is executed. That function, in turn, is composed of various statements which perform calculations, examine or modify the contents of the Web page or perform other tasks in order to respond in some way to that event. For example, pressing the SUBMIT button on an online order form might invoke a JavaScript function that validates the contents of that form to ensure that the user entered all the required information. In general, the elements of a JavaScript program can be divided into following categories:
Statements—Statements are the lines of code from which JavaScript programs are built. Blocks—Blocks allow you to group statements. Comments—Comments allow you to annotate your code with remarks.
3.4 3. 4
S araswati Multimedia and Web Technology (XI) Sa
Data—Data is the actual information your programs work on. Variables and their values—V values—Variables ariables give you a place to store your data. Expressions—Expressions manipulate those values, i.e., perform operations on data. Control structures—Control structures, which modify how statements are performed at runtime. Functions—Functions execute a block of statements with a name. Objects—Objects allow you to group your data and functions together. Arrays—Arrays allow you to hold a great gr eat deal of data and to access individual elements easily.
Before discussing the above points, let us look at the basic JavaScript syntax, which creates a simple program in HTML code with the syntax.
1.4.1 The <SCRIPT> Tag
Not e
The <SCRIPT> tag is used to add JavaScript commands to your c r iipp tt>> t ag ag HTML pages. <SCRIPT> is a container tag that can accept the attribute The b e g inn ing < S cr Langua Lang ua include s a Langu a ge arg ume nt LANGUAGE, which allows you to specify the scripting language used t h a t in d ic a t e s t h e s c r ip t in ingg (JavaScript is generally the default). The syntax is: la n g u a g e . Th Thee La n g u a g e arg a rg ume nt is re qu quire ire d be ca us e script code the t here re is more t ha n one s cript ing la n g u a g e . Wit h o u t t he La n g u a g e a r g u me n t , a we b From the above syntax, brows br owsee r would not know if t he The <script> tags tell the browser to expect a script in between t e xt b e t we e n t h e t a g s w a s J ava S cript , VB VBS S cript or an anot othe herr them. scripting l language anguage . The LANGUAGE is optional—you probably would not need to use it while authoring JavaScript, but it cannot hurt. The element lang_name gives the language that is used in the subsequent script code; this should be JavaScript. If the SRC attribute is specified then it should reference a URL containing code in the script language. For JavaScript, this should be a valid URL for a file containing the JavaScript code. The filename should have the suffix .js. If the SRC attribute is given then the <SCRIPT> can be immediately terminated by a directive. This attribute is implemented in Netscape 3.0.
For example, <SCRIPT LANGUAGE = "type/JavaScript" "type/JavaScript" SRC = "main/hello.js" ..... .....
This explicitly declares to the browser that your script is a JavaScript (instead of VBscript, for example). The "LANGUAGE" attribute while not essential to declare, is useful in certain cases. But the <script language="JavaScript"> is incorrect. <script language = "JavaScript"> is deprecated as "language" value is an identifier which has no standards. The correct syntax is: <SCRIPT type = "text/JavaScript" SRC = "main/hello.js" ..... .....
This overrides the default scripting language. Here, the <SCRIPT> block that loads JavaScript code from a filename hello.js in a directory main relative to the document.
Introduction to JavaScript
3.5
If the SRC attribute is not given then it is expected that all the code between <SCRIPT> and SCRIPT> is the script source itself. It is recommended that source included between <SCRIPT> and be enclosed within the HTML comment delimiters
From the above example, the entire script body is enclosed with HTML comment tags. These are optional but recommended. They tell browsers that don't support JavaScript (or with JavaScript disabled) to ignore the code in between. This prevents the code from being written out to your website users. At present, you should structure your script according to the following rules: r ules:
Place the comment start ( ... ...
Introduction to JavaScript
3.7
Here, the tag <script language=”JavaScript”> introduces the JavaScript source code, the tag ends it. The codes cause source code from older browsers, ones that do not support JavaScript, to be hidden. Within these tags, you can define functions, variables and other JavaScript statements.
The second possibility is to carry out JavaScript commands given a surfer’s particular actions. Such actions can include the loading or leaving of a page or the following of a link with the mouse. In the following example, the function hello is supposed to be carried out when the page is loaded. This must be defined in advance in the header of the HTML file: ... ...
In addition, you can incorporate JavaScript commands into a particular part of the page when you’re building the page. This is useful if, for example, you’d like JavaScript to incorporate supplements such as text directly into the HTML file. For example, if you want to incorporate a function write_time in the HTML HTM L BODY, BODY, then you must define in the header as: <script> write_time()
JavaScript example:
1.4.4 Writing First Script Let us start with a simple script as given: First JavaScript Example <SCRIPT type="text/javascript" type="text/javascript"> >
JavaScript example:
S araswati Multimedia and Web Technology (XI) Sa
3.8 3. 8
As with HTML programming, open your windows Notepad program and type the above code. Save the Notepad text with First.html. Open the First.html file in either Netscape or IE. If you are using IE, then the screen will look like Figure 1.2.
Figure 1.2 First JavaScript screen output.
The JavaScript defines a function called hello() and a statement with alert() for displaying something in the form of a message. More on about function will be discussed in subsequence chapters. Instead of using alert() command, you can display the text in the browser window using Document object. For example, document.write("Hello! document.write("H ello! I am Rahul and a Web programmer in Class-XI");
1.4.5 The Document Object JavaScript uses an object called document. This object manages many of the instructions that JavaScript can handle for HTML. One of the functions of object is to display a string on the screen. A string is a piece of text that the browser is asked to use “as is”. The function used is called write. The syntax of the write function of the document object is: document.write(String) document.write(String )
The String for display can be provided in double quotes or as a variable that we will learn soon. Here is an example of displaying somebody’s name using the document.write() function: <SCRIPT type="text/javascript type="text/javascript"> "> document.write("Author: document.write(" Author: Gagan Sahoo ")
To display various lines of text, use as many document.write() lines in between
When Internet Explorer receives this script, it gets rid of everything that is not part of the string. After this operation, the remaining text becomes: Book Title: Multimedia and Web Technology
This is what the browser would try to display display.. There is also an HTML tag in the code, namely, the break tag ; therefore, the break tag would be applied. Let us see the following code: <SCRIPT type="text/javascript" type="text/javascript"> > document.write("Author: document.write ("Author: Gagan Sahoo ") document.write("Book document.write ("Book Title: Multimedia and Web Technology ") Technology ") document.write("Publisher: document.write(" Publisher: New Saraswati House (India) Pvt. Ltd. ")
3.10
S araswati Multimedia and Web Technology (XI) Sa
document.write("Yea document.write ("Yearr Published (Revised): 2015")
Now, save the file with ...\Unit 3\Chapter 1\Author1.html and preview the page in Internet Explorer Now, as shown in Figure 1.5.
Figure 1.5 Using HTML tags inside JavaScript.
After previewing the page, return to Notepad and to make the page more attractive, change it as depicted below: belo w: <SCRIPT type="text/javascript" type="text/javascript"> > About My Book") document.write(" ") document.write("Author: document.write("Au thor: Gagan Sahoo "); document.write("Book document.write ("Book Title: Multimedia and Web Technology "); Technology "); document.write("Publisher: document.write(" Publisher: New Saraswati House (India) Pvt. Ltd. "); document.write("Year document.write(" Year Published (Revised): 2015"); document.write("") // end hiding -->
Now, save the file with ...\Unit 3\Chapter 1\Author2.html and preview the page in Internet Explorer Now, as shown in Figure 1.6.
Figure 1.6 Using more HTML tags inside JavaScript.
Introduction to JavaScript
3.11
1.4.6 Statements JavaScript programs are made of statements. Let us
take a look at our previous example, which contains a line,
This is a JavaScript statement. This line tells the browser to write the string "Author: Gagan Sahoo" to the browser document window. As you saw the line "Author: Gagan Sahoo " shows up just as if you had included it as part of the HTML code.
1.4.7 Semicolon (;) In JavaScript, a semicolon (;) is a way of saying that the statement has ended and that the script can be executed. Semicolons are normally used at the end of each line, but you can place multiple statements on a line if each is separated by a semicolon. If you do not like the idea of putting semicolons at the end of all your statements, you will find that you can usually leave them off without generating an error. It is best, however, to get in the habit of using semicolons, as it can make tracking down errors easier and is generally considered to be better form.
1.4.8 Blocks It is quite common in programming to want to group many statements together so that they can be treated as one entity; this is often done with functions and in conditions. This grouping of statements together into one entity is called a block. A block is created by surrounding all the statements that it will contain with brackets ({ and }). For example, { document.write("Hello! I am Rahul and a Web programmer in Class-XII"); document.write("Hello! document.write("I document.write ("I am in DAV School, New Delhi"); }
1.4.9 Comments Like other languages, JavaScript supports comments in its code. Comments are completely ignored by the JavaScript interpreter, so you can type whatever descriptive text you want. You can write single-line or multiline comments.
If you just need to add a small amount of description to the code, you are writing a single-line comment which is probably the best option. Placing two slashes (//) before your text makes it a single-line comment. For example, { // This is a single-line comment. document.write("Hello! document.write ("Hello! I am Rahul and a Web programmer in Class-XII"); document.write("I document.write ("I am in DAV School, New Delhi"); }
You can also write wr ite a single-line comment as one line as: docu do cume ment nt.w .wri rite te(" ("II am am in DA DAV V Sch Schoo ool, l, Ne New w De Delh lhi" i"); );
// Wr Writ ite e to br brow owse serr
3.12
S araswati Multimedia and Web Technology (XI) Sa
Sometimes one line of comments is not enough for the description you want to pr ovide. In this case, you can use a multiline comment. Multiline comments are specified by surrounding the commented text with /* at the beginning and */ at the end. For example, example, { /* This is the the simple programming programming for Web Web to display texts texts in a browser */ document.write("Hello! document.write ("Hello! I am Rahul and a Web programmer in Class-XII"); document.write("I document.write ("I am in DAV School, New Delhi"); }
1.5 JAVASCRIPT VARIABLES Variables enable you to define places to store this data. A variable may be initialized, meaning that it is given a value when it is declared or it may be uninitialized. In addition, multiple variables can be declared on the same line by separating their names with commas. JavaScript variables are untyped . They can contain values of any data type.
All JavaScript variables are declared using the keyword var or let. The following rules are used to declare variables in JavaScript:
The variable names start contains letters, digits, underscores, and dollar signs. The first character in the name must be an alphabetic letter. The names can also begin with $ and _ (underscore). Characters subsequent to the first character in the variable name can be alphabetic letters, numbers or underscores. Variable names are case sensitive (num and Num are different variables). Reserved words (like JavaScript keywords) cannot be used as names.
For example, <SCRIPT type="text/javascript" type="text/javascript"> > var MyName; var MySchool = "DAV Public School"; var Age = 15; document.write("My document.write ("My school: " + MySchool);
After you create a variable, you must assign (give) or initialize a value to it. The ( = ) equal sign is called assignment operator: you assign the value of what is on the right side of the = sign to whatever is on the left side of the = sign. Its syntax is: VariableName = VariableName = Value
Here, the VariableName must be a valid variable name. It cannot be a value such as a numeric value or a (double-quoted) string. Here is an example that assigns a numeric value to a variable:
Once a variable has been declared and assigned a value, you can call the document.write() function to display its value. For example: <SCRIPT type="text/javascript" type="text/javascript"> > Salary = 22550; document.write(Salary);
To improve, safeguard and make your code more efficient, you should declare a variable before using it. This is done using the var keyword. The above script could be written as follows: <SCRIPT type="text/javascript" type="text/javascript"> > var Salary; Salary = 22550; document.write(Salary);
Let us start an example for assigning values into variables with the following code in a Notepad window: <SCRIPT type="text/javascript" type="text/javascript"> > var Job1Wage, Job2Wage Job1Wage = 2500.38 Job2Wage = 2300 document.write("
Save the file as: ...\Unit 3\Chapter 1\Assign.html. When you open the file in IE, the following screen will appear as shown in Figure 1.7.
Figure 1.7 Using assignment operator for assigning values.
S araswati Multimedia and Web Technology (XI) Sa
3.14
1.6 JAVASCRIPT DATA TYPES One of the basic tenets of programs is that they have to work on data. Data is any type of information with which you are working. Data can be words, such as "Hi Friends" or numbers, num bers, such as 100 or 250.60. In any case, different programming languages enable you to work on different kinds of data. JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.
Primitive data type Non-primitive (reference) data type
JavaScript is a dynamic type language, which means you don't need to specify type of the t he variable because it is dynamically used by JavaScript engine. You You need to use var here to specify the data type. It can hold any type of values such as numbers, strings, etc. For example, v ar n u m = 40; var MyName="Amitl";
// holding number // holding string
The Table 1.1 shows five types of primitive data types in JavaScript: Table Tabl e 1.1 JavaScript primitive data types. Data Type
String Number Number Boolean Undefined Null Nu ll Object Array
Description
Ex a mpl e
Represents sequence of characters Represents numeric values Represents boolean va value either fa false or tr true Represents un undefined va value Represents null document, window a[0] = 1
"Hello", "We are selected in IIT" 100, 10 0, 25 250. 0.60 60 true, false No value at all
Table 1.2 shows the non-primitive data types in JavaScript: Table Tabl e 1.2 JavaScript primitive data types. Data Type
Description
Object Array RegExp
Represents instance through which we can access members. Represents group of similar values. Represents re regular ex expression.
A string is any grouping of characters that is surrounded by either double quotation marks (") or single quotation marks ('). Strings are used anytime you want to use text in a program. For example, "Hello" "We are selected in IIT"
Usually, double quotation marks are used to denote strings. If you want to include double quotes in the string itself, use string quotation marks instead. For example, 'Hello friends! The CBSE introduced a special course for "Web Developers" in 2004'
JavaScript strings are immutable, which means that there is no way to change the contents of a string. Methods that operate on strings typically return a modified copy of the string.
Introduction to JavaScript
3.15
There are two numeric types in JavaScript : integers and floating-point numbers. The rules for specifying both types are almost identical. Integers may be specified in i n base 10 (decimal), base 8 (octal) or base 16 (hexadecimal) formats. Any of the three forms can also start with a + or – sign. The three forms f orms are:
1-9 followed by any set of digits is a decimal integer. integer. For example, –45 is a decimal integer. 0 followed by any set of the digits 0-7 is an octal integer. For example, 017 is an octal integer. 0x or 0X followed by any of 0-9, a-f or A-F is a hexadecimal integer. integer. For example, 0x12EF5 is a hexadecimal integer.
The minimum and maximum integers that can be used are implementation dependent, but at least 32 bits should be expected. Floating-point numbers can be specified in either the standard decimal point (.) format or the engineering E-notation. Typically Typically floating-point numbers should contain a decimal point or an exponent, which may begin with either e or E. A floating-point number may also have a + or – sign. 0.0, -1.4212 and 3.1424 are all valid floating-point numbers.
A Boolean is a simplest data type available. A Boolean value has only two possible values—true and false. They are often used to represent whether something has been done or not. It is possible to think of true as 1 and false as 0. JavaScript converts these logical values into 1 and 0, respectively. JavaScript also accepts any nonzero integer in place of true, for example, so that 5 and 3 can both be used as stand-ins for true.
An object is a compound data type that contains any number of properties. Each property has a name and a value. The . operator is used to access a named property of an object. For example, you can read and write property values of an object o as as follows: Obj1.x = 1; Obj1.y = 2; Obj1.total = Obj1.x + Obj1.y; Obj1 .y;
Objects are created with the new operator. You You can create a new object with no properties as follows: var Obj1 = new Object( );
Similarly, to create a Data class object that represents the current time with its method, var Now = new Date();
A function is a piece of JavaScript code that is defined once and can be executed multiple times by a program. A function definition looks like this: function sum(x, y) { return x + y; }
S araswati Multimedia and Web Technology (XI) Sa
3.16
Functions are invoked using the () operator and passing a list of argument values: var to tottal = su sum m(1,2);
// Tota tall is no now 3
In JavaScript 1.1, you can create functions using the Function( ) constructor: var sum = new Function (“x”, “y”, “return x+y;”);
The value null has a very special role in the JavaScript language. The null data type only has one possible value, i.e., null. When a variable is set to null, it means that it has no value. Variables Variables are often of ten set to null when a value was to be returned to a function but instead none was generated.
1.7 JAVASCRIPT CONSTANTS In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A constant can be global or local to a function where it is declared. Constants are read-only, therefore you cannot modify them later on. Naming a constant in JavaScript follows the same rule of naming a variable except that the const keyword is always required, even for global constants. If the keyword is omitted, omit ted, the identifier is assumed to represent a variable. For example, const Country = “India”; const Num = 20;
1.8 KEYWORDS In Table Table 1.3, keywords are part of the JavaScript language, l anguage, and have special meaning to the JavaScript interpreter. These reserved words are called keywords. Therefore, they may not be used as identifiers. Table 1.3 Useful keywords. abstract cla ss e ls e function int private switch true
boolean b r ea k const continue extend f a lse goto if interface l on g protected public synchronized try typeof
byte default final implements native return this var
c a se delete finally import new short throw v oi d
catch do float in null static throws while
ch ar double for instanceof p a ck a g e su p er transient with
1.9 JAVASCRIPT LITERALS Literals are the way you represent values in JavaScript. These are fixed values that you literally provide in your application source, and are not variables.
Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).
Decimal integer literal can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading zeros. For example, 123, -20, 12345.
Introduction to JavaScript
3.17
Octal numbers can be made with the digits dig its 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number numb er is octal. For example, 173, -24, 30071. Hexadecimal numbers number s can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal. For example, 7b, -14, 3039. 30 39.
A floating-point literal can have the following parts:
A decimal integer which can be signed (preceded by "+" or "-"), A decimal point ("."), A fraction (another decimal number), An exponent.
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E"). Some examples of floating-point literals are 3.1415, -3.1E12, .1e12 and 2E-12.
The Boolean type has two literal values: true and false. You You can use conditional statement to combine with a Boolean. For example, var Flag = true; if(Flag == true) { // If the condition evaluate evaluates s to true } else { // If the condition condition evaluates to false }
It goes without saying that the Boolean object is an extremely important part of JavaScript. Without a Boolean object, there wouldn't be anything to evaluate within conditional statements.
A string literal is zero or more characters enclosed in double (") or single (') quotes. A string string must be delimited by quotes of the same type; that is, either both single quotes or double quotes. For example, var Str1 = "Multimedia & Web Technology" var Str2 = 'Class - XI' var Str3 = "JavaScript"
You can also use + operator to join strings. For example, var NStr1 = "Multimedia & Web Technology" + 'Class - XI' var NStr2 = Str2 + Str3
In addition to ordinary characters, you can include special characters in strings, as shown in Table 1.4. var StrA = "Multimedia & Web Technology Technology \n Class - XI"
Table 1.4 lists the special characters or escape characters that you can use in JavaScript strings.
3.18
S araswati Multimedia and Web Technology (XI) Sa
Table 1.4 JavaScript special characters. Cha rac t ers
\b \f \n \r \t \v \' \" \\ \XXX \xXX
\uXX \u XXX XX
Meaning
Backspace Form feed New line Carriage return Tab Vertical tab Apostrophe or single quote Double quote Backslash character The character with the La Lattin-1 encoding specifi fieed by up to three octal dig igiits XXX between betwe en 0 and 377. For exampl example, e, \251 is the octal sequen sequence ce for the copyrig copyright ht symbol symbol.. The chara raccter with th thee Lati tinn-11 encodi dinng specif ifie iedd by the two he hexxadecim imaal dig igiits XX between betwe en 00 and FF FF.. For exampl example, e, \xA9 is the hexade hexadecimal cimal sequen sequence ce for the copyrig copyright ht symbol. Thee Un Th Unic icod odee ch char arac acte terr sp spec ecif ifie iedd by th thee fo four ur he hexa xade deci cima mall di digi gits ts XX XXXX XX.. Fo Forr ex exam ampl ple, e, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
You can insert quotes inside of strings by preceding them by a backslash. This is known as escaping the quotes. For example, var EQuote = "Hi friends! \"The CBSE multimedia course updated\" by Author: Gagan Sahoo." document.write(EQuote)
The result of this would be Hi friends! “The CBSE multimedia course updated” by Author: Gagan Sahoo.
In JavaScript an array literal is a list of expressions, each of which represents represen ts an array element, enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. If no value is supplied ,it creates an empty array with zero length. For example, to create an empty array Num, var Num = [ ];
To create an array with week names, var WNames = ["Sunday", "Monday", "Tuesday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
An object literal is zero or more pairs of comma-separated list of property names and associated values, enclosed by a pair of curly braces ({ }). To declare an object literal, we must maintain the following follo wing syntax rules:
There is a colon (:) between property name and value. A comma separates each property name/value from the next. There will be no comma after the last property name/value pair.
Introduction to JavaScript
3.19
For example, to declare a Student object with its few properties, var Student = { First-name : "Amit", Last-name : "Gulati", Roll-No : 119 };
1.10 EXPRESSIONS An operand or a combination of operands and operators that, when evaluated, yields a single value. Expressions Expressi ons are constructs denoting rules of computation of obtaining values of variables and generating new values by the application of operators. Expressions consist of operators and operands, i.e., variables, constants and functions. For example, (f – 32) – 32) * 5 / 9
is an expression.
A numeric expression is simply the rudimentary sort of mathematically operation. For example, 10 + 5
is a numeric expression. Table 1.5 depicted some numeracal expression uisng numerical operators. Table 1.5 Common numerical operators. Operator
E xa mp le
+ – * / %
10 + 5 10 – 5 10 * 5 10 / 5 10 % 5 –(15 * 5)
Definition
Addition Subtraction Multiplication Division Modulo: The remainder after division Unary negation
A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or false. Table Ta ble 1.6 shows logical operators. For example, true && false
which evaluates false because one of the sides is not true. Table 1.6 Logical operators. Operator
&&
E xa mp le
And
Definition
(exp1 && exp2) returns true if both exp1 and exp2 are true, otherwise returns false.
S araswati Multimedia and Web Technology (XI) Sa
3.20
||
Or
!
Not
(exp1 || exp2) returns true if either exp1 or exp2 is true, otherwise returns false. (!exp) returns false only if exp1 is true or true if exp is false.
1.11 TYPECASTING JavaScript is a loosely typed language. That means that you do not have to specify the datatype of a variable when you declare it, and datatypes are converted automatically as needed during the course of script execution. In JavaScript, when we add two strings, we use the + (concatenation) operator. But when we combine a string with a number in the form: stringthing + numberthing
the number is converted to a string and the + operator then glues the two things together (concatenation). However, if they are combined in the opposite order: numberthing + stringthing
then JavaScript attempts to convert the stringthing to a number and add it, numerically, to numberthing. If the stringthing can be converted to a string, such as “-10”, then all goes well; if it cannot then an error result. This illustrates the concept of implicit conversion in JavaScript. In JavaScript, we can say, "This page has been accesses" + ctr + " times today"
without having to worry about the data type of the variable ctr. This construction will always give a valid string and never an error. JavaScript variables have to be declared in a var statement and each variable holds information of a specific type. Internally, 3 and 3.00 and "3.00" are represented differently. differently. JavaScript usually infers types from context, does conversions automatically. For example, "Sum = " + sum
and sometimes we have to be explicit:
parseInt(...) which converts a sequence of characters into
its integer value. For example,
num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) // "+" means "add"
parseFloat(…) which
converts a sequence of characters into its floating-point numbers.
1.12 OPERATORS An operator is one that works on data items and performs some mathematical calculations or changes the data. JavaScript operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional and type.
Assignment Operators. For example, = Compound Assignment Assignment Operators. For example, +=, – =, =, *=, /=, %= Arithmetical Operators. For example, – , +, *, /, %, ++, – – Relational Operators. For example, >, <, >=, <=, ==, !=
Introduction to JavaScript
3.21
Logical Operators. For example, &&, ||, &, |, !, ^ Unary Operators. For example, +, – , ++, – – , ! Conditional Operator. For example, ?.
We shall discuss some of these operators one by one in the following section.
The equal (=) sign is used for assigning a value to a variable. JavaScript, JavaScript, like all scripting languages, allows you to assign values to variables. The syntax is: variable = value;
Here, a value can be a constant, an expression or a variable. We can assign a primitive variable using a literal or the result of an expression. v ar x = 7; var y = x + 2; 2; varr z = x * y; va y;
// Literal assignment // As Assign gnm ment with an an expression // As Assi sign gnme ment nt wi witth an an exp exprres essi sion on wit ith h li lite tera rall
In addition, JavaScript has a set of compound assignment operators of the forms. The compound assignment operators combine the simple assignment operator with another binary operator. The compound assignment operators are also called shorthand operators. The syntax is: argument1 operator=argument2; Or expression1 operator=expression2;
can be understood as: argument1 = argument1 operator argument2; Or expression1 = expression1 operator expression2;
An example program is shown below that demonstrates the different compound operators in JavaScript. var prod_amt = 10 prod_amt = prod_amt + 2.5; // Add 2.5 to current production
Instead of the above expression, you should use JavaScript’s compound addition operator by coding the update in this way: prod_amt += 2.5;
// Add 2.5 to the current production
The += is called the addition assignment operator. Let us see other examples: var y; y *= 2; // //s sam ame e as (y = y * 2) // Co Comp mpou ound nd mu mullti tipl plic icat atio ion n var b1 = true, b2 = false; b1 &= b2; //same as (b1 = b1 & b2)
The computational operators are used in performing arithmetic computations. JavaScript supports the common mathematical operations for both integers and reals. Table Table 1.8 shows all the usable arithmetic operators. Table 1.8 Computational or arithmetic operators. Operator
Name
Ex a mp le
Result (When x = 20, y = 10 s = 0)
+
Addition
x+y
–
Subtraction
x– y
*
Multiplication
x*y
/
Division
x/y
%
Modu lu s
x%y
Sum of x and y. For example, s = x + y is equivalent to 30 Difference of x and y. For example, s = x – y is equivalent to 10 Product of x and y. For example, s = x * y is equivalent to 200 Quotient of x and y. For example, s = x / y is equivalent to 2 Remainder of x divided by y. For example, s = x % y is equivalent to 0
Other than this, the ++ (Preincrement, postincrement) and – – (predecrement, postdecrement) operators are used with the variables as compound expression. The + operator is overload; it also has the extremely important role of string concatenation.
The relational operators are used to determine if a given relationship exists between the pairs of values. These operators are always used for comparing strings, numbers and objects, returning a true or a false Boolean value. Each relational operator always appears with two constants, variables, expressions, or a mix of these— t hese— one on each side of the operator. Table Table 1.9 shows the relational operators. Table 1.9 Relational operators.
Operators
== > < >= <= !=
Description
Example (Assume that x = 10 and y = 20)
equal to greater than less than greater than or equal to less than or equal to not equal to
x == y is not True. x > y is not True. x < y is True. x >= y is not True. x <= y is not True. x != y is True.
Introduction to JavaScript
3.23
The six operators in the above listing provide the foundation for comparing data in JavaScript. Each operator always appears with two constants, variables, expressions, or a mix of these—one on each side of the operators. The comparison is straight forward if the two operands being compared are of the same type. When they are not, the following rules apply:
When comparing a number to a string, the string is automatically converted to t o a number. When only one of the operands is a Boolean, it is converted to 1 for true tr ue and 0 for false. When comparing an object to a string or a number, the object is converted to a string (via its toString method) or a number (via its valueOf method). Failure to convert generates a run-time error.
The strict equality operators === and !== can be used if the operands must be of the same type. Let us see the difference between == and === operators.
== is an equal to operator. That is, when we compare two variables of different type, e.g., a boolean with a string or a number with String using == operator, it automatically automatically converts one type into another and returns value based upon content equality. For example, 0 == false // true, because false false is equivalent of 0 2=="2" // true, “2” string automatically converted into number
=== is an equal value and equal type operator. operator. It only return true if both variable of same type and also contains same value. For example, 0 === false // false, because both operands operands are of different type type 2 === "2" // false, since both operands are not of same type
The logical operators are also called Boolean operators. With Boolean operators we perform logical operations. These are most often used with if and while keywords. By combining logical operators with relational operators, operator s, you can create more powerful data-testing statements ( for logical operators, see Table 1.6). The following example tests the variables using if statement statement (which shall be discussed in succeeding chapters). If ((the variable a is less than the variable b) AND (the variable c is greater than the variable d)). d) ). print results are invalid to the screen. if ((a ((a < b) && (c > d)) document.write("Result document.writ e("Result is invalid.");
Bitwise operators work with bits of a binary number. Table 1.10 shows the bitwise operators. Table 1.10 Bitwise operators. Operator
Shorthand
Ex pr es s io n
Description
& | ^ ~ << >>
A nd Or Xor Not Shift left Shift right
x&y x|y x^y ~x x <>y
Bits that are set in both x and y are set. Bits that are set in either x or y are set. Bits that are set in x or y but not both are set. Bits that are set in x are not set, and vice versa. Shift the bits of x, y steps to the left. Shift the bits of x, y steps to the right.
3.24
S araswati Multimedia and Web Technology (XI) Sa
Bitwise & (And) examines bit position in each of its operands. If both operators have a 1 bit in a given position, then that bit will also be set to 1 in the result. result. In all other cases, the output bit position is zero.
The operators we have discussed so far are all binary operators. JavaScript provides two unary operators for which only one variable is required. You You can use the addition (+) and subtraction ( –) operators by themselves. When you do, they are called unary operators. For example, to assign four variables with different values containing positive or negative numbers, the statements are: var a = var var b = varr c = va varr d = va
--40 40;; +40; +40; -a; -a; +b; +b;
// As Assi sign gn 'a 'a'' a ne nega gattiv ive e 40 40 // Assig Assign n 'b' 'b' a posi positiv tive e 40 (Th (The e plus plus sign sign is not not need needed) ed) // As Assi sign gn 'c 'c'' the the ne nega gati tive ve of 'a 'a'' (40 (40)) // Ass Assig ign n 'd' 'd' the the posi positi tive ve of of 'b' 'b' (the (the plu plus s sign sign is is not not need needed ed))
The unary operators (++ and – –) are called prefix increment or decrement operators when the increment or decrement operators appear before the operand. Let us illustrate it by using an example: a = 10; d = 12; b = a++ ++;; c = ++ ++d; d;
// St Stat atem emen entt (1 (1)) // St Stat ate eme ment nt (2 (2))
After the execution of aforementioned statements, the value of b becomes 10 and the value of c becomes 13 because the precedence of ‘=’ is greater than the unary operator. So, in Statement (1), a is assigned a value and then, it is incremented. In Statement (2), d is is incremented first and then it is assigned to c. After the execution of Statement (1) and Statement (2), the values of a and d are are also incremented by 1. So, the value of a becomes 11 and the value of d becomes becomes 13. Here, Statement (1) is equivalent to the following statements: b = a; a = a + 1; Statement (2) is equivalent to the following
statements:
d = d + 1; c = d;
Also, from the previous two statements: a++ means a = a + 1 and ++d means d = d + 1
Similarly, if we consider the pre-decrement operator (– –), then the above statements can be rewritten as: a = 10; d = 12; b = a– a––; –; c = ––d;
// St Stat ate eme ment nt (3 (3)) // St Statement (4)
From the Statement (3) and Statement (4), a–– means a = a – 1 and ––d means d = d – 1
Introduction to JavaScript
3.25
Let us consider the following cases: If we use the increment operator before the operand in an expression as:
var sum = 0; var a = 10; sum su m = su sum m + ++ ++a; a;
// Or Or sum sum = sum sum + (++ (++a) a) is a pre pre-i -inc ncre reme ment nt;;
then the values of a and sum are changed in the following manner: s um
a
su m
0
10
0
0
11 (after ++a)
11 [after sum + (++a) is a pre-increment]
Here, the line: sum = sum + ++a;
first increase the value of a as a = a + 1 and then the new value of a (11) is added to the old value of sum. So, the execution of the equation becomes, sum = 0 + 11;
i.e. the new sum’s value becomes 11.
If we use the increment operator after the operand in an expression as: var sum = 0; var a = 10; sum su m = su sum m + a+ a++; +;
// Or su sum m = su sum m + (a (a++ ++)) is is a po post st-i -inc ncre reme ment nt;;
then the value of a and sum are changed in the following manner: s um
a
su m
0
10
0
0
11 (after a++)
10 [after sum + (a++)]
Here, the line: sum = sum + a++; // post-increment
first add the value a (10) with the old value of sum and then increase the value of a a ass 11. That is, for the above line the increment value of a (11) does not affect the sum value. So, the execution of the equation becomes, sum = 0 + 10;
i.e. the new sum’s value becomes 10.
If we use the decrement operator before the operand in an expression as: var sum = 0; var a = 10; sum su m = su sum m + –– ––a; a;
// Or su sum m = su sum m + (– (––a –a)) is is a pr pree-de decr crem emen ent; t;
then the values of a and sum are changed in the following manner: s um
a
su m
0
10
0
0
9 (after ––a)
9 [a [ after sum + (––a) is a pre-decrement]
S araswati Multimedia and Web Technology (XI) Sa
3.26
Here, the line: sum = sum + –– ––a; a; //Pre-decrement
first decrease the value of a as a = a – 1 and then the new value of a (9) is added to the old value of sum. So, the execution of the equation becomes, sum = 0 + 9;
i.e. the new sum’s value becomes 9.
If we use the decrement operator after the operand in an expression as: var sum = 0; var a = 10; sum su m = su sum m + a– a––; –;
// Or su sum m = su sum m + (a (a–– ––)) is is a po post st-d -dec ecre reme ment nt;;
then the value of a and sum are changed in the following manner: s um
a
su m
0
10
0
0
9 (after a––)
10 [a [ after sum + (a––) is a post-decrement]
Here, the line: sum = sum + a–– a––;; //Post-decrement
first add the value a (10) with the old value of sum and then decrease the value of a as 9. That is, for the above line, the decrement value of a (9) does not affect the sum value. So, the execution of the equation becomes, sum = 0 + 10;
i.e. the new sum’s value becomes 10. It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value.
The "typeof" operator in JavaScript allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. There are six possible values that typeof returns: "number," "string," "boolean," "object," "function" and "undefined." The parentheses are optional in the typeof syntax. Table Ta ble 1.11 lists the possible return values of typeof. Table Tabl e 1.11 typedef return values. Evaluate to
I n d i ca t e s
"number" "st ri ng " "b ool ean" " o b j ec t " null "undefined"
Operand is a number Operand is a string Operand is a Boolean Operand is an object Operand is null Operand is not defined
Introduction to JavaScript
3.27
For example, var Num = 5; varr res va resul ultt = (t (type ypeof of Nu Num m === === 'n 'num umbe ber' r'); ); var eBook = "Multimedia For Class-XI"; varr res va resul ultt = (t (typ ypeo eoff eBo eBook ok == === = 'st 'stri ring ng'); '); var Num; var result = (Num === undefined); var result result = (typedef (typedef Num === 'undefined') 'undefined');;
// Re Retu turn rns s tru true e // Re Retu turn rns s tru true e // Returns true // Returns Returns true
The conditional operator, ? is JavaScript’s only ternary operator. A ternary operator requires three operands instead of the single and double operands of unary and binary operators. The conditional operator is used to replace if -else logic situations. The format of the conditional operator is: conditional_expression ? e x p r e s s i o n 1 : e x p r e s s i o n 2;
Here:
conditional_expression, expression1 and expression2 are expressions. If the value of conditional_expression is true, then the expression1 is evaluated and becomes the value of the conditional_expression, otherwise expression2 is evaluated and becomes the value of conditional_expression.
Exampl ple e
Consider the following three statements and write if-else statement for this: x = 10; y = 15;
// ......1 // .. ....2
z = (x>y ? x : y);
// ....3
Solution The statement 3 is equivalent to the following if-else: if (x>y) z = x; else z = y;
So the value of z = 15 because x is i s not greater than y. Here is another example of the way the ? is employed: flag = (age > 18 ? true : false);
When JavaScript evaluates this assignment expression, it first looks at the expression to the left of the question mark. If age is greater than 18, then expression between the question mark ( ?) and the colon (:) is evaluated and used as the value of the entire ? expression. If age is not greater than 18, then the expression after the colon ( :) is evaluated and used for the value of the entire ? expression. The result produced by the ? operator is then assigned to flag.
The value of null has a very special role in the JavaScript language. It is the value of last resort, so to speak, for every variable. For the beginning JavaScript programmer, its primary role will be initializing variables that do not have any more meaningful initial value, e.g., to initialize y to some value, we should have actually written, var y = null;
3.28
S araswati Multimedia and Web Technology (XI) Sa
This prevents JavaScript errors that arise when an uninitialized variable is accidentally used in an expression that requires a value. It is important to realize that the value of null (not NULL) does not give the variable y and implicit data type. Null also has the property that it may be converted to a form of all the other types. When it is converted to a number it becomes 0, when it is converted to a string it becomes the empty thing " " and when it is converted to a Boolean value it becomes false. This is the only case where it is permissible to change the implicit data type of a variable after it is declared. Therefore, statements such as: var ok = "Hello" + y; var w = x + y;
result in ok having the value "Hello" (the same as ok) and w having the value to (the same as x). This is why the value of null is an excellent way of initializing variables—it is guaranteed to be harmless.
1.13 JAVASCRIPT POPUP BOXES JavaScript has three built-in windows methods which are used to create popup boxes. These are: confirm(“message”). We
can display a confirm box to the visitor and ask their opinion. This confirm window will wil l have two buttons, one for OK and other for CANCEL. Visitor can click one of the two buttons and the user action can be captured by assigning this to a variable. The confirm box will return TRUE if the OK button is clicked and it will return FALSE if Cancel button is clicked. For example, var Choice = confirm("Do you want to continue ?"); if (Choice == true) { alert("User wants to continue!"); }else{ alert("User does not want to continue!"); }
An alert dialog box is mostly used to warn the user or alert him or her to something. In the following cases, one can use the alert() function: alert(“message”).
Incorrect information in a form An invalid result from a calculation A warning that a service is not available on a given date
For example, the simplest way to direct output to a dialog box is to use the alert() method. alert("Click Ok to continue.");
Exampl ple e
Sagarika works in a company where she was instructed to develop a web application to show an alert window displaying a message called "Welcome to multimedia course" as shown in given figure:
Write the complete code to satisfy the previous window.
Introduction to JavaScript
3.29
Solution The code is: (alert.html) My page <SCRIPT type="text/javascript" type="text/javascript"> > function show_alert() { var msg = "Welcom "Welcome e to multimedia course"; alert(msg); } prompt(“message”). The prompt command will
display a window and ask visitor to enter some data. We We can collect the data entered by the user and store them in a variable. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt() which takes two parameters: (i) A label label whi which ch you you want want to disp display lay in the the text text box box.. (ii) A def defaul aultt string string to to displa displayy in the the text text box. box. This dialog box is with two buttons: OK and Cancel. If the user clicks on the OK button, the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button, the window method prompt() returns null. For example, var myName = prompt("Enter your name : "); alert("You alert("Y ou have entered entered : " + myName);
When the above code is executed, we can show some default text while displaying the prompt. Here is an example where a default message is displayed for the visitor to enter first name. var myName = prompt("Enter your name : ", "your first name"); alert("You alert("Y ou have entered entered : " + myName);
Exampl ple e
Write a program in JavaScript to enter your name as FirstName and SecondName and display the name in an alert window. For example, if you enter the FirstName as “Harapriya” and the SecondName as “Parikar”, then the alert window will display: Hello Harapriya Parikar.
Solution The code is: Use of concatenation op erator >
Concatenation <SCRIPT type="text/javascript" type="text/javascript"> > var FirstName, SecondName, Result FirstName = prompt("Enter first name") SecondName = prompt("Enter last name") Result Resu lt = FirstN FirstName ame + " " + SecondNa SecondName me // + means "join" "join" here here alert("Hello, " + Result) // and here
3.30
S araswati Multimedia and Web Technology (XI) Sa
1 . A var vari iab le is a na nam m e for a m em ory loca ocat tion tha hat t is used u sed to ho hol ld a value of a par p art ticular data typ type. e. 2 . A variab abl le can st store ore onl o nly o ne value of its decl d eclar ared ed typ ype. e. 3 . C o ns nst tan ts ar a re sim ilar to to va var riab les bu b ut they ho h old a p articu cul lar va val lue for the d uratio n o f their exist ste enc nce e. 4 . T he em pty str string is a st str ring con cont taining no cha char ract acters. ers. 5. K eyw or ords ds (or (or reserv eserved ed w or ords) ds) ar are e reser reserved ved for use b y JavaS Ja vaS cr cri ipt pt. . 6 . J av avaS aS cr cri ip t is case ca se-se sens nsi itive ve—u —up p p ercase an and d low ercase le tters are are d ifferen erent t. 7. A const constant ant is a m ean ing ngf fulnam e that that take akes s the the place o f a nu m be ber r or st str ring and ne never ver chan change ge s. 8 . T he pref prefi ix and po st stf fix incr ncrem em en ent t an and d decrem d ecrem en ent t op erat erators ors ha have ve subtl su btle ef e ffects of program s, be cau cause se of differ eren ences, ces, w he hen n they ar are e eva eval lua uat ted . 9 . L og ica cal l o p erat erators ors ar a re a na nat tural ch choi oice to im p lem en ent t a co nd ition for a se sel lec ect tio n or rep rep etition stat st atem em en ent t be cause they ret etur urn n a B oo ool lean value. 10 . L og ical op erat erators ors ar are e used u sed to com co m bine on one e or o r m ore tha than n one o ne relat ati ion onal al exp expr ression ons. s. 11. The com m a enab e nabl les us to to p ut m or ore e than than one expr expressi essions,separ separat ated ed by com m a,on a single line. 12 . E xpression ons s are are com co m bina nat tion ons s of op er erat ators ors an and d ope o pe ran ands ds used u sed to per p erf form a calculat ati ion on. . 13 . J av avaS aS cr cri ip t alw ay ays s perf p erfo rm s m ultip lication , d ivision an and d m od ulus first st, , the n co com m p utes ad a d d ition and an d sub trac act tio n. 14. 14 . Th The e ar a rithm et eti ic op er erat ator ors s are are b inary oper ope rat ator ors s because be cause each op oper erat ates es on o n tw tw o o pe per rand s. 15. 15 . Th The e incr ncrem em en ent t op er erat ator or,+ + and the de decr crem em en ent t op er erat ator or —,incr ncrea ease se or o r de decr crease ease a vari variab abl le b y 1. 16 . If the inc ncr rem en ent t or d ec ecr rem en t op erat erator or is p refixed to the va var riab le , the va var riab le is increa ncrease sed d or d e cr crea ea se sed d b y 1 first an and d the n use d in its exp e xpr res essi sio n. 17 . If the increm ent or decrem de crem ent o p erato r is po p ost stf fixe xed d to the vari v ariab le, the va var riab le is use u sed d in its expr exp ression on, , the hen n incr ncrea eased sed or decr de crea eased sed by 1 . 18 . alert() fun unct cti ion is use u sed d to d isp spl lay a m es essag sag e to a d ialog b ox (also called alert b o x) x). . 19 . p rom pt() fun unct cti ion asks the use user r to inp ut som e inf nform orm at ati ion an and d st stores ores the the inf nform orm at ati ion in a vari va riab le. 20 . co confi nfirm () fun ction d isp spl lay ays s a co con nfirm b ox to to the visitor an and d as asks ks their op inio n. T his co nfirm w indo w w illhave tw tw o but bu ttons, one for O K and ot other her for C A N C E L.
S OLVED EXERCISES 1. Wh What at is is Jav JavaS aScr crip ipt? t? Ans. JavaScript is a scripting language designed primarily for adding interactivity to web pages and creating
web applications. 2. What are the adva advantag ntages es of the the JavaScript ? Ans. Following are the advantages of JavaScript:
JavaScript is no more difficult to learn than HTML . It allows people with little or no programming
experience who are daunted by Java’s complexity to create interactive and Web-based Web-based applications. JavaScript can be used to solve common problems, such as validating forms input and can also be used to create dramatic and visually appealing content, which would be impossible with HTML. JavaScript is one of the Dynamic HTMLs available in both Netscape Navigator and Internet Explorer. As JavaScript lives inside the HTML document, it can either exist as a complete script that is embedded in the
or elements or it can consist of event handlers that are written directly into the HTML code.
Introduction to JavaScript
3.31
3. Justify Justify,, “JavaScript “JavaScript is an interpr interpreted eted language” language”.. Ans. JavaScript was a purely interpreted language. This means that scripts execute without preliminary
compilation, i.e., without conversion of the script text into system-dependent machine code. The T he user's browser interprets the script, that is, analyses and immediately executes it. 4. What is the the use of of <SCRIPT> <SCRIPT> tag tag ? Explain Explain with syntax. syntax. Ans. The <SCRIPT> tag is used to add JavaScript commands to your HTML pages. <SCRIPT> is a container
tag that can accept the attribute LANGUAGE, which allows you to specify the scripting language used (JavaScript is generally the default). The syntax is: <SCRIPT LANGUAGE = "lang_name "lang_name"" [SRC = "URL"> script code
5. What What is the use of SRC SRC in in JavaScript syntax ? Ans. If the SRC attribute is specified then it should reference a URL containing code in the script language.
For JavaScript, this should be a valid URL for a file containing the JavaScript code. 6. Is there there any difference between <script language="J language="JavaScript"> avaScript"> and type="text/javascript". type="text/javascript". Ans. Yes. <script language="JavaScript"> is deprecated as "language" value is an identifier which has no
standards. type="text/javascript" is the correct syntax. This overrides the default scripting language. 7. Wh What at is va vari riab able le? ? Ans. A variable is an identifier, which holds a value. In programming, we say that we assign a value to a
variable. Technically speaking, a variable is a reference to the computer memory, where the value is stored. 8. What What is is rese reserv rvee word word? ? Ans. Some words cannot be used as variable names in JavaScript. These words are called keywords or reserved words. 9. How will will you you include include comm comments ents in the JavaScript ? Ans. Like other languages, JavaScript supports comments in its code. Comments are completely ignored by
the JavaScript interpreter, so you can type whatever descriptive text you want. There are two types of comments entry in JavaScript as: // Working Working with wit h JavaScript. (Single-line comment) /* JavaScript programming supports the control statements like: if, while and for */ (Multiline comment)
10. Expla Explain in about about the numb number er data data type type in JavaScript ? number s. The rules for specifying Ans. There are two numeric types in JavaScript: integers and floating-point numbers.
both types are almost almost identical. identical. Integers may be specified in base base 10 (decimal), base base 8 (octal) or base 16 (hexadecimal) formats. Any of the three forms can also start with a + or – sign. 11. How can can you you store store strin string g data data in JavaScript? Explain with example. Ans. A string is any grouping of characters that is surrounded by either double quotation marks (“) or single
quotation marks (‘). Strings are used anytime you want to use text in a program. For example, "Class-XI" "Multimedia & Web Technology"
12. Write the the general general rules rules for declar declaring ing variables variables in JavaScript. Ans. The general rules are:
The variable name cannot be a reserved word The first character in the name must be an alphabetic letter or an underscore(_)
3.32
13. Ans. 14. Ans. 15. Ans. 16. Ans.
S araswati Multimedia and Web Technology (XI) Sa
Characters subsequent to the first character in the variable name can be alphabetic letters, numbers or underscores. Variables are case sensitive.
Which escape escape sequences sequences represent the newline newline character character and tab in JavaScript ?
The escape sequences are : \n and \t Whatt is a logic Wha logical al expre expressi ssion? on?
A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or false. What are are the types types of numeric numeric values values in JavaScrpt JavaScrpt? ?
JavaScript has two kinds of numeric values—integers and floating point. Whatt is esc Wha escape ape se seque quence nce? ?
Combination of characters is preceded by a code-extension character (also called the escape character). The code-extension character indicates that the succeeding characters are interpreted differently. differently. Escape sequences are normally used to control printed or displayed output. The characters interpreted with a backslash (\) are called escape sequences or escape characters.
17. What are oper operator ators? s? Name Name them them.. Ans. Operators are special symbols that perform a particular function on operands. There are five general
types of operators: arithmetical, logical, comparison, assignment and bitwise operators. 18. Ans. 19. Ans.
Name two two specific specific purposes purposes for for the + operato operatorr.
The + operator can be used for f or arithmetic addition and for string stri ng concatenation. Explain about conditi conditional onal operat operator or with with its its syntax. syntax. The conditional operator ? is JavaScript’s only ternary operator. A ternary operator requires three
operands instead of the single and double operands of unary and binary operators. The conditional operator is used to replace if -else logic situations. The format of the conditional operator is: conditional_expression ? expression1 : expression2; 20. Wha Whatt are are expr express ession ions? s? Ans. Expressions are combinations of operators and operands used to perform a calculation. For example, varr SI; va SI; // Si Simp mple le in inte tere rest st // Evaluated expression SI. SI = (principal * rate * interest) / 100
21. Wh What at is a lite litera ral? l? ‘A’ is Ans. A literal is a sequence of characters used in a program to represent a constant value. For example, ‘A’
a literal that represents the value A, of type char, and 17L is a literal that represents r epresents the number 17 as a value of type long. A literal is a way of writing a value, and should not be confused with the value itself. 22. Wha Whatt is str string ing lite literal ral? ? Ans. A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be
delimited by quotes of the same type; that is, either both single quotes or double quotes. 23. Explai Explain n an assignment assignment statement statement giving an example. example. What are assignment assignment statemen statements ts used for? Ansn. An assignment statement computes a value and stores that value in a variable. Examples include:
x = 17; // Assign a constant value to th the variable x. newRow newR ow = row; // Copy the value value from the variable variable row row into the the variable variable newRow newRow.. ans = 17*x + 42; // Compute the value of the expression 17*x + 42 and store that value in ans. An assignment statement is used to change the value of a variable as the program is running. Since the value assigned to the variable can be another variable or an expression, assignment statements can be used to copy data from one place to another in a computer, and to do complex computations. 24. State State the the differ difference ence betw between een = and ==. ==. Ans. The ‘=’ (assignment operator) is to assign the value of the variables, whereas ‘==’ (relational operator)
Introduction to JavaScript
3.33
is to compare two values. For example, intt x = 10 in 1000; // Si Simp mple le as assi sign gnme ment nt int y = 102; if (x==y) // Co Compares tw two op operands 25. Write a JavaScr JavaScript ipt statement statement to accom accomplish plish each each of the following following tasks: ( a Declare re variable variabless sum and a to be of of type int. a)) Decla ( b Assign ign 1 to varia variable ble a. a. b)) Ass c)) Ass ( c Assign ign 0 to variab variable le sum. sum. ( d ) Add variable a to variable sum sum and assign assign the result to variable sum. sum. (e) Print “The “The sum is: “ followed followed by the the value of variable variable sum. sum. (b) a = 1; Ans. (a) var sum, a; (c) sum = 0; (d ) sum += a; a; or sum = sum sum + a; a; (e) docume document.wri nt.write("Th te("Thee sum is: " + sum); 26. What are are relationa relationall operators operators? ? Give examp examples. les. Ans. The operators that are used to do comparisons are called relational operators. For example, >, >=, <, <=,
etc. 27. What is is the differe difference nce between between / and % operator? operator? Ans. The / operator is used to find the quotient and the % operator produces remainder after dividing two
numbers with each other. For example, 5/2 produces 2 (quotient) and 5%2 produces 1 (reminder). 28. What is the use use and syntax of a ternary ternary opera operator? tor? Ans. The conditional operator (?) is a ternary operator, because it uses three operands. This operator is used
to check a condition and produce a logical result, either True or False. The syntax is: condition ? expression1 : expression2; 29. Give one point of differe difference nce between between unary unary and binary binary operators operators.. Ans. Unary Operators: A type of operators that work with one operand. For example, -,++,-- are the unary
operators. The operators are used with one operand as follows: -a; N++;; N++ --x; Binary operators: A type of operators that work with two operands are known as binary operators. +,-,*,/,% these are binary operators. 30. Give the meaning meaning of each each of the following following JavaSc JavaScript ript operato operators: rs: ( a ( b ( c a)) ++ b)) && c)) != Ans. (a) The operator ++ is used to add 1 to the value of a variable. For example, example, "count++" has the same
effect as "count = count + 1". (b) The operator “&&” represents represents the word and. and. It can be used to combine combine two Boolean Boolean values, as in "(x > 0 && y > 0)", which means, "x is greater than 0 and y is greater than 0." (c) The operation != means "is not equal to", as in "if (x != 0)", meaning "if x is not equal equal to zero". 31. If a = 5, b = 9, calcu calculat latee the value value of: a+= a++ – ++b ++b + a; Ans. The value is 6. 32. What will will be the outpu outputt of the followi following ng stateme statement? nt? document.write ("1" + 3); Ans. It will print 13. 33. Wha Whatt is the the output output of of the follo followin wing? g? document.write("four :" + 4 + 2 + " "); document.write("four :" + (2 + 2));
3.34
S araswati Multimedia and Web Technology (XI) Sa
Ans. The output is as follows:
four :42 four :4 34. If a = 5, b = 9, calcu calculat latee the value value of: a+= a++ – ++b ++b + a; Ans. The value is 6. 35. What will will be the output output of of the follow following ing progra program? m? var num = parseInt(100.2); var perc = num; document.write(" " + perc);
Ans. The output is: 100 36. What are the values values of x and y when the followi following ng statements statements are execut executed? ed? var a = 63, b = 36; var x = (a > b ? true : false); var y = (a < b ? a : b);
Ans. The value of x = true.
The value of y = 36. 37. What will be the the result stored stored in x after after evaluating evaluating the following following expression? expression? var x = 4; x += (x++) + (++x) + x;
Ans. The result of x = 20. 38. What is the output output of the followin following g code in JavaScri JavaScript? pt? Give reaso reason. n. ( a 10+2 +20+ 0+"3 "30" 0" a)) 10 ( b "10" 0"+2 +20+ 0+30 30 b)) "1 there is numeric value before and after +, it is treated as binary + Ans. (a) 3030 because 10+20 will be 30. If there
(arithmetic operator). (b) The output is 102030 because after a string all the + will be treated as string concatenation operator (not binary +). 39. Find the outp output ut of of the foll followin owing: g: var v = 1, a = 1, b = 2, c, d; c = ++b; c = ++b; d = a++; c++; document.write((v == 1 ? "A" : "B") + " "); v++; document.write((v == 1 ? "A" : "B") + " "); document.write("a = " + a + " "); document.write("b = " + b + " "); document.write("c = " + c + " "); document.write("d = " + d); Ans. The output is: (outputa.html)
A B a =2 b = 4 c =5 d =1 40. Write four four different different JavaScript JavaScript statements statements that each each add 1 to integer variable variable num. Assum Assumee that the initial value of num is 0.
Introduction to JavaScript
3.35
Ans. Four different JavaScript statements are: (a) nu num m = num num + 1; 1; (b) nu num m += += 1; 1; (c) ++num; (d ) nu num m++; 41. Write a statement statement for each each of of the follow following: ing: ( a Store re a number number 275 275 as a String String a)) Sto b)) Conve ( b Convert rt the String String to a numer numeric ic value ( c existing g total of 1000 1000 to update update the total. total. c)) Add it to the existin "275"; "; Ans. (a) var num = "275 (b) var num = parse parseInt(x Int(x); ); (c) var tota totall = 1000 1000 + Nnum; Nnum; 42. What are the the values values of x and y when when the followin following g statements statements are are executed? executed? var a=63, b = 36; var x = a > b ? true : false; var y = a < b ? a : b;
Ans. The value of x = true.
The value of y = 36. 43. What will be the the result stored stored in x after after evaluating evaluating the following following expression? expression? var x=4; x+=(x++)+(++x)+x;
Ans. The result of x = 20. 44. Exp Explai lain n the follo followin wing g comman command: d: document.write ("Hello World .")
World.”. Ans. The write() method of document object prints a string called “Hello World.”. 45. What is a unary opera operator? tor? Write Write two unary opera operators tors.. unary operator. The ‘++ ‘ (increment ) and ‘– –’ Ans. The operator which needs only one operand is called unary (decrement) operators. 46. What will will be displaye displayed d in the followi following ng line of of a web browser browser? ? document.write("Live\nIn Peace\tand harmony");
Ans. The output is: Live In Peace and harmony
47. Write the statements for the each situation described below: (i) Assig Assignn a value value 2 to the variab variable le A. (ii) Assig Assignn the value represente representedd by variable N to the variable variable N1. (iii) Print the the string string "February" "February" on the the string. string. (iv) Assig Assignn the value represent represented ed by the formula formula A2 + B2 + C to the variable X. (v) Increa Increase se the value value of the variable variable count count by 2. (vi) Assig Assignn the value value 3 to the variable variable C1, C1, C2, C3. C3. (vii) Print the value C1, C1, C2, C3 in single line. (viii) Print the value value C1, C2, C3 in three three separate separate lines. lines. (ix) Print the value of of C1, C2, C3 in one line with some space between between them. ( x statement Hello! World World in the following format : x) Print the statement
Hello! World. Ans.
(i) var A = 2;
(iii) document.write("February");
(ii) var N = 100; var N1 = N; (iv) var X = A^2 + B^2 + C;
48. Write JavaScr JavaScript ipt statement statementss to accomplis accomplish h each of the the following: following: ( a increment the value of a by 1 after calculation. Use only one a)) Assign the sum of a and b to c and increment statement. ( b variable a by 1, then subtract it from the variable num. Use Use only one statement. statement. b)) Decrease the variable ( c Calculate te the remainder remainder after q is divided divided by divisor and assign assign the result result to q. Write this statement statement c)) Calcula in two different ways. (b) sum –= – –a; Ans. (a) c = a++ + b; (c) q %= di divi viso sor; r;
q = q % divisor; 49. What will will be the output output of of the follow following ing progra program m: var x = 2, y = parseFloat(5.00); document.write("The value of x is " + x+10*y + " "); document.write("The value of y is " + x+10/y);
Ans. The output is:
The value of x is 250 The value of y is 22 50. Evaluate Evaluate the following following expressions, expressions, if the values values of the variables variables are are a = 2, b = 3 and c = 9. ( a (b++ ++)) * ( –– c) ( b (++ +b) % c –– c) a)) a = (b b)) a = (+ value of the express expression ion is: is: – 24 24 Ans. (a) The value (b) The value value of the the expressi expression on is: 5 51. Write the the results results of the following following JavaScrip JavaScriptt statements: statements: var c, d = true, e = false; c = d & e; document.write("Value of c: "+ c + " "); d &= e; document.write("\nValue of d: "+ d + " "); e = d; document.write("\nValue of e: "+ e + " "); c ^= e; document.write("\nValue of c: " +c);
Ans. The results are:
Value of o f c: 0 Value of d: 0 Value of o f e: 0 Value of o f c: 0 52. What will will be the the output output of the the followin following g code segm segment? ent? var a = 5, b = 10, c = 9, d = 8; document.write(" " + ((a++) + (++c) - (--b) + (d--))); document.write(" " + a>b ? c>d ? ++d : 35 : --b); Ans.
The output is line: document.write(" " + ((a++) + (++c) - (--b) + (d--))); is 14. The output is line: document.write(" " + a>b ? c>d ? ++d : 35 : --b); is 8.
Introduction to JavaScript
3.37
53. Rewr Rewrite ite the follo following wing in Terna ernary ry operato operatorr if (income <= 10000) tax = 0; else tax =12;
Ans. The statement is:
tax = income <= 10000 ? 0 : 12; 54. Differentiate between confirm() and alert() methods. Ans. The confirm() method of window object brings up a dialog box with Yes or No buttons and a userspecified message. The alert() method brings up an alert dialog box. alert(….) is the standard function for bringing up an alert dialog box on the screen. 55. Write a JavaScript JavaScript code code to enter the price price of a pencil pencil and quantity quantity of pencils and and calculate calculate total amount amount as price*quantity. price*quant ity. Display the amount and tax as 10% in browser window. Ans. The JavaScript code is: ( price.html) Price calculation LE> <SCRIPT type="text/javascript" type="text/javascript"> > varr pri va price ce = par parse seFl Floa oat( t(pr prom ompt pt(' ('En Ente terr pri price ce')) '));; varr qt va qty y = pa pars rseI eInt nt(pr (prom ompt pt(' ('En Ente terr qu quan anti tity ty') ')); ); var tot = price * qty; // Total price var tax = tot * 10/1 /10 00 ; // Tax am amount document.write("T document.write(" Total price: " + tot + " "); document.write("Tax: " +tax);
// Pri Price ce of pen penci cill // Qu Quan anti tity ty of pe penc ncil il
What are variables? Describe the five categories of the JavaScript. What is the use of SRC? What attribute can the JavaScript <SCRIPT> tag accept? What is the difference between single-line and multiline comments? How many data types are available in the JavaScript? What is the use of bitwise operator? What are keywords? What are the rules to be followed while naming the identifier? Classify the following into valid and invalid identifier: (i) My M ybook (ii) Break (iii) _DK (iv) My My.b .boo ook k What are integer variables? What are character variables? What are float-point variables? How will statements get terminated in JavaScript? Write a statement to declare three integers integers and store them in the variables x, y and z.
3.38
S araswati Multimedia and Web Technology (XI) Sa
16. Answer the following: (a) Assig Assignn the value of the variable variable number1 number1 to the variable variable total. (b) Assign the sum sum of the two two variables loop_count and petrol_cost to the variable sum. (c) Assign the the character character W to the the char variable variable letter letter. (d ) Assign the result of dividing the integer variable sum by 3 into the float variable costing. Use type-
casting to ensure that the remainder is also held by the float variable. (e) Divide the variables total by the value 10 and and leave the result in the variable discount. 17. Answer the following using JavaScript statement: (a) to print print out the the value value of the intege integerr variable variable sum. sum. (b) to print print out the charact character er variable variable letter letter.. (c) to print print a float float variable variable into the the variable variable discoun discount_rate t_rate.. 18. Which of the following are invalid names and why? (i) PaidInterest (ii) s-num (iii) percent (iv) 123 (v) dit km (vi) class (vii) main 19. What value will be stored in different variables when the following JavaScript statements are executed? var i = 10; var j = i + 5; var k= i + j / 5; var l = k + 1; var m = l + 1 – i; var n = k + m * l; document.write(i + " " + " " " " + k + " " + " " " " + l + " " + " " " " + m + " " + " " + n);
20. Is the line given below a valid comment? // This is a /* valid*/ comment
21. Correct the error, if any, in the following statements: (i) var 3* 5; (ii) l*b = area; (iii) l = ab + c*d; (v) area = 3.14 * R**R; 22. What will be the output of the following statements:
(iv) A = P * R * N/100;
var a= 10; var b= 5; var c= 7; document.write(a + " " + b + " " + c + " "); document.write(a + "\t" + b + "\t" + c + " "); document.write(a + "\n" + b + "\n" + c);
23. In each of the following cases, show how the comment can be placed in the JavaScript program: (i) Add the the programprogram-hea headin dingg Sum of the odd and even numbers. (ii) Add the com commen mentt average value to the statement: x = sum/n;
(iii) Add the comme comment nt begin of main with the main() statement. 24. Give the output of the following program segment: var i = 100, j = 9; document.write(i/j);
25. What is the purpose of comments and indentation in a program? 26. What will be the output of the following program? var x=2; var y=5; document.write("The value of x is " + x + 10 * y); document.write("The value of y is "+ x + 10 / y);
JavaScript Functions
3.39
JavaScri Ja rip pt F unctions Functions
2
2.1 INTRODUCTION The basic statements, expressions and operators that were discussed in previous chapter is what computer scientists usually call primitives. Primitives are the building blocks from which more complex elements of a program are construc constructed. ted. Functions and objects represen representt the highest level of organizati organization on within the JavaScript language.
2.2 FUNCTIONS A function is a block of code that will be executed when "someone" " someone" calls it. In JavaScript, we can define defin e our own functions, called user-defined functions, or we can use built-in functions already defined in the JavaScript language. We We have already seen examples of built-in functions, such as:
Below, we will show how to define our own user-defined functions. Functions Func tions are the central working units uni ts of JavaScript.
A function definition is just a regular variable definition where the value given to the variable happens to be a function. A function is a block of code that has a name. Whenever that name is used the function is called, which means that the code within that function is executed. Functions may also be called with values, known as parameters, which may be used inside the body of the function. Functions serve two purposes:
A function is an organizational tool, in the sense that it permits you to perform the same operation without simply copying the same code. The second purpose of JavaScript functions is to link actions on a Web page with JavaScript code. Mouse clicks, button presses, text selection and other user actions can call JavaScript functions by including suitable tags in the HTML source for the page.
JavaScript provides several ways of defining them:
Function Declaration Function Expression
3.39
3.40
S araswati Multimedia and Web Technology (XI) Sa
Function as a result of a new Function call
A function is written as a code block (inside curly { } braces), preceded by the functio preceded functionn keywo keyword. rd. The basic syntax to creat createe a functi function on is a Function Declaration. The syntax is: function function_name (arg1, arg2, ....) { some statements/code statements/code;; return somevalue; }
Not e
J a va S cr ipt is c a s e s e ns it ive . The T he funct ion ke keyword yword mus t be writt e n in lowerc lowercaa s e let t e rs , an andd the t he func functt ion mus t be ca ll llee d with the t he s a me ca pit pitaa ls a s us e d in t he functt ion na me func me..
From the above syntax,
The function_name is given immediately after the function keyword. All function names should be unique and also should not conflict with any of the statement names which JavaScript itself uses (known as the reserved words). For example, you cannot have a function named while and you should not have two functions both named diplay_name. The arg1, arg2, .... is a comma-separated list of the values that are passed into the function. These are referred to as function’s parameters or arguments. This list may be empty, indicating that the function does not use any argument (often called a void function). The function’s body (statements) is the set of statements that make up the function. The return statement is option, but a function can return a value.
The code inside the function will be executed when "someone" calls the function. The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript code. JavaScript user-defined functions should be defined in the HEAD section of an HTML document. The reason for placing JavaScript functions in the HEAD section is the function must be defined and loaded into memory before the function can be called by JavaScript code or an event handler. Below,, we define a function named print_message() in the HEAD section of the webpage. The function Below contains one statement of code, to display a message box. The function is called later in a SCRIPT element in the BODY section of the webpage. Exampl ple e
Using the JavaScript code write the HTML code to demonstrate the user-defined function.
Solution Write the following code in Notepad editor and save as jfun01.html. Simple function demo <SCRIPT type="text/javascript" type="text/javascript"> > // Called function func fu ncti tion on pr prin int_ t_me mess ssag age( e()) // Def Defin ine e fun funct ctio ion n pri print nt_m _mes essa sage ge() () { alert("Function to avoid repetition of code"); } <script language = "JavaScript"> print_message(); // Call function print_message()
JavaScript Functions
3.41
In the above program the function print_message() is invoked from JavaScript. Then the control passes to print_message() function, and the body of the function gets executed. Simultaneously the execution control returned back to JavaScript to execute the remaining statements.
Figure 2.1 A simple function output.
Here from the function declaration, the JavaScript , which invokes the function print_message() , is called the calling function and the function print_message() is the called function. Exampl ple e
Write a JavaScript function to display the temperature value in an alert window. The code should enter the temperature value in an HTML text box.
Solution Write the following code in Notepad editor and save as jfun02.html. Temperature in Fahrenheit > <SCRIPT type="text/javascript" type="text/javascript"> > function show_temp() { var Tval=frm.txt.value; alert("The temperature in Fahrenheit is " + Tval + " degrees F.") }
Here, a FORM is used to hold a text entry box labeled txt and a push button labeled show_temp. When the user clicks on this button, the associated JavaScript function show_temp() is invoked. The statement, var Tval=frm.txt.value;
inside the function show_temp() sets the variable and allows access to the text entry box txt. alert() abd displays the temperature value by using concatenated strings operator +.
3.42
S araswati Multimedia and Web Technology (XI) Sa
After typing, save the file with the name ...\Unit 3\Chapter 2\jfun02.html and browse in IE. In IE when you enter the details and press the Temperature button, the screen will look as shown in Figure 2.2.
Figure 2.2 Function to display temperature.
2.2.1 Function Returning Value A JavaScript function can return a value using return statement. The value returned can be a valid JavaScript type. A return statement determines the value the function returns. When control comes across such a statement, it immediately jumps out of the current function and gives the returned value to the code that called the function. function. The syntax syntax is: is: return (return value) value);
When using the return statement, the function will stop executing, and return the specified value.
2.2.2 Function Using Arguments/Parameters Arguments/Parameters Like other programming languages, a JavaScript function can also handle arguments in its function. The parameters to a function behave like regular variables, but their initial values are given by the caller of the function, not the code in the function itself. When you call a function, you can pass along some values to it, these values are called parameters or arguments. Parameters are the variables we specify when we define the function. When the function is later called somewhere else in the code, arguments are the th e values passed as parameters. You You can specify as many parameters as you like, separated by commas (,). The parameters then serve as variables that can be used inside the function. JavaScript passes values by reference, meaning that when you pass a value to a function, you are really just passing a value pointer to the function. (A value pointer pointer is just an address, similar to a house address address on an envelope that gives information about how to find the house.) If the function modifies that value, the value is changed for the entire script, not just the scope of the function. For example, <script language = "JavaScript"> function welcome(myName) // In the function declaration, we specify the parameter myName { alert( "Welcome "Welcome " + myName + " to my website!" ); }
JavaScript Functions
3.43
<script language = "JavaScript"> // When the the function is called, "Navya Singhal" is is the argument argument passed to the function function welc we lcom ome( e( "Na "Navy vya a Sing Singha hal" l" ); ); // Fu Func ncti tion on ar argu gume ment nt "Welcome e Navya Singhal to my website!" when the The function above will display the message box "Welcom function is called in the webpage.
The variables (or parameters) which accept the actual variables inside the function are called formal variables. Each function definition contains an argument list called the formal argument list. Items in the list are optional, so the actual list may be empty or it may contain any combination of data types such as inteter, float and character. For example, // Formal arguments in function declaration <SCRIPT type="text/javascript" type="text/javascript"> > function welcome(myName) { alert( "Welcome "Welcome " + myName + " to my website!" ); }
Here, myName is a formal arguments. Let us consider another example, function maxTwo(a, maxTwo(a, b) { if (a > b) return a; else return b; }
In the above function, a and b are formal parameters. They are called formal because actual parameter values are supplied to the function by the calling program, and formal parameters use the copy of those actual parameters. parameter s.
The variables which are associated with function name during function call are called actual variables. When the program calls the function, an argument list is also passed to the function. This list is called the actual argument list. For example, <SCRIPT type="text/javascript" type="text/javascript"> > // Function to find the average average of 3 numbers numbers functi fun ction on cal calc_A c_Avg( vg(num num1, 1, num num2, 2, num num3) 3) // Formal Formal parame paramete ters rs { varr loc va local al_a _avg vg;; // Hol olds ds av ave era rage ge for th the ese num umbe bers rs local_avg = (num1 + num2 + num3) / 3; return (local_avg); } // Call the function, function, passing the numbers, and accept accept return value varr avg va avg = cal calc_ c_Av Avg( g(10 100, 0, 23 235, 5, 40 400) 0);; // Ac Actu tual al pa para rame mete ters rs ....
S araswati Multimedia and Web Technology (XI) Sa
3.44 ....
Here, 100, 235, and 400 are the actual arguments, which are passed into the calc_Avg() function. Exampl ple e
Write a JavaScript function to find the average of three numbers. The three numbers should be treated as parameter to the function. Also, function should return the average and all details.
Solution Write the following code in Notepad editor and save as jfun01.html. JavaScript Function return Example <SCRIPT type="text/javascript type="text/javascript"> "> // Function to find find the average average of 3 numbers numbers func fu ncti tion on cal alc c_A _Avg vg(n (num um1, 1, nu num2 m2,, nu num3 m3)) // Fo Form rma al par param ame ete terrs { varr loca va local_ l_av avg; g; // Ho Hold lds s ave avera rage ge fo forr th thes ese e nu numb mber ers s local_avg = (num1 + num2 + num3) / 3; return (local_avg); } var num1 = 100, num2 = 235, num3 = 400; varr avg; va avg; // Wi Will ll ho hold ld th the e ret retur urn n val value ue // Call the function, function, passing the numbers, and accept accept return value avg = calc_Avg(n (nu um1, num2, num3); // Ac Actual pa parrameters document.write("The first number is : " + num1 + " "); document.write("The second second number is : " + num2 + " "); document.write("The third third number is : " + num3 + " "); document.write("The average average is : " + avg );
Open the jfun02.html file in IE, and see the output window as shown in Figure 2.3.
Figue 2.3 Average of three numbers.
The calc_Avg() function above takes three numbers as parameters, and returns the average of the three numbers. On Line, avg = calc_Avg(num1, num2, num3);
JavaScript Functions
3.45
when the calc_Avg() function is called, the value 245 is returned and then stored in the variable avg. The above declaration is called function expression. When the JavaScript parser sees a function in the main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a Function Expression. You can also use the value returned by the calc_Avg() function without storing it as a variable. For document.write() () line: instance, we could call the function and use the return value in the document.write document.write("The document.write("Th e average is : " + cal_Avg(num1, num2, num3);
Exampl ple e A web page for an organization is given below:
Write a JavaScript function called Fullname() to concatenate two names and also display in third textbox.
Solution Write the following code in Notepad editor and save as jfun03.html. Employees Employe es Payroll > <SCRIPT type="text/javascript" type="text/javascript"> > function Fullname() { var nName = frm.txt1.value + " " + frm.txt2.value; frm.txt3.value = nName; }
Real Value System - Employees Payroll
2.3 SCOPE AND LIFETIME OF VARIABLES The scope of a variable means how the different parts of the program can access that variable. When scope of a variable is used in a method, the variable affects only that method. The scope of a variable is that region of the program within which it can be used. The lifetime of a variable is the period during which it can be accessed. JavaScript has five kinds of variables: loop scopes, local variables, static variables, instance variables and class variables.
In the previous chapter, we declared different variables inside loops. Any variables created inside a loop are treated as local scope or local variables to the loop. This T his means that once you exit the loop, the variable can no longer be accessed. This includes any variables created in the loop signature. Let us see following two examples: Example 1: for (i = 0; i <= 10; i++) { document.write("\nloop scope variable " + i + " "); } Example 2: var i; for (i = 0; i <= 10; i++) { document.write(("\nloop scope variable " + i + " "); }
In Example 1, i can only be used inside the for loop. In Example 2, you are free to use i inside the loop as well as outside the loop because it was declared outside the loop (it has been declared as method scope).
The variables which are declared inside a function/method are called local variables. variables. You may use a local variable completely within wit hin a function definition. definition . Its scope is then limited to the function itself, i.e., i.e ., it can be used only within the declaring method. The variable is said to be accessible or visible within the function only and has a local scope. For example, <SCRIPT type="text/javascript" type="text/javascript"> > // Function to find the average average of 3 numbers numbers function calc_Avg(num1, num2, num3) {
JavaScript Functions
3.47
var local_avg; // Holds average for these numbers local_avg = (num1 + num2 + num3) / 3; return (local_avg); } var num1 = 100, num2 = 235, num3 = 400; varr avg; va avg; // Wi Will ll ho hold ld th the e re retu turn rn va valu lue e // Call the function, function, passing the numbers, and accept accept return value value avg = calc_Avg(num1, num2, num3); document.write("The document.write("T he first number is : " + num1 + " "); document.write("The document.write("T he second number is : " + num2 + " "); document.write("The document.write("T he third number is : " + num3 + " "); document.write("The document.write ("The average is : " + local_avg);
Here in line, document.write("The document.write("Th e average is : " + local_avg);
will produce an arror, because local_avg is a local variable to the function. You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Following are some of the features of local variables:
They can be used only in those statements that are inside the same block in which local variables are declared. That is, the local variables are not known outside of their own code block. For example, fun1() { varr a = 5; va // a is is a lo loca call var variiab able le an and d blo bloc ck sco scope pe } fun2() { var a = 10 10;; // a is a local variable variable and and block scope scope }
Here, the integer variable a is declared twice, once in fun1() and once in fun2(), but the a in fun1() has no effect on function fun2(). This is because a is known only to the code within the block in which it is declared. Local variables are deleted from memory as soon as the function is completed
We can also declare local variables inside any code block that is nested inside another code block.
For example, consider the following function: void fun() { var age = prompt("Enter your age") if (age == 18) { document.write("Your document.write("Y our age is accurate for voting"); } }
Here, the local variable guess is created at the entry of the function fun() and so its scope remains until the terminating curly brace of the function fun() is encountered. However, the local variable age is created upon entry into the if code code block and destroyed upon the exit from the if block. That is, age is known only within the block and cannot be referenced elsewhere within the outer block (i.e., of the fun()). if block We can initialize the local variable var iable to some value. Now, this value will be assigned to the variable variab le each time we will enter the block of code in which it was declared, no matter if the value is later modified in the block. If you try to access the local variable outside the method, the compiler would flag it as an error. However, the same variable name can be declared within several different methods without there being a conflict.
3.48
S araswati Multimedia and Web Technology (XI) Sa Not e
To de cla re J a va To vaS S cr cript ipt globa glob a l variab var iables les ins inside ide func functt ion, you ne e d to us e window wind ow obje c t . Whenn you de cla Whe clare re a var variab iable le var i; // i is a global variable outside out side th thee funct function, ion, it is ad adde dedd thee window obje object ct inte interna rna ll llyy. There can be situations where a local variable with the same name in th Yo Y o u c ca a n a c c e s s it t h r o u gh is used in a function. Then the local variable hides the global variable, winn d o w o b je c t a ls o . Fo Forr i.e., the function will give preference to the local variable as compared wi example: to the global variable.
A global scope variable is visible to all functions/methods and is declared outside the method, and all scripts and functions on the web page can access it. For example,
Global variables, variables declared outside of a function, are deleted when you close the page. The following example, describes both global and local variables in JavaScript program:
var Num = 10 10;; funct ion a( a(){ ){ / / ac acce cess ss ing global variable alert (wi (window ndow.v .value) alue);; }
<SCRIPT type="text/javascript" type="text/javascript"> > // Difference between Global and Local Variables Variables // Declare the global variables var global_one = 32; var global_two; function test { // This function has a local variable a global value is copied into into it // the local is then passed into into a function as a parameter var local_var; // Local variable loc oca al_ l_va varr = gl glob oba al_ l_on one e; // Co Copy py gl glob obal al // into local func_two(local_var); } function func_two(number) { // create a local variable and copy a parameter parameter into it var local_var = number; } // copying a local variable into a global // like this is not allowed allowed global_two = local_var
2.4 JAVASCRIPT BUILT-IN FUNCTIONS JavaScript has several "top-level" built-in functions. These functions f unctions perform themselvesf with other JavaScript statements. JavaScript JavaScr ipt function is a name, which is pre-written in the interpreter. interpr eter. Table 2.1 shows some of them. Table Tab le 2.1 JavaScript built-in functions. Function Name
Descript ion
eval(string)
Evaluates codestring as JavaScript code, returning anything that JavaScript returns. Returns the conversion of charstring into a form that displays in the browser without HTML markup.
escape(string)
JavaScript Functions
3.49
This is just reverse of escape function. Returns true if numvalue is not a number, otherwise returns false— IsNan(numValue) used with parseFloat and parseInt function. Converts a string into an integer. parseInt(numString) parseFloat(numString, radix) Converts a string into a floating-point number. round(number) To get rounded value of a number. ceil(number) To get the next higher integer. floor(number) To get just next highest lower integer. To get the power of an integer. pow(number) To get the highest integer from a set of number. max(number) To get get square root of any number. sqrt(number) unescape(string)
eval(). This function evaluates a string
as a JavaScript statement or expression, and either executes it or returns the resulting value. The syntax is: eval(string)
A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. For example, eval(n eval (new ew St Stri ring ng(" ("2 2 + 2") 2")); ); // re retu turn rns s a St Stri ring ng obj objec ectt con conta tain inin ing g "2 "2 + 2" eval("2 + 2"); // returns 4 var x = 2; var y = 4; var x = 2 var y = 39 var z = "42" document.write(eval("x document.write(e val("x + y + 1")) document.write(eval(z)) escape(). This
function encodes the string passed to it so that it can be used across any network, say, for example, in query strings. The syntax is: escape(string)
string is a String object or literal to be encoded. For example, document.write(escape("te document.wri te(escape("testing sting escape function!!"));
which prints: testing%20escape%20function%21%21
escape() function leaves digits,latin letters and the characters + - * / . _ @ unchanged and replaces all other characters with ASCII code of the original or iginal character preceded by % symbol. unescape(). This method is used to
decode the encoded strings and returns the t he ASCII string for the
specified value. The syntax is: unescape(string)
string is a String object or literal to be encoded.
S araswati Multimedia and Web Technology (XI) Sa
3.50
For each distinct set of characters in the argument string of the following form
"%integer", where integer is a number between 0 and 255 (decimal) "hex", where hex is a number between 0x0 and 0xFF (hexadecimal) (hex adecimal)
For example, unescape("%26") unescape("ab%21%23"
// re returns "&" // returns "ab!#"
isNaN(). This
function determines whether the value of a variable is a legal number or not. This function is remembered as short form is Is Not a Number Number . This function returns true if the data is string and returns false if the data is a number. Here is one simple example to check one string. The syntax is: isNaN(numValue)
numValue numV alue is the value to be tested against NaN.
If you fa face ce pro proble blem m t o find t he ree s ult in IE, r IE, us e s om e ot o t he r brows br ows e r.
// true true // true // false // false // f al alse
// true: true: "abcdefg" "abcdefg" is conver converted ted to a number number.. // Parsing this as a number fails fails and returns returns NaN document.write(isNaN("")) document.write( isNaN(""));; // false: the empty string is converted to 0 which is not NaN document.write(isNaN("30")) document.write (isNaN("30")) // false false // dates document.write(isNaN(ne document.w rite(isNaN(new w Date())); // false doc do cume men nt.wr wriite(i (is sNa NaN( N(n new Dat Date() ()..toS oSttring ng() ())) ));; // true true
The function is better use in if condition to check to display a message accordingly. For example, var myString = prompt("Enter a number"); if (isNaN(myString)) { alert("This is not a number "); } else { alert("This is a number "); } parseInt(). This
function is used to convert strings to numbers. This function can only convert strings which are in the form of numbers and it can't change any alphabet or strings. If there is no number at the beginning of the string, "NaN" (not a number) is returned. The syntax is: parseInt(numString, [radix])
Here, numString is string to convert into a number.
JavaScript Functions
3.51
For example, docume docu ment nt.w .wri rite te(p (par arse seIn Int( t("1 "124 24.5 .56" 6")) ));; docu do cume ment nt.w .wri rite te(p (par arse seIn Int( t("a "abc bc34 34") ")); ); docum doc ument ent.w .writ rite(p e(pars arseIn eInt(" t("25. 25.5ab 5abc" c")); )); document docu ment.wr .write ite(par (parseI seInt(" nt("216.0 216.0PLL") PLL")); );
// retu return rn 124 124.. // Retu Return rns s NaN. NaN. // Ret Return urns s 25. 25. // Retu Returns rns 216.
parseFloat(). This function is used to convert
strings to float numbers. Using this function, we can only convert string numbers to numeric data but we can't convert alphabetic characters. The syntax is: parseFloat(numString)
Here, numString is string that contains contai ns a floating-point number to convert conv ert into a number. The parseFloat function returns a numerical value equal to the number contained in numString. If no prefix of numString can be successfully parsed into a floating-point number, NaN (not a number) is returned. For example, document. docume nt.wri write te(pa (pars rseF eFloa loat(" t("124 124.5 .56") 6"))) document.write(" "); docum doc ument ent.w .writ rite(p e(pars arseFl eFloat oat("a ("abc3 bc34") 4")); ); documen docu ment.wr t.write ite(par (parseFl seFloat( oat("25. "25.5abc 5abc")); ")); document.write document .write(parseFl (parseFloat("216 oat("216.0PLL")); .0PLL"));
This function is used to round off any number number with decimal place to an integer value by using round function. If the decimal portion of the number is equal or greater than .5 then the next higher integer is returned or if i f the number is less than 05 then t hen the number is rounded to next lowest integer. The syntax is: round().
Math.round(number)
For example, docume docu ment nt.w .wri rite te (M (Mat ath. h.ro roun und( d(22 22.7 .75) 5)); ); document.write(" "); docu do cume ment nt.w .wri rite te (M (Mat ath. h.ro roun und( d(17 17.0 .05) 5)); ); docume doc ument nt.w .wri rite te (Ma (Math th.r .roun ound(d(-22. 22.75) 75)); ); docume doc ument nt.w .wri rite te (Ma (Math th.r .roun ound(d(-18. 18.15) 15)); ); docu do cume ment nt.w .wri rite te (M (Mat ath. h.ro roun und( d(21 21.6 .65) 5)); );
// prin printt 23 // prin printt 17 // print print -23 // print print -18 // prin printt 22
We can format math number by using round function. Here is an example to format upto two decimal places. var Num = 11.257; document.write (Math.round(Num (Math.round(Num * 100) / 100); ceil(). This
function is used ceil of a number to the smallest integer that is greater than or equal to given number. So by using this we can get the next higher integer of a given number. The syntax is: Math.ceil(number)
For example, docume docu ment nt.w .wri rite te (Ma (Math th.c .cei eil( l(24 24.3 .314 14)) ));; doc do cum ume ent.writ ite e (M (Math.ceil( l(20 20..56) 6)); ); docu do cume ment nt.w .wri rite te (Ma (Math th.c .cei eil( l(-1 -13. 3.56 564) 4)); );
// outp output ut 25 25 // out outpu putt 21 // out outpu putt -13 -13
floor(). This function is used to get the floor of a number or the largest integer which is equal to or
lower than the given number. So by using floor we can get the floor value of an number.
3.52
S araswati Multimedia and Web Technology (XI) Sa
The syntax is: Math.floor(number)
For example, docume docu ment nt.w .wri rite te (Ma (Math th.f .flo loor or(2 (24. 4.31 314) 4)); ); docu do cume ment nt.w .wri rite te (Ma (Math th.f .flo loor or(2 (20. 0.56 56)) ));; docume doc ument nt.wr .writ ite e (Mat (Math.f h.floo loor( r(-13 -13.56 .564)) 4));; pow(number).
// outp output ut 24 // out outpu putt 20 // outpu outputt -14
This function is used to get the power of an integer. The syntax is:
Math.pow(x,y)
For example, document.write(Math.pow(5,5)); document.write(Math.pow(0,0)); document.write(Math.pow(0,1)); document.write(Math.pow(1,0)); document.write(Math.pow(1,1)); document.write(Math.pow(2,2)); document.write(Math.pow(2,-2)); document.write(Math.pow(-2,2)); max(number).
// output is 3125 // ou output is is 1 // ou output is is 0 // ou output is is 1 // ou output is is 1 // ou output is is 4 // ou output is 0. 0.25 // outpu putt is is 4
This function is used to get highest value from a set of numbers. The syntax is:
Math.max(x1,x2,x3,….xn)
For example, docume docu ment nt.w .wri rite te(M (Mat ath. h.ma max( x(23 23,1 ,12, 2,24 24,1 ,15, 5,17 17,,5) 5)); ); document.write(" "); docu do cume ment nt.w .wri ritte( e(M Mat ath. h.ma max( x(-5 -5,,16 16,,-22 22,1 ,12, 2,-2 -20) 0)); ); document.write(" "); document.write(Math.max(-12,-23,-3)); sqrt(number).
// ou outp tput ut is 24 // ou outp tput ut is 16 // output is -3
To get square root of any number. The syntax is:
Math.sqrt(x);
For example, doc ocu ument nt..write(M (Ma ath.sqrt(4) 4)); ); document.write(" "); docu do cume ment nt.w .wri ritte( e(M Mat ath. h.sq sqrt rt(6 (64) 4)); ); document.write(" "); doc ocu ument nt..write(M (Ma ath.sqrt(9) 9)); ); document.write(" "); docu do cume ment nt.w .wri rite te(M (Mat ath. h.sq sqrt rt(2 (27) 7)); ); document.write(" "); docum doc umen ent. t.wr writ ite(M e(Mat ath. h.sq sqrt rt(0 (0.3 .36)) 6));; document.write(" "); docu do cume ment nt.w .wri rite te(M (Mat ath. h.sq sqrt rt((-64 64)) ));;
// ou outtpu putt is is 2 // out outpu putt is 8 // ou outtpu putt is is 3 // outpu outputt is 5. 5.19 1961 6152 5242 4227 2706 0663 632 2 // outpu outputt is 0.6 0.6 // outp output ut is is Nan Nan
The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times. JavaScript’s Date object follows the UNIX standard of storing date and time information internally as the