Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Introduction to JavaScript

This tutorial is meant for the students of CIS*1000: Introduction to Computer Applications offered at the University of Guelph
by

Rion Meehan

on 12 June 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Introduction to JavaScript

Introduction to JavaScript
and general programming concepts
Foundation
Variables
Conditional Structures
Functions
Objects
Forms
About this Tutorial
Introduction to Conditional Structures
Conditional structures allow us to control the flow of our programs while they run, without having to know the state of key information that may influence its execution.

For instance, when we ask users questions (such as "would you like to proceed?") we don't know what option they may pick. Conditional structures allow us to outline both paths and determine which to followed during execution. They also allow us to do things over and over again without having to write the code over and over again.

JavaScript has 5 conditional structures: the
if
-
else
statement,
switch
statement,
while
loop,
do-while
loop, and
for
loop. There are also two useful keywords:
break
and
continue
.
The If-Else Statement
The
if-else
statement is the simplest of the conditional structures. It is formed using the
if
keyword followed by a condition written in round brackets
()
. The condition must evaluate to true or false. Conditions can be formed using truth equations, many of which can be seen in the example on this slide.

After the round brackets
()
, we add a pair of squiggly brackets
{}
.
All of the code written between these brackets
{}
is dependent on the condition being true. If the condition is false, then the code inside of the brackets
{}
will not execute. Instead, it will skip past the brackets and continue normally.

The If-Else Statement
We can extend the
if-else
structure by using
else if
or
else
. Using
else if
will require another condition and another set of squiggly brackets
{}
. Using
else
only requires the brackets
{}
. In order to use
else if
there must already be an
if
. After the
if
you can have as many
else if
as you want. The
else
must always be at the end of this structure, after the
if
and all
else if
. There can only be one
else
.

If the
if
condition is false, then the program will test the first
else if
, if that is false, then it will test the next one. If any of them are true, then that section will execute and the rest will be skipped.
If all of them are false, they will all be skipped, unless there an
else
, which will only execute if everything else is false.

The Switch Statement
The switch statement is useful when you would otherwise have a very long if-else statement. Note that it will only work when the variable you're testing is a number. It also offers more options as to how you would like each path to be handled. A switch statement can be formed using the keyword
switch
followed by the variable you want to test in round brackets
()
. Then add a pair of squiggly brackets
{}
and write the content of the switch statement inside of these.

Each path of a switch statement is called a
case
. To add a case, use the keyword
case
followed by a value and a colon
:
. Everything after this colon, to the closing bracket
}
will be considered part of this case, including other cases. This means if your first case is triggered then every other case will be executed as well, unless you use the keyword
break
.
The Break and Default Keywords
The keyword
break
can be used to stop the execution of a loop or structure at any time. It is very common in switch statements, as it allows cases to be separated from one another. In a loop, using the keyword
break
will terminate the loop and continue execution after it. In an if-else or switch, the keyword
break
will skip to the end of the structure and continue execution.

The keyword
default
is only used in switch statements, it the equivalent of the if-else statement's
else
. It is written in place of the
case
keyword with no value afterward, and it is normally written after all other cases.
The While Loop
The while loop is the simplest loop in JavaScript. A while loop can be formed by using the
while
keyword, followed by a condition in round brackets
()
, and finally a pair of squiggly brackets
{}
. Anything written in the squiggly brackets
{}
will be executed if the condition is true and repeated until the condition is false. So, make sure that whatever your condition is, that its outcome changes (or at least has the potential to change) each time the loop executes, otherwise the loop will run forever.

Each time the program reaches the ending squiggly bracket
}
it will check the condition again. If it is still true, it will jump back to the top of the loop and repeat the code. Otherwise it will continue execution normally after the loop.
The Do-While Loop
If you want your while loop to run once regardless of whether or not the condition is true, then you can use a do-while loop. A do-while loop is the same as a while loop, except the condition is not tested the first time it is reached. To form a do-while loop, use the keyword
do
followed by a pair of squiggly bracket
{}
. Directly after the closing squiggly bracket (on the same line) write the keyword
while
followed by your condition in round brackets
()
.

There is also the keyword
continue
, which can be used to skip to the end of a structure. In a loop, this means it will skip the rest of the loop and test the condition again.
The For Loop
If you need a loop that will run a set number of times, you can use a for loop. It is almost the same thing as a while loop. To form a for loop, use the keyword
for
followed by a pair of round brackets
()
. Inside these brackets we need to write three statements. The first is a declaration for a counter variable (a variable that is only used to count the number of times the loop has run). Follow this statement by a semicolon
;
. Second is a condition, just like a while loop. Add another semicolon
;
. Finally, we need an increment or decrement. This is how much the counter will change each time the loop reaches its end.

Counters normally start at 0. This means that your for loop should run while the counter is less than the number of iterations you want.
Introduction to Functions
A function is an executable block of code that can be run by calling it. They can be user-defined or part of the language itself.

Functions are normally considered to be atomic units. They have a single task and they hide how they accomplish this task from their callers. If you write a function and you cannot describe its purpose without using the word "
and"
, then it is likely that your function should actually be several smaller functions.

In JavaScript, a function has two important properties: its parameters and its return value.
Declaring a Function
Functions can be declared using the
function
keyword. This must be followed directly by what you want to name the function. Function names should follow the same conventions are variable names.

After the function's name goes its parameters. The parameter list is a list of variable names inside of round brackets
()
with commas
,
between each variable name. This list outlines exactly what information your function needs in order to execute.

After the parameters goes a pair of squiggly brackets
{}
, inside of which you will write the body of your function (the code to be executed when the
function is called). Inside of the body you can use any of the parameters as if they are defined variables already containing information.
Return Statements
Another important aspect of functions is the ability to return information to the caller. In order to return information we use the keyword
return
followed by the information we want to return. Since JavaScript does not have declared return types, the information returned can be any data type you want.









It is important to note that a function will end as soon as it hits a return statement, any code written directly after a return statement will never be executed. We can also write a return statement with no information to be returned, if we just want to end the function.
Introduction to Objects
Calling Functions
Properties
Methods
Everything is JavaScript is an object. From all of the variables that we have declared through out this tutorial to some of the keywords we have seen like
document
. These objects are what give JavaScript its incredibly flexible power.

You can consider an object in JavaScript to be like the data representation of a real object. Every object has properties and methods which are used to define its state and interact with it. For instance, a dog can be defined as a object in JavaScript.

You can create an object, or any other data type, with no information in it, using the
new
keyword.
This tutorial will cover basic concepts in JavaScript and programming in general. It should provide you with enough JavaScript knowledge to complete an assignment for:
CIS*1000: Introduction to Computer Applications

This tutorial does not cover every concept of JavaScript, nor is it meant to. It was compiled and organized using personal knowledge and the information provided at
www.w3schools.com/js

It is recommended that you approach this tutorial with a working knowledge of HTML and a basic understanding of CSS. If you need them, great tutorials for HTML and CSS can be found at www.w3schools.com
The properties of an object define its current state. They are the things that the object is or the object has. For instance, a dog object could have a property like "breed" or "age".
Methods are functions that belong to an object in general, but should effect and refer to only a single instance. An instance is a single variable of an object type. Methods are things that the object does or are facilitated by the object.
Calling Functions From HTML
Functions are completely useless if you don't call them. To call a function, simply write its name followed by a pair of round brackets
()
. Inside of these brackets you must provide a comma separate list of values that correspond to the functions parameters. These are known as arguments.

There must be the same number of arguments as the function has parameters, else the code will not execute. If the function returns something, you should also make sure to store it (if you care about its return value.
Local Variables
Recursion
What is JavaScript?
JavaScript is a scripting language that can be inserted into HTML documents. A scripting language is a lightweight programming language.

Unlike HTML which provides structure and CSS which provides style, JavaScript provides functionality.

JavaScript is supported by all modern browsers and is easier to learn than most other programming languages.

JavaScript is not the same thing as Java.
How to write JavaScript in HTML documents
JavaScript can be inserted into HTML documents using the
<script>
tag. The
<script>
tag can be placed anywhere in the
<head>
or
<body>
tags.






JavaScript code can be written directly inside this tag or it can be included from a separated file using the
src
element. The code will be executed as soon as it is reached in the HTML document.
Statements
A statement in JavaScript is a command that will be executed by the browser. Statements can be ended with semicolons. This allows multiple statements to




be written on the same line. However, in JavaScript, semicolons are optional. If you choose not to use them, then each statement must be written on a separate line. Statements are executed in the order they are written. If a statement is syntactically invalid, it will stop the execution of the program.
Comments
Comments allow us to document and explain our programs. Unlike statements, comments are not commands; comments will be completely ignored by the browser. JavaScript has two types of comments. The
//
type will affect everything after it on the same line. The
/*
type will affect everything between the
/* */
.
Notes about Comments
Comments have a different use other than just documenting. We can use comments to stop sections of code from executing without deleting it. This is commonly called "commenting out". It is very useful when you are trying to figure out why a script isn't working.
Related to this, if you don't close a /* comment properly, it will treat the entire script after it as a comment and none of it will execute.
Output
It might be difficult to tell if your JavaScript programs are working if they don't output anything. In JavaScript, we can have a large visual impact on our HTML documents in a variety of ways. The simplest way is to write directly to the document using
document.write()
. Anything written in quotes
""
between the round brackets
()
will appear on the webpage based on the position of the script in HTML document. Note that if you call
document.write()
after the page has loaded, it will overwrite the entire page.
Walkthrough Example: Forms
To finish up our Introduction to JavaScript, we are going to write a script. In particular, we are going to write a script that process a form. If you are familiar with HTML then you should already know how to make forms, but the next two slides will explain anyway.

Forms can be used for a variety of purposes, our form will be a simple sign-up form. The most critical aspects of a form are a clear indication of the desired information and the format it should be in. So, our script will need to validate and then inform the user of the success or failure of our validation.
Selective Output
We can also choose exactly where our output is going. Using the ID of HTML tags in our document, we can select one and then write inside of it. The function we can use for this is
document.getElementById()
. Inside of the round brackets
()
we provide the id of the tag we want to write to, in quotes
""
. We can then set the property
innerHTML
to whatever information we want to display.
Keywords
In every programming language, there is a list of reserved words. These words are used to speak in that language. When we get to the portion of this tutorial that talks about naming conventions for variables and functions, keep in mind that you cannot name a variable or function using a keyword.

Over the course of this tutorial, I will be highlighting symbols, keywords, and built-in function names in
red
.
Case Sensitivity
An important concept in JavaScript and programming in general is case sensitivity. Most programming languages will see a word no capital letters as a completely different word then a word with any capitals letters.







So keep in mind, if you want to output something but you type Document instead of
document
, then the browser will have no idea what you want and stop the script.
Formatting and Whitespace
It is considered good practice to format your code nicely. This means indenting it properly, just like you would HTML code. It also means following naming standards, including comments, and having an appropriate amount of whitespace.

Whitespace is empty space, such as blank lines or spaces. JavaScript completely ignores whitespace, so you can write your
code as compact or apart as you like. The best practice is to keep your code nicely spaced so that it is easily to read, but compact structures are acceptable as well. Wide spacing isn't as acceptable.
Introduction to Variables
In programming, variables are containers that we use to store information. Each variable has a unique identifier that we use to refer to it when we need it.

A variable's name must be unique, no two variables can have the same name. In JavaScript, if you try and use the same name over again, it will overwrite the previous variable that shared that name.

Variables can store lots of different types of information and can be used to interact with our user, perform complex equations, and represent objects.

Remember, JavaScript is case-sensitive. This means that dog, Dog, DoG, and DOG are all different variables.
How to Declare a Variable
Normally, before you can use a variable you must declare it. However, this isn't completely true in JavaScript.

Declaring a variable tells the computer that we a chunk of memory to store our information in and we will be refering to this chunk using the variable name.







In JavaScript, we can declare a variable by using var followed by an identifier. We can also declare a variable by simply assigning it
a value. This, however, will make it a global variable, which we will talk about later.
Variable Name Standards
Consistency is an important part of programming, it keeps tried programmers from making too many mistakes. In general, there is an accepted standard for how to name your variables.

Try to keep the names of your variables meaningful and short. One letter names are usually reserved for counters or meaningless variables. Multiple word variables should be written in camelCase.
Lowercase words are common use and uppercase words are used to indicate constants.
Operators
An operator is a symbol that can be used to effect the value of a variable. Using operators we can form simple equations likes we would in math.
Data Types and Dynamic Types
JavaScript has 7 data types, each of which represent a different type of information. In other programming languages, the data type of a variable is very important, because you cannot switch between them. JavaScript, however, has dynamic types, which means that you can data types interchangeably. You can set a variable that held a string to a number with no issues.
Numbers
To JavaScript, an integer and a decimal are both just numbers. There is a real difference, in that you can only use certain operators or functions with one or the other. However, they share the same data type.

Be wary of floating point numbers (decimals) in programming. Just because it seems to add up, doesn't mean the computer will be able to compute it.
Booleans
Booleans are the simplest data type. However, a lot of novice programmers have difficulty understanding both the purpose and use of booleans.

A boolean can only have two possible values: true and false. They are very useful in conditional structures and functions, as they can be used to quickly assert a truth value.
Strings
A string is anything contained within quotes
""
. More formally, a string is a series of characters. It can be made up of any character you can type, as well as a couple you can't.

The characters you can't type are known as invisible characters which you don't need to worry about) and special characters which is the next slide.
Special Characters
There are a ton of special characters which can be added to strings from different effects. First of all, the backslash
\
in known as the escape character, as it changes the normal meaning of other characters. If you ever come upon a character that you cannot print because JavaScript is using it for some special purpose, you can escape it by preceding it with a backslash
\
, which will remove its meaning. Be wary of stray backslashes in your strings, almost all escaped characters mean something different than their original counterparts.
Arrays
Arrays can be very complicated and this tutorial's explanation is by no means a complete view of them. Just like how a string is a series of characters, an array is a series of variables. They can be used to store massive amounts of information in a very simple way.
More about Arrays
Something we will see a little later is that everything in JavaScript is an object. To arrays, this means that we have different data types mixed in. It doesn't just have to be strings or numbers.

Also, note that when you use an index like
[0]
you are referring to a single variable (whatever is stored in
[0]
), but you can still refer to the array as a whole by just using its name. This way you can set variables equal to entire arrays or just one portion of them.

There is a lot more that can be said about arrays (like multi-dimensional arrays), but this is all of the knowledge you'll need for this tutorial. If you wish to learn more about arrays, visit http://www.w3schools.com/js/js_obj_array.asp
You can call a JavaScript function from HTML by setting attributes on HTML tags. Two particularly useful and common ones are
onclick()
and
onload()
. The provided argument is the function you want to call. There names indicate when they will call your function (when the element is clicked and when the element is loaded).





For a full list of these kinds of attributes as well as the tags they can be applied to, visit:
http://www.w3schools.com/jsref/dom_obj_event.asp
A local variable is a variable declared inside of a function or any other block of code. Local variables are temporary and will cease to exist as soon as their block ends. The parameters to your functions are also local variables.

The opposite is a global variable which will exist as long as the script is running. Like was said in the variable section, declaring a variable by assigning it a value will force it to be a global variable.
A function can be defined as recursive if it calls itself. A recursive function with no handling conditional structure will most likely cause an infinite loop.

Recursion can be used to accomplish a lot of the same tasks done by loops, in fact it may even make more sense to program it this way. The downfall of recursion is that it is a lot more expensive and is therefore avoided when lots of iterations are required.
Defining Objects
You can declare an object using the new keyword, but you can define an object using an object constructor.
Our Form - Part 1
Our form will have four parts: a text box for a name, a text box for an email address, a check box, and a validate button. First of all, we need to make a form and give it a name. The form needs to have a name so that we can refer to its elements in our JavaScript program. We are also going to create an empty function for later.
Our Form - Part 2
Next we need to add our elements to our form. Each can be accomplished using the correct tags. We also need to make sure that all of the elements are labeled so that the user knows what we are looking for, and that all of the elements have names so we know how to find them.
Validation - Part 1
Now we get to the JavaScript. When the validate button is pressed, it is going to call our validate function. The first thing we are going to do is fetch the values of all of our elements. This works a little differently for each element.
Validation - Part 2
Now that we have the information, we need to actually validate it. To do this we are going to use a conditional structure and two smaller functions. The conditional structure will expect each function to return true or false based on the validity of the information provided.




Once we know whether or not the information is valid, we need to return true or false. Returning true says that the information was accepted and the user should be allowed to go to the next page. Returning false says that the information was not accepted and they should be kept on the form page.

Also, note that the
&&
in the if condition stands for AND. The entire condition can only be true if both parts are true.
Validation - Part 3
Validating the name should be easy. First we need to ensure that there is any information written at all. Next, we can use a regular expression to try and match a valid name. A regular expression searches for particular patterns in strings, if a string satisfies a regular expression then it contains the pattern it was looking for.
Validation - Part 4
The method for email addresses is nearly identical, except the regular expression is much more complex. I will not bother to provide a true explanation of regular expressions as it is a completely different topic on which entire courses can be taught. Just be aware of their existence, and know that if the problem you are trying to solve is simple, someone has probably solved it.
Completion
That's it, we now have all the necessary pieces to make our form fully functional. Here it is in all its glory:
The End
Thank you for reading my JavaScript tutorial. Keep in mind that this was not a complete explanation of the JavaScript language, nor was it the best one. If you simply want to complete your assignments this semester, then this should be more than enough for you. However, if you are truly interested in computer programming, I urge you to continue learning. Like I said at the beginning, w3schools is a great website for learning web-based programming languages and its tutorial even has complete lists of object methods and properties.

document.write("I hope you have a great semester!");
Full transcript