Introduction to JavaScript
https://github.com/snostorm/LLC-JavaScript
( Interactive code slides thanks to CoderDeck ! )
https://github.com/snostorm/LLC-JavaScript
( Interactive code slides thanks to CoderDeck ! )
Aug. 17, 2013
3 tools you need to get started
Choose a modern web browser that has good, built-in development tools to help make building web pages easier.
(If you are unable to install Chrome:
install
Firefox
.)
JSBin lets you write HTML, CSS and JavaScript directly in your browser.
JSBin (and other similar tools) are a great way to quickly try out and share your HTML, CSS and JavaScript but in reality we want people to visit our actual web pages.
There are many, many free and paid options but let's keep it simple for our mentors today and use the same editor to edit our code. Other options like TextWrangler, Notepad++ and Text Edit are available, too.
Are you using Dropbox? Sharing your public files is easy:
There are many services now that turn your public Dropbox into a full website
instead of having to share the ugly public link), read more here.
Do you already have your own hosted website? FTP software will let you copy the files you work on today to somewhere where the rest of the world can see them!
Again, there are many, many free and paid options.
FileZilla
is good when you're more advanced.
Programming and JavaScript
It's a
programming language
that was designed to run in your web browser to
manipulate content on web pages.
It's a
programming language
that was designed to run in your web browser to
manipulate content on web pages.
A program is a set of instructions meant for a computer to execute.
Computers are fast but blind.

Think about a tourist that stops you to ask for directions:
The clearer the instructions, the more likely they will get to their destination.

Suppose I want a computer to say hello using my name.
Break down the steps as much as possible:
Programming is like having a conversation with your computer. You write to it using a programming language and give it instructions this way.
Computers only understand instructions when you speak to them in a language they can understand. Much like Japanese, English or any other natural language, programming is about sticking to grammar rules called syntax.
Computers have come a long way since their binary days (0 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0 0 1 1 1 1) so meet them half-way.
Different programming languages have different syntax.
Here are two ways a computer could say hi to me:
Java
Scanner userInput = new Scanner(System.in);
String name;
System.out.print("What's your name? ");
name = userInput.next();
System.out.println("Hello, " + name);
JavaScript ( Try it out now! )
var name;
name = window.prompt("What's your name?",'');
document.write("Hello, " + name);
They might vaguely look the same (as a lot of programming languages do) but they are not related at all.
(Java was really popular at the time so Netscape just hijacked the name.)
It's a
programming language
that was designed to run in your web browser to
manipulate content on web pages.
C++, Java, and .NET are also programming languages but they can be run directly by the operating system (e.g. Windows, Mac, Linux).
JavaScript is typically meant to be run in a web browser (e.g. Safari, Firefox, Chrome, Internet Explorer).

Java, .NET, PHP or Ruby can be considered server-side or "back-end" web technology because the code is typically compiled and executed by the operating system of a computer serving up web pages.
JavaScript is often referred to as a client-side or "front-end" web technology because it is interpreted by the web browser. It can be used for server-side programs too, but today we'll be focusing on the browser.
At any time, someone can right-click and "view source" on a web page to see all the JavaScript that went into it.
(I suggest that you do this yourself every time you see something you like!)
Whereas for server-side code, it's sometimes a mystery what technology is running on a server.
It's a
programming language
that was designed to run in your web browser to
manipulate content on web pages.
JavaScript was meant to manipulate webpages written in HTML and works in tandem with CSS.
| HTML (Hypertext Markup Language) is the markup language. |
CSS (Cascading Style Sheets) is the style sheet language. |
JavaScript is the programming language. |
![]() |
![]() |
![]() |
| It should define the content. | It should define the presentation | It should define behaviour. |
Usually JavaScript will run the same way in various browsers.
But, browsers are software programs written by many different people/companies (people programming things just like you!), so sometimes they say "hi" with different accents.
Imagine a British accent versus a Texas accent.
This is especially noticeable with newer "HTML5" features.

JavaScript is essential for "AJAX", "Web 2.0", and "HTML5" websites. All these terms refer to various methods of making interactive web pages using Javascript.
Try this experiment: Turn off JavaScript in your web browser. Go to the JavaScript settings for Chrome ( chrome://settings/content ) and select "Do not allow any site to run JavaScript"
Then visit your daily sites.
e.g. Google , Facebook , Twitter
(Remember to turn JavaScript back on to see this presentation!)
Note the sometimes subtle and sometimes major differences:
The modern web just sort of gives up without JavaScript!
Especially "one-page apps" where the experience is very seamless.
Like
this one
Part 1
As the owner of the thriving store, Planet Robots, you have to make sure you have a top notch website.
You'll want to do things like offer online shopping, print shipping labels and tempt loyal customers with members only sales!
You'll also want to make sure that everything works properly as well.
That means customers shouldn't be able to submit empty forms and product totals must be calculated properly in their shopping carts.
In order to create a website that can handle these requirements, we will need to learn how to use variables, functions, objects, arrays and loops.
Variables are used to store values.
Declaring a variable tells the computer that it exists and to
remember it.
Variables are like boxes; it can be used to store different things.
Variables are also like the computer's short-term memory. It doesn't remember anything unless you tell it to.
In this example, the computer can't remember anyone's name!
In a web checkout form that asks for your name and address, variables can be used to store this information. Then they can be used to create things like shipping labels.
Before we continue, here's a few helpful JavaScript built-ins that will help with testing and writing code.
*Declare variables with the keyword var.
var email;
Assign a value to the variable using the equals (=) sign.
End the statement with a semicolon (;).
var email = "hello@isanybodyoutthere.com";
Now the computer will remember my email address!
Statements are commands that tell the computer what to do.
Ending the statement with a semicolon is like ending a sentence
with a period. It tells the computer that the statement is done.
IMPORTANT!
Using the equals (=) symbol in Javascript is NOT the same as in math.
var total = 1 + 1
is not the same as
1 + 1 = 2
You will see later that we can change the value of a variable.
Variables are assigned a value with whatever you place to the right of '='.
Variables can hold different kinds of values.
1. Numeric variable (integers & decimals)
var someIntegerNumber = 10; var someDecimalNumber = 10.5;
2. String variable (letters, words & sentences)
var singleWordString = "hello"; var sentenceString = "Hello, good day to you!"; var numberString = "10";
3. Boolean variable (true/false)
var isSaturday = false; var isSunday = true;
String values are always written inside single or double quotes ('string' or "string").
Variables cannot start with a number or any special characters except for underscores (_) and dollar signs ($).
Although it's valid to use underscore or a dollar sign, it is not used often
and usually only in special circumstances.
Variables can't contain spaces. Use a convention called camel case.
Every new word is capitalized and the result looks likeCamelHumps.
JavaScript is case sensitive so variable names are also case sensitive.
Another convention is to use underscores to_separate_words. This is common in other programming languages (like PHP).
*When naming a variable, it's best to give it a descriptive name.
It makes it easier to see at a glance, what kind of value that variable is going to hold.
This is especially useful when sharing code with others who may not use the same kinds of abbreviations.
var firstName; ← Clear that first name will go here.
var fn; ← Not as obvious as firstName.
var x; ← Not clear at all.
Whitespace refers to blank characters and includes space characters, tabs and line breaks.
JavaScript ignores whitespace except when used in a string.
var name="Sean"; //same as var name = "Sean";*
Sometimes you want to write notes to yourself (and others!) to organize blocks of code or leave explanations, but you want the browser to ignore it. Use comments!
// This is how you leave a single line comment. // You can write many single line comments. // Just make sure to add the double backslash // for every new line.
Here's another way to comment larger blocks of text.
/* This is how you leave multi-line comments for when you want to write a longer message */
Multi-line comments are great for "hiding" large blocks of code so you can try something new without erasing your old code. Don't forget to remove the old code later if you decide that you don't need it though!
Here's a test shipping form. Right now, after you press Run, the shipping label is blank. How do we fix this?
(1) Use variables to store your name and address!
(2) To verify that your variables are working, uncomment out the document.write() lines and replace ********** with the actual name of your variables.
We can use JavaScript to do math using arithmetic operators.
The arithmetic operators in JavaScript are (+) for addition, (-) for subtraction, (*) for multiplication and (/) for division.
*Getting JavaScript to do math can be very useful.
For example, we can use it to calculate totals in a shopping cart form.
Instead of using just numbers, JavaScript can do math using variables with numerical values.
*Remember there were different variable types? Arithmetic operators can only be performed on numerical values.
But numbers can be declared as strings too, so be careful!
If you put double quotes (" ") or single quotes (' ') around the value, the computer will thinks it's a string.
*Let's try applying some arithmetic operations to our shopping cart.
addition (+), subtraction (-), multiplication (*), division (/)
Even after a variable has been declared with a value, we can still
re-assign the value. For example, we may want to increase or decrease values by 1. This will come in handy when we discuss Loops later on.
Don't worry about the function or unfamiliar parts right now. You will be familiar with them soon enough.
Run it and see what happens!
Here's a one-product shopping page where you can update the
quantity by adding or removing it from the shopping cart.
Here's what it will look like.
Go to the next slide to get the exercise code.
How do we increase or decrease the value of the variable?
Now that we've calculated some numerical totals, how do we format the output to add a non-numerical value like a dollar sign? We use concatenation.
Concatenation is the joining of strings, using the (+) symbol. Remember this example?
*If you use the (+) operator with numerical values, it will add the values. Otherwise, it will combine the outputs as a string.
Only the addition (+) operator can be used to combine strings.
Let's re-visit mini-exercise #2 and add a total cost field.
Let's pretend to be your wise but nagging grandmother right now:
All these things make logical sense to us as grown up humans but computers are a blank slate. The last one is a little closer to the simple instructions that a computer needs.
As a programmer, you tell the computer how to behave across certain states or events by using CONDITIONALS.
If Conditionals...
|
A basic conditional test looks like this: IF the weather is raining |
In JavaScript,
if ( weather == rain ) {
bringUmbrella();
}
|
The round brackets ()
group together a condition to test.
The curly braces {}
group together a set of statements to execute.
Drill this into your head. Tattoo it to your arm! So many errors happen because of this key difference:
|
= assignment Store a value to a variable: var kitten = "Fluffy"; |
== equality Compare a value to another value: if ( kitten == cat ) |
If ConditionalsSometimes it can be rainy but warm, or rainy and cold. You react to each thing individually.
Use several if statements when you're testing mutually inclusive scenarios.
IF the weather is raining |
In JavaScript...
if ( weather == rain ) {
bringUmbrella();
}
if ( temperature < 10 ) {
wearSweater();
}
|
if/else ConditionalsSometimes there's a catch-all state that you want to happen if your previous tests don't happen.
IF the weather is raining |
In JavaScript...
if ( weather == rain ) {
bringUmbrella();
}else{
dressNormally();
}
|
if/else if/else ConditionalsIt shouldn't snow and rain at the same time so sometimes these conditions are mutually exclusive.
IF the weather is raining |
In JavaScript...
if ( weather == rain ) {
bringUmbrella();
}else if ( weather == snow ) {
wearWarmBoots();
}else{
dressNormally();
}
|
A basic conditional that your browser does internally is to react to mouse clicks on a HTML element. The browser does its own conditional check behind the scenes.

<button onclick="animate()">Pull</button>
IF a user has clicked on a button
THEN call the animate() function.
Notice how the brush acts when you speed up / slow down, or get close to other lines. You can even change brushes.

(Notice how the birds fly differently based on how far you pull them back in the slingshot, and in what direction.)

| If Statement | If...else statement | If...else if...else statement |
|---|---|---|
if (condition) {
|
if (condition) {
|
if (condition) {
|
What does a condition actually look like?
if ( condition ) { ... }
Here's a cheat sheet of different operators that can be used in conditional statements.
Using these two variables, var two = 2 and var ten = 10 , the examples below show how the statements would return true using the various operators.
| Comparison operators | ||
|---|---|---|
| == | is equal to | ten == two * 5 |
| === |
is exactly equal to
(value and type) |
ten === 10
ten === "10" (false) |
| != | is not equal to | ten !== two |
| > | greater than | ten > two |
| < | less than | two < ten |
| >= | greater than or equal to |
ten >= two * 5
ten >= two * 5 + 1 |
| <= | less than for equal to |
two
<= ten
two <= 2 |
| Logical operators | ||
|---|---|---|
| && | and | (ten < 11 && ten > 9) |
| || | or | (ten == 10 || two == 2) |
| ! | not | !(ten == two) |
Let's look at some examples. What do you think the output will be? Uncomment the code to be executed for each condition to see if the result is what you expected. Try changing the variable values too!
Now that we know what variables, operators and conditionals are, let's put them all into action using dynamic content.
Uh-oh! Someone can attempt to put a negative number of products in their shopping cart! Complete task #1 in the next slide to fix this. For task #2, warn the user that they are attempting to check out with an empty basket. Make a more robust shopping cart so that your customer's order doesn't go sideways.
This is based on Exercise #3 so it should look very familiar!
(Hint: How do you test if a number is greater than, less then, or equal to another number?)
TODO: Check within the code for your THREE tasks.
Let's revisit the shipping form again -- it's a very simple shipping form, but you don't want someone to be able to submit their order if they haven't filled out their address!
You have been supplied with 1 variable ("address") which will automagically match what is typed into the form field (minus extra whitespace) after you press the "Check out now!" button.
(Hint: If you don't type anything into the address field, you get an "empty string". How do you test for an empty string?)
TODO: Check within the code for your ONE task.
Now here's a more complex shopping form that you require all fields to be filled in. You have been supplied with 3 additional variables which will automagically update: "name", "city", and "postal".
(Hint for task #3: How do you test for something AND somethingElse OR anotherThing at one time?)
Bonus: There's always different ways to get to the same end goal. If you're finished early, try out different ways that you can reduce the number of variables and lines of code.
TODO: Check within the code for your FOUR tasks.
Learn from our mistakes!
Name something that you did while writing code that caused an error. What were you attempting to do and what were your assumptions when doing it? How did you fix it?
What are some questions or issues you are having with the material covered so far? Lunch with your mentors and pick their brains. :)
Come back for 2:00pm
And we will move on to Part 2