Week1-2 - Seneca College

advertisement
INT222 - Internet Fundamentals
Shi, Yue (Sunny)
Office: T2095
sunny.shi@senecacollege.ca
SENECA COLLEGE
Outline
•
•
•
•
•
•
Overview of JavaScript
Scratchpad
Javascript Basics
Three programming Constructs
Built-in functions
Next Class
– More about JavaScript functions
2
Overview of JavaScript
• Originally developed in Dec 1995 by Brendan Eich at Netscape.
• Not Java
• Standard version is called ECMAScript,
• The ECMAScript standard is documented in the ECMA-262 specification
• JavaScript without purchasing a license.
3
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
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
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
Demo
•
•
•
•
•
ChangeContent.html
ChangeStyle.html
Dynamic_window.html
Pizza.html
Title_game.html
7
Scratchpad
• Firefox -> Tools -> Web Developer -> Scratchpad
• Mozilla Developer Network (MDN) online help
documentation:
• https://developer.mozilla.org/enUS/docs/Tools/Scratchpad
Scratchpad
• Input:
var x = prompt(“Enter a number”, “0”); // x is a
string
• Output:
alert(“information to display”);
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);
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
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”);
12
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("<h1>This is a heading</h1>");
/*document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>") */
•
Using Comments at the End of a Line
document.write (“hello world.”); // write “hello world”
13
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”;
14
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
15
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
16
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";
17
Arithmetic Operators
Given Y=5
Operator
Description
Example
Result
+
Addition
x=y+2
x=7
-
Subtraction
x=y-2
x=3
*
Multiplication
x=y*2
x=10
/
Division
x=y/2
x=2.5
%
Modulus
(division
remainder)
x=y%2
x=1
++
Increment
x=++y
x=6
--
Decrement
x=--y
x=4
18
Assignment operators
• Assign values to variables.
• Given x=10, y=5
Operator
Example
Same As
Result
=
x=y
+=
x+=y
x=x+y
x=15
-=
x-=y
x=x-y
x=5
*=
x*=y
x=x*y
x=50
/=
x/=y
x=x/y
x=2
%=
x%=y
x=x%y
x=0
x=5
19
The + Operator Used on Strings
•
•
•
•
•
Concatenate two strings
x=“abc”
y=“123”
x+y =>“abc123”
x+” “+y => “abc 123”
20
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
21
Comparison Operators
• Given x=5:
Operat
or
Description
Example
==
is equal to
x==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 equal
x!=8 is true
x!=5 is false
!==
is not equal (neither value
nor type)
x!==“5” is true
x!==5 is false
>
is greater than
x>8 is false
<
is less than
x<8 is true
>=
is greater than or equal to
x>=8 is false
<=
is less than or equal to
x<=8 is true
y=5;
if (y==“5")
document.write("true");
else
document.write("false");
if (y===“5")
document.write("true");
else
document.write("false");
if (y=== 5)
document.write("true");
else
document.write("false");
if (y="7")
document.write("true");
else
document.write("false");
 true
 false
 true
 true
23
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
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
Programming Constructs – Sequence
var x = 5;
var y=6;
var z = x+y;
alert(z);
Programming Constructs –
Selection
• if
if (mark > 90)
grade=‘A+’;
• if/else
if (mark > 90)
grade=‘A+’;
else
grade=‘A’;
27
Programming Constructs
– Selection
• 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
}
28
y=1;
switch (y)
{
case 1:
alert("111");
case 2:
alert("222");
case 3:
alert("333");
default:
alert("ddd");
}
111
222
333
y=1;
switch (y)
{
case 1:
alert("111");
break;
case 2:
alert("222");
break;
case 3:
alert("333");
break;
default:
alert("ddd");
}
111
ddd
29
Programming Constructs –
Iteration
• while
• do/while
• for
30
The while loop
while (condition)
{
action statement(s)
}
var i=1;
while (i<5)
{ alert("week "+i + ":" + i);
i++;
}
31
The do...while Loop
do {
action statements
}
while (condition)
var i=10;
while (i<5)
{ alert(“week “+i);
i++;
}
32
The for loop
for (initialExp ; condition ; updateExp)
{
statement(s) to be repeated
}
for (i=1; i<5; i++)
{
alert("week "+i );
}
33
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++;
}
34
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
35
Functions
(1) built-in functions/ global functions
(2) user-defined functions/ custom built functions
36
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
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.
38
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
39
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
40
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
41
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
42
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
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
Summary of Built-in Functions
•
•
•
•
•
•
•
•
•
prompt()
alert()
eval()
isNaN()
parseInt()
parseFloat()
Number()
String()
toFixed()
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
46
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));
47
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
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.
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.
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
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;
varx=6;
var s1 = “ab
var s2= “ab c”;
c”;
52
Next Class
•
•
•
•
More about JavaScript functions
Closure
Anonymous functions
Recursion
53
Thank you!
Download