Send the link below via email or IMCopy
Present to your audienceStart 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
and general programming concepts
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.
loop. There are also two useful keywords:
The If-Else Statement
statement is the simplest of the conditional structures. It is formed using the
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
structure by using
will require another condition and another set of squiggly brackets
only requires the brackets
. In order to use
there must already be an
. After the
you can have as many
as you want. The
must always be at the end of this structure, after the
. There can only be one
condition is false, then the program will test the first
, 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
, 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
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
. To add a case, use the keyword
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
The Break and Default Keywords
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
will terminate the loop and continue execution after it. In an if-else or switch, the keyword
will skip to the end of the structure and continue execution.
is only used in switch statements, it the equivalent of the if-else statement's
. It is written in place of the
keyword with no value afterward, and it is normally written after all other cases.
The While Loop
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
followed by a pair of squiggly bracket
. Directly after the closing squiggly bracket (on the same line) write the keyword
followed by your condition in round brackets
There is also the keyword
, 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
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 "
, then it is likely that your function should actually be several smaller functions.
Declaring a Function
Functions can be declared using the
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
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.
Another important aspect of functions is the ability to return information to the caller. In order to return information we use the keyword
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
You can create an object, or any other data type, with no information in it, using the
CIS*1000: Introduction to Computer Applications
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.
tag can be placed anywhere in the
element. The code will be executed as soon as it is reached in the HTML document.
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.
. 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
after the page has loaded, it will overwrite the entire page.
Walkthrough Example: Forms
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.
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
. 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
to whatever information we want to display.
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
So keep in mind, if you want to output something but you type Document instead of
, 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.
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.
Variables can store lots of different types of information and can be used to interact with our user, perform complex equations, and represent objects.
How to Declare a Variable
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.
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.
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
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 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.
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.
There are a ton of special characters which can be added to strings from different effects. First of all, the 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 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
Also, note that when you use an index like
you are referring to a single variable (whatever is stored in
), 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
. 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:
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.
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 - 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
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.
That's it, we now have all the necessary pieces to make our form fully functional. Here it is in all its glory:
document.write("I hope you have a great semester!");