Download presentation
Presentation is loading. Please wait.
Published byLinette Miles Modified over 9 years ago
1
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 sunny.shi@senecacollege.ca SENECA COLLEGE
2
22 Outline Overview of JavaScript Scratchpad Javascript Basics Three programming Constructs Built-in functions Next Class – More about JavaScript functions
3
Overview of JavaScript Originally developed in Dec 1995 by Brendan Eich at Netscape.Brendan Eich Not Java Standard version is called ECMAScript, The ECMAScript standard is documented in the ECMA-262 specification JavaScript without purchasing a license. 3
4
Overview of JavaScript small, light-weight, cross-platform, object-oriented scripting language. Interpreted language Loose data-type programming language adding interactivity to static HTML pages. embedded to HTML pages working in major browsers, e.g, I.E. Firefox, Chrome, Opera, Safari. Everyone can use 4
5
What Can JavaScript do? usually on client side to add interactivity to the HTML documents. also possible to use JavaScript for server-side programming. also significantly used for other applications outside of web pages 5
6
What Can JavaScript do? Respond to events on the web pages, such as button clicks, mouse moving, objects getting/ losing focus. Validate user’s input before sending out the request to server. Create/open or close a window in run time. Write information to web pages dynamically. Change web page contents. Change web page styles. Build small but complete client-side applications. Communicate asynchronously with the server. Develop visualizations, animations, and games on web pages without the need for a Java applet or Flash plugin. 6
7
Demo ChangeContent.html ChangeStyle.html Dynamic_window.html Pizza.html Title_game.html 7
8
Scratchpad Firefox -> Tools -> Web Developer -> Scratchpad Mozilla Developer Network (MDN) online help documentation: https://developer.mozilla.org/en- US/docs/Tools/Scratchpad https://developer.mozilla.org/en- US/docs/Tools/Scratchpad
9
Scratchpad Input: var x = prompt(“Enter a number”, “0”); // x is a string Output: alert(“information to display”);
10
Example var x = 2; x = parseInt(prompt("Input a number", "")); var y =0; y = parseInt(prompt("Input 2nd number"," ")); var z = x+y; alert (z); // alert(“x+y=” +z); //alert(x+ "+" + y + "=" + z);
11
JavaScript MDN (Mozilla Developer Network) Javascript Guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide JavaScript is a loosely typed language. Do not have to specify the data type of a variable when you declare it. Data types are converted automatically as needed during script execution. 11
12
12 Data Types Primitive types – Boolean, Number, String Complex type – Object (including Array, Function, Date, Math, and RegExp) Special values – Null, Undefined var variableName; var variableName = "This is a String"; var variableName = 'This is a String'; var variableName = 45.55; var variableName = 45; var variableName = true; var variableName = null; var myDate = new Date(); var x = prompt(“Enter a number”, “0”);
13
13 JavaScript Comments Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. // this is a single line comment Multi line comments start with /* and end with */. /* these are multi-line comments */ Using Comments to Prevent Execution // document.write(" This is a heading "); /*document.write(" This is a paragraph. "); document.write(" This is another paragraph. ") */ Using Comments at the End of a Line document.write (“hello world.”); // write “hello world”
14
14 JavaScript Variables A JavaScript variable naming rules: - must start with a letter or underscore ("_") -subsequent characters can be letters, underscores or digits. Declare (Create) a variable” -var courseName; -If do not initialize a variable, its value is “undefined” Assign values to variables: courseName=“BTI220”; Initialization: var courseName=“BTI220”;
15
15 JavaScript Variables Assigning Values to Undeclared JavaScript Variables the variables will automatically be declared and becomes Global variable. x = 5; Attention: x=5; x=“abc”; // allowed
16
16 Expressions An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value. The value may be a number, a string, or a logical value. Two types of expressions: 1) those that assign a value to a variable, e.g. x = 7. 2) those that simply have a value, e.g., 3 + 4 simply evaluates to 7; it does not perform an assignment. JavaScript has the following kinds of expressions: 1)Arithmetic - evaluates to a number 2)String - evaluates to a character string 3)Logical - evaluates to true or false
17
17 A Conditional Expression Syntax: (condition) ? val1 : val2; If the condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a conditional expression anywhere you would use a standard expression. e.g., grade = (mark >= 50) ? “pass" : “fail";
18
18 Arithmetic Operators OperatorDescriptionExampleResult +Additionx=y+2x=7 -Subtractionx=y-2x=3 *Multiplicationx=y*2x=10 /Divisionx=y/2x=2.5 %Modulus (division remainder) x=y%2x=1 ++Incrementx=++yx=6 --Decrementx=--yx=4 Given Y=5
19
19 Assignment operators Assign values to variables. Given x=10, y=5 OperatorExampleSame AsResult =x=y x=5 +=x+=yx=x+yx=15 -=x-=yx=x-yx=5 *=x*=yx=x*yx=50 /=x/=yx=x/yx=2 %=x%=yx=x%yx=0
20
20 The + Operator Used on Strings Concatenate two strings x=“abc” y=“123” x+y =>“abc123” x+” “+y => “abc 123”
21
21 Adding Strings and Numbers 1.x =5+5; document.write(x); 2.x="5"+"5"; document.write(x); 3.x=5+"5"; document.write(x); 4.x="5"+5; document.write(x); 1. 10 2,3,4. 55
22
Comparison Operators Given x=5: Operat or DescriptionExample ==is equal tox==8 is false x=8 is true ( in condition) x==“5” is true ===is exactly equal to (value and type) x===5 is true x==="5" is false !=is not equalx!=8 is true x!=5 is false !==is not equal (neither value nor type) x!==“5” is true x!==5 is false >is greater thanx>8 is false <is less thanx<8 is true >=is greater than or equal tox>=8 is false <=is less than or equal tox<=8 is true
23
23 if (y===“5") document.write("true"); else document.write("false"); y=5; if (y==“5") document.write("true"); else document.write("false"); if (y="7") document.write("true"); else document.write("false"); true false true if (y=== 5) document.write("true"); else document.write("false"); true
24
Summary of the Differences From C 1.Define a variable – var x=6; – x=“abc”; // allowed, even x was previously defined as a number 2.+ on strings – 5+”abc” – 5+”6” 3.Comparison with ==, === – 5==“5” //true – 5===“5” //false 4./ on integer numbers – var x=9; – var y=x/2; //4.5 5.% on double numbers – var x = 4.1 %2 ; // 0.09999999999999964
25
Summary of the Differences From C (cont’d) Strings 1.assignment var x=“abc”; x =“def”; 2.Concatination 5+”abc” 5+”6” 3.Comparison var x=“abc”; var y=“abd”; if ( x<y) //true 4.String length var x=“abc”; var y=x.length; //3
26
Programming Constructs – Sequence var x = 5; var y=6; var z = x+y; alert(z);
27
27 Programming Constructs – Selection if if (mark > 90) grade=‘A+’; if/else if (mark > 90) grade=‘A+’; else grade=‘A’;
28
28 Switch statement: select one of many blocks of code to be executed. switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } Programming Constructs – Selection
29
29 y=1; switch (y) { case 1: alert("111"); case 2: alert("222"); case 3: alert("333"); default: alert("ddd"); } y=1; switch (y) { case 1: alert("111"); break; case 2: alert("222"); break; case 3: alert("333"); break; default: alert("ddd"); } 111 222 333 ddd
30
30 Programming Constructs – Iteration while do/while for
31
31 The while loop while (condition) { action statement(s) } var i=1; while (i<5) { alert("week "+i + ":" + i); i++; }
32
32 The do...while Loop do { action statements } while (condition) var i=10; while (i<5) { alert(“week “+i); i++; }
33
33 The for loop for (initialExp ; condition ; updateExp) { statement(s) to be repeated } for (i=1; i<5; i++) { alert("week "+i ); }
34
34 Break Statements Break the loop and continue executing the code that follows after the loop (if any). var i=1; while (i<5) { alert(“week “+i); if (i==3) break; else i++; }
35
35 Break Statements Break the current loop and continue with the next value. (nested loops). var i=1; var j=1; while (i<5) { alert('week: '+i ); for (j=1; j<=7; j++) { alert('day:'+j +'of week:'+ i); if (j==3) break; } // for i++; } // while
36
36 Functions (1) built-in functions/ global functions (2) user-defined functions/ custom built functions
37
Where to use JavaScript Functions Similar to C functions, defined/called in applications for event handlers on the web pages. Be triggered/ executed/ called/invoked when some events occur on the web page – JavaScript functions are actions or behaviors that are associated with the events on web pages. associated to an object to specify the behavior of the object. – a method or a member function. 37
38
38 Built-in functions Are functions that are built into the JavaScript language. They have already been defined and the logic behind them has already been coded for your use - you simply use them.
39
39 Built-in functions eval() one argument: a string. If the string is an expression, eval() evaluates the expression. If the string is made up of JavaScript statements, eval() performs the statements. Syntax : eval(string) var x = 2; var y = 4; alert(x+y); alert(eval("x+y")); // 6
40
40 Built-in functions isNaN() to determine if an argument is "NaN" (not a number). Syntax : isNaN(a test value) alert(isNaN("avc")); // true alert(isNaN("123")); //false alert(isNaN(123)); // false
41
41 Built-in functions parseFloat(): parses a string and returns a floating point number. If a character other than a numeral, a sign (+ or -), or an exponent is found, the function returns the value up to that point. If the first character in the string cannot be converted to a number, the function returns "NaN". Syntax : parseFloat(string ) alert(parseFloat("12.66")); // 12.66 alert(parseFloat("12.4ff")); // 12.4 alert(parseFloat("abc")); // NaN
42
42 Built-in functions parseInt() parses its first argument (a string), and then tries to return an integer of the specified radix (or base). If a number in the string is beyond the base, parseInt() ignores the rest of the characters and returns an integer value up to that point. If the first character can't be converted to a number, parseInt() returns "NaN". Syntax : parseInt("string", base) parseInt(15.99, 10) // 15 parseInt("F", 16) // 15 parseInt(“10”, 8) // 8
43
Built-in functions Number()/ String() convert an object to a number or a string. x = "12.78"; y = 10; z = Number(x) + y; alert("sss =" + String(y)); 43
44
Built-in functions toFixed() formats a number to a specific number of digits to the right of the decimal. var x = 12.98943; alert(x.toFixed()); // 13 note that, 0 digit alert(x.toFixed(2) ); // 12.99 note the rounding alert(x.toFixed(6)); // 12.989430 Note: this is a function of Number object instead of a global function
45
Summary of Built-in Functions prompt() alert() eval() isNaN() parseInt() parseFloat() Number() String() toFixed()
46
46 User-defined functions Syntax: function fname(var1,var2,...) { code block } Need to call to execute fname(arg1, arg2,…); Do not need to specify return data type
47
47 User-defined functions Function with return values The return statement is used to specify the value that is returned from the function. function fname(var1,var2,...) { code block return value; } Eg, function sq(x) { return x*x; } y = 10; alert(sq(y));
48
User-defined functions If the function does not have a return statement it still has a value undefined (except the constructor). if (funcName(arg1, arg2,...) === undefined) // true { // will do something here... } 48
49
Functions The scope of a variable: the scope available to access. Local variables – Declared (using var) within a JavaScript function becomes LOCAL – can only be accessed from within that function. – the variable has local scope. 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. Local variables are deleted as soon as the function is completed. Global variables – Declared outside a function – all scripts and functions on the web page can access it.
50
Functions Lifetime of JavaScript variables – starts when they are declared. – Local variables are deleted when the function is completed. – Global variables are deleted when you close the page. Undeclared JavaScript Variables – are GLOBAL variables.
51
Example function f() { x = "abc "; // global variable alert("x is global: "+ x); // ok, display “abc” var y= "abd"; // local variable alert(“y is local: " +y); // ok, display “abd” } f(); alert("outside function, x = "+ x); // output: abc***: alert("outside function, y = "+ y); // Exception: y is not defined
52
52 Guidelines JavaScript is Case Sensitive courseName != coursename Semicolon is optional White Space – JavaScript ignores extra spaces. They are equivalent: courseName=“INT222"; courseName = “INT222"; – sometimes, it is different with or with no space: var x=6; var s1 = “ab c”; var s2= “ab c”;
53
Next Class More about JavaScript functions Closure Anonymous functions Recursion 53
54
Thank you!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.