Introduction to JavaScript Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript
Introduction to JavaScript
Boolean operators Conditional execution
Dennis Olsson
Loops Objects Arrays Operators Summary Introducing events Summary
Lecture #7
Introduction to JavaScript
1 Introduction
Dennis Olsson
2 Basic Syntax
Today Introduction
3 XHTML and JavaScript
Basic Syntax XHTML and JavaScript
4 Boolean operators
Boolean operators
5 Conditional execution
Conditional execution
6 Loops
Loops
7 Objects
Objects Arrays Operators Summary Introducing events Summary
8 Arrays 9 Operators - Summary 10 Introducing events 11 Summary
Introduction to JavaScript
First of all
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops
• JavaScript is NOT Java. • Borrows some syntax from Java, which is similar to
C/C++, PHP, etc. • Based on the implementation of ECMAScript in Netscape,
working name: Mocha.
Objects Arrays Operators Summary Introducing events Summary
This course will approach some things in JavaScript. the goal is to get you to try it out, and start experimenting. A lot of the programming is done using some reference literature (physical or electronical).
Introduction to JavaScript
Structure
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
A comment is either started by // and ended at the end of the line, or started with /* and ended with */. A statement is a single line of code. All statements: • ends with semicolon and • can be replaced by a block
A block is a group of zero or more statements and is started with { and ended with }. Block are formed to support execution of several statements when there as default is only support for one statement. It’s recommended to always use a block for a loop or an if-statement (introduced below).
Introduction to JavaScript
Functions
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
A function is a section of code isolated from the rest, but given a name. Anyone can call a function. It may or may not take arguments, and may or may not return a value. Code from example-simple function.html function sayWelcome() { // A pop-up dialog with the text is shown alert("Welcome, user!"); } // Call the function sayWelcome();
Introduction to JavaScript Dennis Olsson
Example with arguments
Today Introduction Basic Syntax XHTML and JavaScript
Code from example-simple argumentfunction.html
Boolean operators Conditional execution Loops Objects
function sayWelcome(welcomeword, towho) { // A pop-up dialog with the text is shown alert(welcomeword + ", " + towho + "!"); }
Arrays Operators Summary Introducing events Summary
// Call the function sayWelcome("Welcome", "user");
Introduction to JavaScript Dennis Olsson
Example with return value
Today Introduction Basic Syntax
Code from example-simple returnfunction.html
XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
function welcomeText(a, b) { return a + ", " + b + "!"; } function sayWelcome(welcomeword, towho) { // A pop-up dialog with the text is shown alert(welcomeText(welcomeword, towho)); } // Call the function sayWelcome("Welcome", "user");
Introduction to JavaScript
Variables
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
A variable is a place to store information of some kind as: • Strings – Contain zero or more characters • Floating Point numbers – A number with zero or more
decimals
Loops
• Integer number – A number without decimals
Objects
• Boolean – Either true or false
Arrays Operators Summary Introducing events Summary
• Object – An object (a lot more on this later)
JavaScript is weakly typed language, meaning that a variable can contain any of the above values independently of previous declarations.
Introduction to JavaScript Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators
Variables Declaring a variable with var will make it usable within the function. If var is omitted, the variable will be usable throughout the whole document. Using var outside a function will will have no effect on the scope. Code from example-variable scope.html
Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
function myFunction() { var a = "a"; b = "b"; alert("In function: " + a + " and " + b); } // call the function myFunction(); alert(b); alert(a); // Crash since a is undeclared
Introduction to JavaScript
Adding to HTML-files
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators
XHTML has a special tag for scripts: <script> Always add the attribute type="text/javascript". Code from example-simple function.html
Conditional execution Loops Objects Arrays
<script type="text/javascript"> /*
Operators Summary Introducing events Summary
/* ]]> */
Introduction to JavaScript Dennis Olsson
Use XML-comments?
Today Introduction Basic Syntax XHTML and JavaScript
Some example code on the web, as well as some old schools recommend programmer to wrap the javascript inside XML-comments, as:
Boolean operators Conditional execution Loops Objects Arrays Operators Summary
<script type="text/javascript">
Introducing events Summary
This is however not recommended, since comments in XML implies the browser not to parse the text. It still works in most browsers though!
Introduction to JavaScript
Including from XHTML-files
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
To embed the JavaScript is however not recommended if it’s more than a few functions, and will not be allowed in the assignments. Also, it’s a way to break the clean separation of content, presentational information and function wanted. Therefore, use:
Loops Objects
Code from example-simple include.html
Arrays Operators Summary
<script type="text/javascript" src="example-simple_include.js">
Introducing events Summary
Firefox can’t parse <script ... /> correctly.
Introduction to JavaScript
Including external .js-files
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
An included .js-file containing JavaScripts need no extra tags. The complete file named example-simple include.js is shown below. Code from example-simple include.js function sayWelcome() { // A pop-up dialog with the text is shown alert("Welcome, user!"); } // Call the function sayWelcome();
Introduction to JavaScript Dennis Olsson
About the examples
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
Many of the examples handed out will not use external JavaScripts. There are manly two reasons:
Loops
• Twice the amount of files to look at
Objects
• Since the source code of most examples fit in one screen
Arrays Operators Summary Introducing events Summary
it’s easier to get an overview of it.
Introduction to JavaScript Dennis Olsson
Comparing values
Today Introduction Basic Syntax XHTML and JavaScript
There are basically three comparisons that can be done between values:
Boolean operators
• a < b – true iff a is less than b
Conditional execution
• a == b – true iff a is equal to b
Loops
• a > b – true iff a is greater than b
Objects Arrays Operators Summary
There are two combinations and one negation of these: • a <= b – true iff a is less than or equal to b
Introducing events
• a != b – true iff a is not equal to b
Summary
• a >= b – true iff a is greater than or equal to b
Introduction to JavaScript
Joined conditions
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events
Sometimes there’s a need to compare several values at once, and make sure they have a certain pattern concerning their boolean values. To do this, it’s possible to use a set of binary1 operators. • a && b – true iff both a and b are true. • a || b – true iff either one of a and b is true.
Finally, there’s a unary operator for boolean expressions, namely: • ! – negate the following condition
Summary
1
As in: takes two arguments
Introduction to JavaScript
Example conditions
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
true | | false → true true && false → false true && !false → true
Loops Objects Arrays
false | | ( true && ( false | | false ) ) → false
Operators Summary
false | | ( true && ( false | | !false ) ) → true
Introducing events Summary
Introduction to JavaScript
if
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
We need a way to test if a condition is true. Some pieces of code should only be executed if one or more criterias are fulfilled. For this we have if. Code from example-tiny examples.js
Loops Objects Arrays Operators Summary Introducing events Summary
function example_if() { if ( true ) alert("true it is"); if ( false ) alert("false it is"); }
Introduction to JavaScript
if – else
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
There is also a need to fall back on a block of code if a condition was false. The previous example, for instance, demanded two comparisons. It can be released with: Code from example-tiny examples.js function example_if_else() { if ( true ) alert("true it is"); else alert("false it is"); }
Introduction to JavaScript Dennis Olsson
if – else if
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
If we need to test several conditions independently, and want to stop at the first, we can nestle the if-statements. Code from example-tiny examples.js function example_if_else_if() { if ( false ) alert("false it is"); else if ( true ) alert("true it is"); else alert("it was neither true or false"); }
Introduction to JavaScript Dennis Olsson Today Introduction Basic Syntax
switch If there’s a lot of values to compare with, the if – else if-way will become hard to edit during development. The aid is named switch.
XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
Code from example-tiny examples.js
function example_if_else_if() { var value = 3; switch (value) { case 2: alert("Two, that’s the value of the variable."); break; case 1: case 3: alert("Almost two, that’s the value of the variable."); break; default: alert("Variable out of scope"); } }
Introduction to JavaScript
while
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
There is often need for a code block to be executed several times in a row. Often the number of executions can be determined by a condition. The most basic loop is while, which executes code zero or more times. Code from example-tiny examples.js
Loops Objects Arrays Operators Summary Introducing events Summary
function example_while() { var value = 0; while(value < 3) { alert("Value is: " + value); value = value + 1; } }
Introduction to JavaScript
for
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators
The above scheme with definition - comparison - increasing is often used, and there is a way to write this a whole lot shorter using for. Code from example-tiny examples.js
Conditional execution Loops Objects Arrays
function example_for() { for ( var value = 0 ; value < 3 alert("Value is: " + value); }
;
value = value + 1
Operators Summary Introducing events Summary
Any of these fields can be omitted. For example for(; condition ;) is exactly the same as while( condition ).
)
Introduction to JavaScript
do – while
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
There is another loop that is a modified version of while, namely the do – while. See the example below.
do { // execute this first once // and then over - and - over, until the condition b } while ( condition );
Introduction to JavaScript Dennis Olsson
break and continue
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
We may choose to break out of a loop, or instruct it to start over again without finishing the current iteration. Using break will cause the execution to continue after the loop, while continue will cause the execution to continue at the very end of the block. The very end means that, in a for-loop, the value will be incremented before the execution continues at the top. The keyword continue is in short “continue with the next lap, if any”.
Introduction to JavaScript Dennis Olsson
Objects - introduction/summary
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
Learning an object oriented language is out of the scope of this course. However, a basic understanding of the meaning is needed. In 19 words: An object is a chunk of organized data, and a set of methods (≈ functions) to work on that data. A deeper understanding in objects will be gained during the next lecture.
Introduction to JavaScript Dennis Olsson
Array
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops
An array is a chunk of data, and is handled like an object. It’s therefore created using the keyword new. The values can then be accessed using an index starting at 0. An interesting attribute (≈sub-value) of an array is length, which will return the highest index in the array + 1. Code from example-tiny examples.js
Objects Arrays Operators Summary Introducing events Summary
function example_array() { var arr = new Array("This", "is", "an", "array"); arr[5] = "a late string"; for ( var i = 0 ; i < arr.length ; i = i + 1 alert("Value is: " + arr[i]); }
)
Introduction to JavaScript
for – in
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
There is a much easier way to access all elements without knowing the number of elements, using for - in. This will also skip holes in the array. Code from example-tiny examples.js
Loops Objects Arrays Operators Summary Introducing events Summary
function example_for_in() { var arr = new Array("This", "is", "an", "array"); arr[5] = "a late string"; for ( var i in arr ) alert("Value is: " + arr[i]); }
Introduction to JavaScript
Arithmetic Operators
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects
In all examples, a and b are variables or constants. a a a a a
+ – * / %
a
++ ++ –– ––
b b b b b
Arrays Operators Summary Introducing events Summary
a
b b
→ → → → →
Add a and b Subtract b from a Multiply a and b Divide a with b Get the remainder when a is divided by b
→ → → →
Increase a after it’s read Increase b after it’s read Decrease a after it’s read Decrease b after it’s read
Introduction to JavaScript
Assignment Operators
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
In all examples, a is a variable, and b is a variable or constant. a a a a a a
= += –= *= /= %=
b b b b b b
→ → → → → →
a a a a a a
= = = = = =
b a a a a a
+b –b *b /b %b
Introduction to JavaScript
Comparison Operators
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript
In all examples, a and b are variables or constants.
Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
a a a a a a a
== === != > < >= <=
b b b b b b b
→ → → → → → →
True when a has the same value as b a has the same value and type as b a has another value than b a is greater than b a is less than b a is greater than or equal to b a is less than or equal to b
Introduction to JavaScript
Logical Operators
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators
In all examples, a and b are variables or constants.
Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
a a
&& | | !
b b b
→ → →
True when Both a and a are true At least one of a and a is true The negation of b
Introduction to JavaScript Dennis Olsson
Events
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
Events is happening when the user takes an action like clicking on a link, when the browser changes state (as when the page has loaded), or when the source code itself triggers an event (for example by using a timer). Events will be brought up later during the course, but to understand the examples, and be able to do the assignment, they will be introduced here.
Introduction to JavaScript Dennis Olsson
OnClick–Events
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
The events handlers can be set as attributes to a tag in XHTML. A simple example would be the following Code from example-tiny examples.html
Loops Objects
The function example_if
Arrays Operators Summary Introducing events Summary
This will run the JavaScript function example if() when the link is clicked.
Introduction to JavaScript
Hierarchy
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
When a link is clicked, the link is owned by, among others, the body. The event will propagate up through this hierarchy. To show this propagation, study the example below. Code from example-onclickevent.html
Loops Objects Arrays Operators Summary Introducing events Summary
the body’);"> the paragraph’);"> caught by the link’);"> event
Introduction to JavaScript Dennis Olsson
OnLoad–Events
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
An OnLoad–event is triggered when the loading is complete. This means that the OnLoad for a document is triggered when all elements in it are available. This can also be set as a attribute to a XHTML-tag, like:
Loops Objects
Code from example-onloadevent.html
Arrays Operators Summary Introducing events Summary
Introduction to JavaScript Dennis Olsson
OnLoad continued
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution
To set the onload as an attribute is however a way to mix function and content, something we want to avoid. Instead, the following should be used. Code from example-onloadevent2.html
Loops Objects Arrays Operators Summary
function loadMeWhenPageLoads() { alert("Welcome, user!"); } window.onload = loadMeWhenPageLoads;
Introducing events Summary
Do not include the parenthesis after the function name.
Introduction to JavaScript Dennis Olsson
Events vs. Separation
Today Introduction Basic Syntax XHTML and JavaScript Boolean operators Conditional execution Loops Objects Arrays Operators Summary Introducing events Summary
To separate the function from the content, we need to be able to set the attributes when the page is loaded, not written by the web designer. We will look at this during the next lecture.
Introduction to JavaScript
Summary
Dennis Olsson Today Introduction Basic Syntax XHTML and JavaScript
• Basic syntax – blocks, functions, parameters, variables
Boolean operators
• XHTML and JS – the script-tag, external files, CDATA
Conditional execution
• Boolean Operators – AND, OR, NOT, etc.
Loops
• Conditional execution – if – else, switch – case – default
Objects
• Loops – while, for, do – while, break / continue
Arrays
• Arrays – arrays, for – in
Operators Summary
• Operators – Arithmetic, Assignment, Comparison, Logical
Introducing events
• Events – onclick, onload
Summary