Download class materials

http://bit.ly/gdipgh-js-materials

This includes the slides.


Online Slides

You can also access the slides at http://bit.ly/gdipgh-js-slides

Beginning Javascript

Class 1

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What is your favorite dinosaur?

Goals for the class

  • Week 1: Intro to JavaScript
  • Week 2: More JavaScript & the DOM
  • Week 3: Intro to jQuery
  • Week 4: AJAX and APIs

Terms

  • Web design
    The process of planning, structuring and creating a website
  • Web development
    The process of programming dynamic web applications

Terms

  • Front end
    The outwardly visible elements of a website or application. (Javascript goes here!)
  • Back end
    The inner workings and functionality of a website or application.

Clients and servers

How your computer accesses websites

JavaScript is "client side"

Your browser understands it!

History of JavaScript

  • Developed by Brendan Eich of Netscape in 1995
  • Standardized in 1997
  • Java -- Actually JavaScript has nothing to do with the language Java. Java was just the cool kid in town at the time
  • Script -- Instructions that a computer can run one line at a time

History of JavaScript

  • "AJAX" -- a way to communicate to servers was created in 2005
  • jQuery -- a super-popular JavaScript Library 2006
  • Node.js -- a way for JavaScript to perform back end functions in 2010
  • 2012 -- spec for JavaScript "nearly" finished

What does JavaScript do?

Useful References

Activity: Enhance a Web Site
Using JavaScript

Use JavaScript to add content and interactivity
to a web site

You will need

Open the files in your text editor

The project can be found in the activity folder.

Open the page in your browser

Open index.html.

Note

Our activities throughout the class will
build on each other. Make sure
you keep your work.

Statements/Script

Each line in JavaScript is an instruction or a script.

When the browser reads it, it "executes the script".


  alert('Hello World!');
          

Statements usually end with a semicolon

Try it out using the console.


  alert('Hello World!');
          

alert displays a message in an alert box

Useful for notifying your user about an important event.

Use sparingly!

Let's try another one!


  console.log('Hello World!');
          

console.log outputs a message to the web console

This is very useful for debugging

Adding JS to HTML

Three main ways, just like CSS

Adding JS to HTML: Inline


  <html>
    <head>
      <title>My Site!</title>
    </head>
    <body>
      My site!
      <a href="#" onclick="alert('Hello World!');">click me</a>
    </body>
  </html>
          

We'll talk more about this one later

Adding JS to HTML: Embedded


  <html>
    <head>
      <title>My Site!</title>
      <script>
        alert("Hello World!");
      </script>
    </head>
    <body>
      My site!
    </body>
  </html>
          

Adding JS to HTML: External


  <html>
    <head>
      <title>My Site!</title>
      <script src="scripts.js"></script>
    </head>
    <body>
      My site!
    </body>
  </html>
          

scripts.js


  alert("Hello World!");
          

This is usually the best way to add JavaScript.

Let's Develop It

Hello World

  • Create a new JavaScript file (a file that ends in .js)
  • Link it to your html file
  • Output "Hello World" in your JavaScript file

Let's Develop It

index.html

    <!DOCTYPE html>
    <html>
      <head>
        <title>Jane Doe's Site!</title>
        <link rel="stylesheet" href="style.css">
        <script src="scripts.js"></script>
      </head>
      <body>
        <img class="photo" src="photo.png">
        <h1>Jane Doe</h1>
        <p>Hi! My name is Jane Doe.</p>
      </body>
    </html>
            

Let's Develop It

scripts.js

    alert("Hello World!");
            
or

    console.log("Hello World");
            

Example

Are you done or really stuck?

Check out our example.

Data Types

Information (data) in JavaScript
comes in different types.

Data type: String

A group of characters in quotes

You can use double quotes


  console.log("Hello World");
            

or single quotes


  console.log('Hello World!');
            
Make sure your quotes match!

Data type: Number

Integers


  console.log(2012);
            

Decimals


  console.log(3.14);
            

Data type: Boolean

true or false


  console.log(true);
            

  console.log(false);
            

true/false must be all lowercase

Data type: Null

A special keyword denoting an empty (null) value.


  console.log(null);
            

null must be all lowercase

Variables

Variables store information

Declare a variable (Give it a name)


  var bananas;
            

Initialize variable (Give it a value)


  bananas = 5;
            

Variables

Declare and initialize at the same time!


  var bananas = 5;
            

Change value of variable


  bananas = 4;
            

(I ate a banana)

Naming rules

Begin with a letter, _, or $

Contain letters, numbers, _ and $


  var hello;
  var _hello;
  var $hello;
  var hello2;
            

Names are case sensitive


  var hello;
  var Hello;
  var heLLO;
            

Naming conventions

Most people use either

Snake case


  var hello;
  var hello_world;
  var first_name;
            

Camel case


  var hello;
  var helloWorld;
  var firstName;
            

Stick with one for consistency

Naming conventions

Give variables meaningful names

bad names


    var foo = 3.14;
    var fn = "Julie";
    var a = true;
            

good names


    var pi = 3.14;
    var firstName = "Julie";
    var isAllowed = true;
            

Data type: Undefined

no value yet


  var favoriteDinosaur;
            

JS data types are "loosely typed"

You don't know the data type of a variable until you assign it.

The type can change when it is assigned different values.


  var looseType;      // I am undefined
  looseType = 10;     // I am a number
  looseType = "hi!";  // I am a string
  looseType = false;  // I am a boolean
  looseType = null;   // I am null
          

Comments

Used to add hints, notes, suggestions, or warnings.
The browser will ignore them.


  // comment on one line
  /* comment on
     multiple lines
   */
          

Warning: Other people can see them in the source.


  // My super-secret password is password1234
  /* I hate my users so much!
     I curse them!
   */
          

Arithmetic Expressions

Math-y expressions!

Arithmetic Expressions:
Addition (+)


  var bananas = 5;
  var oranges = 2;
  var fruit = bananas + oranges;
          

Arithmetic Expressions:
Subtraction (-)


  var bananas = 5;
  var people = 3;
  var leftover_fruit = bananas - people;
          

Arithmetic Expressions:
Multiplication (*)


  var seconds_per_minute = 60;
  var minutes_per_hour = 60;
  var seconds_per_hour = seconds_per_minute * minutes_per_hour;
          

Arithmetic Expressions:
Division (/)


  var days_per_year = 365;
  var days_per_week = 7;
  var weeks_per_year = days_per_year / days_per_week;
          

Arithmetic Expressions:
Modulus (%)

Returns the integer remainder of
dividing the two operands.


  var grapes = 37;
  var people = 7;
  var leftover = grapes % people;
          

Arithmetic Expressions:
Increment (++)

Increments the value by 1

Postfix - returns the value before adding one.


    var current_hour = 8;
    current_hour++; // Returns 8
    current_hour;   // Returns 9
            

Prefix - returns the value after adding one.


    var current_hour = 8;
    ++current_hour; // Returns 9
    current_hour;   // Returns 9
            

Arithmetic Expressions:
Decrement (--)

Decrease the value by 1

Postfix - returns the value before subtracting one.


    var current_hour = 8;
    current_hour--; // Returns 8
    current_hour;   // Returns 7
            

Prefix - returns the value after subtracting one.


    var current_hour = 8;
    --current_hour; // Returns 7
    current_hour;   // Returns 7
            

String Expressions

Word-y expressions!

String Expressions:
Concatenation (+)

Combines strings together


  var phrase = "My name is ";
  var name = "Pat";
  var sentence = phrase + name + ".";
          

Assign and concatenate (+=)


  var sentence = "My name is ";
  sentence += "Jo";
  sentence += " and I like " + "cats";
            

We also used + for addition.

What happens when we mix numbers and strings?


  var num = 5;    // This is a number
  var str = "10"; // This is a string
  num + num; // 10
  str + str; // "1010"
  num + str; // ????
  str + num; // ????
          

  var num = 5;    // This is a number
  var str = "10"; // This is a string
  num + num; // 10
  str + str; // "1010"
  num + str; // "510"
  str + num; // "105"
          

Be careful when you mix data types.
You can get unexpected results.

Let's Develop It

Favorite activity calculator

How many times do you do something in a year?

  • Store one of your favorite activities in a variable
  • Store the times you do it per month in a variable
  • Store the months in a year in a variable
  • Calculate how many times you do the activity per year using math operations
  • Output the result in one alert that includes: the activity, times you do it a month, and times you do it a year

Let's Develop It

Favorite activity calculator

Hints

  • timesPerYear = timesPerMonth * monthsPerYear
  • You will need string concatenation to create the result.
  • Creating extra variables may be helpful.

Example

Are you done or really stuck?

Check out our example.

if statement

Runs some JavaScript based on conditions


  if (conditions) {
    // statement to execute
  }
            

If the conditions evaluate as true,
the JavaScript inside the braces runs.


  var bananas = 1;
  if (bananas < 2) {
    console.log("You should buy more bananas!");
  }
            

What would happen if bananas was set to 3?

block statement

A group of statements deliniated by braces.


  {
    console.log("statement 1");
    console.log("statement 2");
    console.log("statement 3");
  }
          

Comparisons

Compare the values and return a logical value (boolean) based on whether the comparison is true

Frequently used in conditionals like if


  (bananas < 2)
            

Comparison: Equal

Returns true if the values are equal


  1 == 1; // true
  1 == 2; // false
  "this" == "this" // true
  "this" == "that" // false
  10 == "10" // ???
          

Use strict equals to check the data type (recommended)


  1 === 1; // true
  1 === 2; // false
  "this" === "this" // true
  "this" === "that" // false
  10 === "10" // false
          

Comparison: Equal

Returns true if the values are equal

Don't confuse = (assign a value)
with == or === (compare a value)

Comparison: Not Equal

Returns true if the values are not equal


  1 != 1; // false
  1 != 2; // true
  "this" != "this" // false
  "this" != "that" // true
  10 != "10" // false
          

Use strict not equals to check the data type (recommended)


  1 !== 1; // false
  1 !== 2; // true
  "this" !== "this" // false
  "this" !== "that" // true
  10 !== "10" // true
          

Comparison: Greater than


  3 > 1; // true
  2 > 4; // false
          

Comparison: Greater than or equal


  3 >= 1; // true
  3 >= 3; // true
  2 >= 4; // false
          

Comparison: Less than


  1 < 3; // true
  4 < 2; // false
          

Comparison: Less than or equal


  1 <= 3; // true
  3 <= 3; // true
  4 <= 2; // false
          

Logic Operators

Combine or modify boolean values.

Logic Operator: AND

Returns true if all values are true.

Otherwise it returns false.


  true && true;   // true
  true && false;  // false
  false && true;  // false
  false && false; // false
          

  true && true && false; // ???
          

  (1 === 1) && ("this" != "that"); // ???
          

Logic Operator: OR

Returns true if any value is true.

Returns false if all values are false.


  true || true;   // true
  true || false;  // true
  false || true;  // true
  false || false; // false
          

  false || false || true; // ???
          

  (3 == 4) || (true); // ???
          

Logic Operator: NOT

Inverts the boolean value.


  !false; // true
  !true;  // false
          

  !(1 === 1); // ???
          

  !(6 > 2); // ???
          

Logic Operator: Example


  var bananas = 5;
  var oranges = 2;

  if (bananas > 3 && oranges > 3){
    console.log('Eat fruit!');
  }

  if (bananas < 2 || oranges < 2){
    console.log('Buy fruit!');
  }

  if (!(bananas >= 0)){
    console.log('How do you have negative bananas?');
  }
            

Evaluate to false in
logical expressions

false isn't the only one

  • false
  • null
  • 0
  • empty string ("" or '')
  • undefined

  false || null || 0 || "" || '' || undefined; // false
          

If/Else Statement

You can use else to perform an alternative action if the "if" fails


  var bananas = 5;
  if (bananas > 3){
    console.log('Eat a banana!');
  } else {
    console.log('Buy a banana!');
  }
          

If/Else Statement

You can use else if to have multiple choices


  var age = 20;
  if (age >= 35) {
    console.log('You can vote AND hold any place in government!');
  } else if (age >= 25) {
    console.log('You can vote AND run for the Senate!');
  } else if (age >= 18) {
    console.log('You can vote!');
  } else {
    console.log('You have no voice in government (yet)!');
  }
          

Let's Develop It!: Welcome

Output a welcome message

  • Set a variable with the current month (number)
  • Set a variable with the current day (number)
  • Set a variable with your birth month (number)
  • Set a variable with your birth day (number)
  • If the current day/month matches your birth day/month output a birthday message
  • Otherwise, output a general message

Let's Develop It!: Welcome

Output a welcome message

  • Extra credit: Output a holiday message if the month is December

On your birthday

On regular days

In December

Example

Are you done or really stuck?

Check out our example.

Dates

Get the current date and time


  var date = new Date();
          

Set a specific date and time using a string


  var adaLovelaceBday = new Date("December 10, 1815");
  var dueDate = new Date("May 1, 2015 12:30");
          

Dates

Set a specific date and time using numbers


  var newYear = new Date(2015, 0, 1, 0, 0, 0);
          
  • year - 4-digits
  • month - starting with 0 for Jan to 11 for Dec
  • day - the day of the month (1-31)
  • hour - the hour of the day (0-23)
  • minute - the minutes (0-59) for time
  • second - the seconds (0-59) for time

Dates

Get information about a date


  var date = new Date();
  date.getFullYear(); // Year
  date.getMonth();    // Month
  date.getDate();     // Day
  date.getHours();    // Hour
  date.getMinutes();  // Minute
  date.getSeconds();  // Second
          

See the Mozilla Developer Network for
more information about dates

Let's Develop It!: Welcome message

Modify your welcome message to automate
the current month/day

  • Create a variable with the current date
  • Set your current month variable using the month from the current date
  • Set your current day variable using the day from the current date

Hints

  • You can get the current date using new Date()
  • You can get the month from a date using .getMonth()
  • You can get the day from a date using .getDate()

Example

Are you done or really stuck?

Check out our example.

Questions?

?