chapter 4: fundamentals of javascript

Download Chapter 4: Fundamentals of JavaScript

If you can't read please download the document

Upload: carlyn

Post on 07-Jan-2016

31 views

Category:

Documents


1 download

DESCRIPTION

Chapter 4: Fundamentals of JavaScript. 4.1 Capabilities 4.2 Essential Terminology 4.3 Structure of JavaScript Code 4.4 Data and Objects 4.5 Tokens, Operators, Expressions, and Statements 4.6 The JavaScript math Object 4.7 Comparison Operators and Decision-Making Structures - PowerPoint PPT Presentation

TRANSCRIPT

  • Chapter 4: Fundamentals of JavaScript

    4.1 Capabilities4.2 Essential Terminology4.3 Structure of JavaScript Code4.4 Data and Objects4.5 Tokens, Operators, Expressions, and Statements 4.6 The JavaScript math Object4.7 Comparison Operators and Decision-Making Structures4.8 Loop Structures4.9 Using JavaScript to Change Values in Form Fields

  • 4.1 Capabilities of JavaScriptManage input and output.

    Permit information to be manipulated in a symbolic way, independent of how a particular computer stores that information internally.

    Perform arithmetic operations on numbers.

    Perform operations on and with strings of characters.

    Make decisions based on comparing values.

    Perform repetitive calculations.

  • 4.2 Some Essential Terminologyexpression a group of tokens and operatorsidentifier a name associated with a variable, object or functionkeyword a word with a specific meaning in a programming languageliteral an actual value embedded in a scriptoperator a token that symbolizes a mathematical or other operationprogram a series of interpreted or compiled statementsreserved word a word that might become part of a languagescript a series of JavaScript statementsstatement a command that changes outcomes in a programtoken an indivisible lexical unit in a programming languagevariable a place in memory that holds data, represented by a uniqueidentifier

  • 4.3 JavaScript StatementsUsually embedded inside script tags.Built from tokens.Each statement should terminate with a semicolon.Statements are "free format" and can appear anywhere on a line.Multiple statements on a line are allowed if each is terminated with a semicolon.Statement blocks begin and end with curly brackets:

    {statements go here}

    Comments:

    // single line comments /* Multiple line comments cannot be nested one inside another. */

  • Data and ObjectsAll information in JavaScript is associated with a data type, either explicitly or implicitly.Each data type is stored differently and each is associated with a specific set of allowed operations.Variables serve as data "containers." Each "container" is given a symbolic name (its identifier). When done explicitly, this is called a "data declaration."JavaScript data declarations are done explicitly with the var keyword.JavaScript is a "weakly typed" language. You aren't required to do explicit variable declarations, and data types can be changed during a script, "on the fly."A JavaScript identifier reserves a place in memory for a variable, but does not dictate the type of the data. You can change not only the value of the contents whenever you want, but also the data type. That is, JavaScript will infer data type based on the contents of a variable "container." You cannot do this in languages such as Fortran and C!!JavaScript supports three basic data types ("primitives") numbers, strings of characters, and boolean (true or false).JavaScript variable names are always case-sensitive.

  • LiteralsIn the statements name="Professor Wonderful"; and pi=3.14; the values on the right are literals a string literal in the first case and a numeric literal in the second.

    You should avoid using literals in your code. It is better to assign literal values to a variable with an identifier.

  • Objects and MethodsIn plain language, an "object" is a "thing" that has properties and can do things. A ball is an object. It has a size and a color. It can roll and bounce, etc.Languages such as JavaScript have "objects." These objects have properties (document.lastModifed) and methods document.write() ) that define what can be done by and to them.

  • The prompt() and alert() MethodsWe will use these two methods for now to minimize interactions with HTML.Document 4.1 (circle.htm)

    var radius=prompt("Give the radius of a circle: "); var area=Math.PI*radius*radius; alert("The area of the circle with radius="+radius+ " is "+area+".");

  • Some String Methods (just a few)(See Table 4.2.)

    charAt(n) "HTML".charAt(3); returns a value of L. concat({two or more string arguments}) var s="I".concat(" love"," HTML.");s has value I love HTML.

    substr(m[,len]) excel.substr(0,5); returns a value of excel. excel.substr(2); returns a value of cel.

    toLowerCase() var h="HTML";h=h.toLowerCase();replaces h with the new value html.

  • JavaScript's OperatorsTable 4.3. JavaScripts arithmetic operators.var a=3,b=4,c=5;var x,y;x=a+b*c; // has a value of 23y=(a+b)*c; // has as value of 35

    OperatorSymbolExamplesPrecedenceAddition+3 + 42Subtraction-z 102Multiplication*a*b1Division/z/3.3331modulus (remainder)%17%3 (= 2), 16.6%2.7 (=0.4) 1

  • The JavaScript Assignment OperatorThe JavaScript assignment operator is the "equals" sign (=).The assignment operator is NOT the same as the "equality" sign from mathematics.The meaning of the assignment operator is: Evaluate the expression on the right side of the assignment operator and assign the result to the identifier on the left side of the assignment operator. In algebra, x=a+b and a+b=x are equivalent. In JavaScript, only x=a+b; is allowed. In algebra, x=x+1 makes no sense at all, but in JavaScript, x=x+1; is a perfectly reasonable statement.Only an identifier can appear on the left side of the assignment operator in a JavaScript statement.

  • Shorthand Arithmetic/Assignment OperatorsTable 4.4. Shorthand arithmetic/assignment operators.

    OperatorImplementationInterpretation+=x+=y;x=x+y;-=x-=y;x=x-y;*=x*=y;x=x*y;/=x/=y;x=x/y;%=x%=y;x=x%y;++x++; or ++x;x=x+1;--y--; or --y;x=x-1;

  • The Math Object Properties

    PropertyDescriptionMath.EBase of the natural logarithm, e, 2.71828Math.LN2Natural logarithm of 2, 0.693147Math.LN10Natural logarithm of 10, 2.302585Math.LOG2ELog to the base 2 of e, 1.442695Math.LOG10ELog to the base 10 of e, 0.434294Math.PI, 3.1415927Math.SQRT1_2Square root of , 0.7071067Math.SQRT2Square root of 2, 1.4142136

  • The Math Object Methods

    MethodReturnsMath.abs(x)Absolute value of xMath.acos(x)Arc cosine of x, , for -1x1Math.asin(x)Arc sine of x, /2, for -1x1Math.atan(x)Arc tangent of x, /2, for -

  • Some DetailsBase 10 log of x: Math.log(x)/Math.log(10);

    or, using the Math.LN10 property,

    Math.log(x)/Math.LN10;

    Math.round(Math.random()*(n-m))+m;

    with (Math) { {statements that refer to properties and/or methods of the Math object for example,} var x=sin(.197);}

  • Using the Math ObjectDocument 4.3 (mathFunctions2.htm)

    Demonstration of the Math object. for (var i=1; i

  • Relational and Logical Operators

    OperatorInterpretationMathSymbolPrecedenceExampleValueRelational17.5false>=greater than or equal to217.7>=17.7true

  • if then else Constructsif ( {an expression. If true, statements are executed}){{statements here}}// optionallyelse if ( {an expression. If true, statements are executed}){{statements here}}// optionally, more else if statements// optionallyelse{{statements here}}

  • Using an if StatementOnly the first branch of an if statement for which the expression evaluates as true will be taken. Document 4.4 (grades.htm) Get letter grade var grade=prompt("What is your numerical grade?"); document.write("For a numerical grade of "+grade+

    ", your letter grade is "); if (grade >= 90) document.write("A"); else if (grade >= 80) document.write("B"); else if (grade >= 70) document.write("C"); else if (grade >= 60) document.write("D"); else document.write("F"); document.write(".");

  • Potential Problems with if StatementIf today is Tuesday or Thursday, I should be in class.

    if ((today == "Tuesday") || (today == "Thursday"))

    ??? What happens if this expression is rewritten as

    (today == "Tuesday" || "Thursday") // don't do it!

    An alternate version of the original expression, without the two inner sets of parentheses is:

    // poor style!(today == "Tuesday" || today == "Thursday")

    ??? What happens if

    if ((today = "Tuesday") || (today = "Thursday"))

  • The switch() ConstructFrom Document 4.6 (daysInMonth.htm) var month=prompt("Give month (1-12): "); switch (month) { case "1": case "3": case "5": case "7": case "8": case "10": case "12": alert("There are 31 days in this month."); break; case "4": case "6": case "9": case "11": alert("There are 30 days in this month."); break; case "2": alert("There are either 28 or 29 days in this month."); break; default: alert("I do not understand your month entry."); }