Introduction to JavaScript for Python Programmers Jay Summet CS 1301

advertisement
Introduction to JavaScript for
Python Programmers
Jay Summet
CS 1301
CS 1 with Robots
Lecture Outline
How Python & JavaScript are similar
How Python & Javascript are different
JavaScript fundamentals
JavaScript Examples
2
Python & Javascript: Similarities
Both are programming languages
Used by programmers to tell the computer what to do.
Both are interpreted languages
JavaScript is interpreted by the web browser, Python is
interpreted by IDLE or the python interpreter.
Both used to implement algorithms
Series of actions and calculations, that use decisions and
loops to control the flow of execution.
Both are imperative languages
3
Python & Javascript: Differences
Different web browsers support different JavaScript code.
The basic syntax works on all browsers, but some browsers
support non-standard extensions that are not supported on
other browsers.
The source code can be stored inside of a web page,
sometimes intermixed with HTML.
Web browsers typically do not provide good debugging
information about why a JavaScript fails, so debugging a
non-working script can be difficult.
The Syntax of Python & Javascript are different
Statements can be terminated with semi-colons.
Brackets must be used to indicate blocks.
4
Javascript in a Web Page
JavaScript is separated from HTML by putting it inside of
special script tags:
<script laguage=javascript>
JAVASCRIPT
JAVASCRIPT
</script>
Some javascript is actually part of HTML, for example, a
function call on a button press:
onClick=”cwCalc();”
Output from a JavaScript program usually is shown to the
user as HTML that is rendered by the web browser.
5
Javascript: Syntax Differences
Indentation does NOT indicate blocks. Instead, curly
brackets are used to indicate blocks. (Like C and C++)
Python:
def myFunc(aVar):
if (aVar == “test”):
return( 0)
else:
return(-1)
JavaScript:
function myFunc(aVar) {
if (aVar == 'test') {
return(0)
} else {
return (-1)
}
}
6
Javascript: Indentation does NOT matter!
This:
function myFunc(aVar) {
if (aVar == 'test') {
return(0)
} else {
return (-1)
}
}
functions the same as this:
function myFunc(aVar) {
if (aVar == 'test') {
return(0)
} else {
return (-1)
} }
7
But please use good indentation!
Improves readability and understandability
function myFunc(aVar)
{
if (aVar == 'test')
{
return(0)
}
else
{
return (-1)
}
}
8
Calling Functions, & Returning Values
The previous example should make it clear that calling
functions and returning values works basically the same in
JavaScript as it does in Python.
function myFunc(aVar)
{
if (aVar == 'test')
{
return(0)
}
else
{
return (-1)
}
}
myfunc(“aString”)
9
Declaring Variables and Arrays
Variables must be declared before being used:
var VARIABLENAME = VALUE
var myName = “Jay”
The “VAR” keyword tells the JavaScript interpreter that
you are making a variable.
Arrays must have their size declared at time of creation:
var ARRAYNAME = new Array(SIZE)
var myArray = new Array(50)
You index elements in an array using bracket notation:
var oneElement = myArray[1]
10
Conditional (IF) Statements
Very similar in Python & JavaScript.
IF and IF/ELSE are the same (except for brackets). No
ELIF statement.
“Weird Conditionals”: I won't talk about them, if you run
into them, do a quick web search to figure out how they
work.
Switch/case/break
?:
11
Looping (while) statement
Very similar in Python & JavaScript.
while (BOOLEAN EXPRESSION) {
STATEMENT;
STATEMENT;
}
New do/while statement. Test is performed at the end of
the loop instead of the beginning:
do {
STATEMENT;
STATEMENT;
} while (BOOLEAN EXPRESSION)
12
Looping (for) statement
FOR loops in JavaScript are based on C and C++ syntax,
and are usually quite different than in Python.
for( INITIALIZE; BOOLEAN EXPRESSION; ACTION)
{
STATEMENT;
STATEMENT;
}
for (var j = 0; j < 5; j = j+1)
{
document.write(“j is: “ + j)
}
13
Looping (for) statement
FOR loops in JavaScript are based on C and C++ syntax,
and are usually quite different than in Python.
for( INITIALIZE; BOOLEAN EXPRESSION; ACTION)
{
STATEMENT;
}
Code before the first semicolon (the initialization code) is
executed once at the beginning of the loop.
The boolean expression (in the middle) is evaluated every
time the loop repeats, and the statements in the loop are
only executed if the result is TRUE.
The action code is executed after the loop executes, and
is typically used to increment a counter.
14
Looping (for) Statement Example
for (var j = 0; j < 5; j = j+1)
{
document.write(“j is: “ + j)
}
The document.write statement executes 5 times, with j
equalling 0,1,2,3, and 4. After the 5th execution, the j=j+1
action executes, and then the j < 5 test evaluates to
FALSE, so document.write() does not execute when j = 5.
15
Looping (for) Statement – Iteration over Properties
JavaScript does have a FOR/IN version of the for loop,
but it doesn't work exactly as you'd expect from your
experience with Python's FOR loops.
for (VARNAME in OBJECT)
{
document.write( VARNAME )
document.write( OBJECT[VARNAME] )
}
Note that it iterates through the property names of an
object, and you have to use bracket notation to get the
property values.
16
Input / Output with JavaScript
As most JavaScript runs inside of a web browser, most of
the input and output to and from a JavaScript program
goes through the web-browser.
Input comes from the user via web forms, button and link
clicks.
Output is typically is displayed as a webpage or part of a
webpage as HTML rendered by the web browser.
17
Webpage Output with JavaScript
A script can use the document.write( “a string”) function to
add content to a web page as it is loaded.
<html>
<body>
<h1>Example:</h1>
<script language=javascript>
document.write(“<h2>Here is my website!</h2>”)
</script>
</body>
</html>
Note that this javascript code will be executed when it is
encountered, and it outputs HTML that is rendered by the
web browser.
18
Webpage Output with JavaScript
A script can output calculated and dynamic information:
<html>
<body>
<h1>Clock Example:</h1>
<script language=javascript>
var date = new Date()
var hours = date.getHours()
var min = date.getMinutes()
document.write(“Time: <b>” +hours+”:”+min+”</b>”)
</script>
</body>
</html>
19
Dialog Output with JavaScript
A script can use the alert( “a string”) function to pop up an
“Alert” Dialog box.
<html>
<body>
<h1>Example:</h1>
<script language=javascript>
alert(“Here is an annoying pop-up!”)
</script>
</body>
</html>
This javascript code will be executed when it is
encountered, and causes an alert-box to appear.
20
Input: Running a function when the user clicks
Define a function:
<script language=javascript>
function myFunc() {
alert(“You clicked it!”)
}
</script>
You can use an onClick=”FUNCTIONNAME();” parameter
on a button to call the function:
<input type=button value=”Do It!” onClick=”myFunc();” >
Clicking on the button will cause the alert box to appear.
21
Input: Running a function when the user clicks
<html>
<body>
<script language=javascript>
function myFunc() {
alert("You clicked it!")
}
</script>
<input type=button value="Do It!" onClick="myFunc();" >
</body>
</html>
22
Output: Modifying an already loaded webpage
document.write() can be used to add text to a webpage as
it is being loaded.
To modify text in a webpage AFTER it is loaded, you can
use a named area (DIV) and replace the HTML content
with javascript.
<div id="txt">Plain Text</div>
is HTML that creates a DIV named “txt”.
You can then change the HTML content of this DIV
(currently “Plain Text”) with javascript as follows:
var myDIV = document.getElementById('txt')
myDIV.innerHTML=”<b>New Text!</b>”
23
Putting it all together: An example program
<html>
<body>
<script type="text/javascript">
var num = 0
function startTime() {
num = num + 1
var myDiv = document.getElementById('txt')
myDiv.innerHTML="<b>Clicked " +num+ " Times</b>";
}
</script>
<div id="txt">Plain Text</div>
<input type=button value="click it!" onClick="startTime()">
</body>
</html>
24
Download