An Introduction
to JavaScript.

Women/InTech

September 22, 2013

Who am I?


Lauren Herda

I design software and other cool stuff at Figure 53.

www.herda.me
@herda on App.net
@lrenhrda on Twitter

I'm a user experience (UX) and front-end visual designer for Web, mobile, and installation applications.

What is JavaScript?

  • Not quite "programming."
  • Interpreted, rather than compiled.
  • Not Java!
    • The two share syntax... 
    • But they fill separate roles.

JavaScript's Role

(Or, at least so far as we're concerned)…

  • Applies behaviors to elements on a Web page.
  • Client-side, not server-side.
  • Primarily used to enhance a site's interactivity. 

However, JavaScript has uses beyond what we're going to cover in this class, and you in can in fact carry your knowledge of JavaScript over to doing server-side coding!

vs. HTML & CSS

  • HTML is how you organize a page.
  • CSS is how you present that page.
  • JS is how you interact with a page.

What You'll Need

Getting Started

  • Take a look at Google Chrome.
  • View → Developer → JavaScript Console
  • Console works as a real-time interpreter for JavaScript.
  • Console simulates how the browser interprets your script.

The Basics of JS

Playing Around a Bit…

  • "Lauren";
    "Lauren"
  • 5 + 7;
    12
  • 12 * 12;
    144

Interacting

  • console.log("Lauren");
    "Lauren"
  • Let's try… confirm("Are you there?"); prompt("What is your name?");
  • Now try a random word without quotes!

Remembering and Recalling Data

In JavaScript, you can sometimes think of things as "nouns" and "verbs."

The "nouns" in JavaScript are your data. Data can be stored in variables.

  • var myName = "Lauren"; var myNameLength = "Lauren".length;

Now we’ve stored a couple of things in variables: my name, and the length of my name. Let's interact with that data…

  • alert(myName); alert(myNameLength);

There are 5 basic data types that you can work with in JavaScript…

undefined

  • Data type undefined is the default. If a variable has never been created/set, it is automatically treated as undefined.
  • booger;
    ReferenceError: booger is not defined
  • Chrome is not able to refer to booger, so it returns a reference error.

null

  • null is a value that is intentionally "nothing."
  • If we set booger to null, notice what happens when we try to recall it…
  • booger = null; booger;
    null
  • No more ReferenceError!

number

  • A number can be any numeric value. 5;
    5
  • Doing some math will return a numeric value. 12.5 * 11;
    137.5

boolean

  • A boolean value will be either true, or false.
  • var baz = false; baz;
    false

string

  • A string value can be created by wrapping a sequence of characters in quotes. "Lauren";
    "Lauren"

Comparisons

  • == — Equal
  • > — Greater than
  • >= — Greater than or equal to
  • === — Identical
  • != - Not equal
  • < — Less than
  • <= — Less than or equal to
  • !== — Not identical
  • var blah = "Lauren".length != 3; console.log(blah);
    true
    blah == 7;
    false

Control Structures

Now that we have data and comparators, we can start to make use of them using control structures.

  • An if statement: if ( <condition>) {  <code> }
  • A while loop: while ( <condition>) {  <code> }
  • A do while loop: do {  <code> } while ( <condition>)
  • A switch statement:
    switch (<condition>) { 
    case <condition>:
        …
        break;
    default:
        …
        break;
    }
    
  • A for loop:
    for (<init>; <condition>; <incrementor>) { <code> }

Math Review & Modulo

  • Basic Math (4 * 2) - (3 + 2);
    3
    (12 / 3) * 8;
    32
  • Modulo — returns the remainder of division! 75 % 8
    3

Logical Operators

  • Negation ("NOT ___") if (!myVar === false) { … }
  • Disjunction ("___ OR ___") if (x == 3 || y == 7) { … }
  • Conjunction ("___ AND ___") if (x == 3 && y == 7) { … }
  • Ternary Conditional (x == 3 ? alert("Yep") : alert("Nope"))

    Proceeds with one of two cases, based on a condition. 

    If the condition is truthy, it proceeds with the expression after the ?. If falsy, it proceeds with the expression after the :.

Remember the 5 basic data types, and the comparators?

“Falsy” Values

  1. false
  2. 0
  3. ""
  4. null
  5. undefined
  6. NaN

“Truthy” Values

  1. Anything else!
  2. "0"
  3. "false"
  4. empty functions
  5. empty arrays
  6. empty objects

Comparison of Falsy Values

  • Know that false, 0, "" are equivalently falsy.

    var c = (false == 0);     // true
    var d = (false == "");    // true
    var e = (0 == "");        // true
    
  • Also,  null and undefined are only equivalent to themselves and one-another, but NaN isn't even equivalent to NaN!

    var f = (null == false);          // false
    var g = (null == null);           // true
    var h = (undefined == undefined); // true
    var i = (undefined == null);      // true
  • You can compare both the value AND the type of an object by using the Identical ( ===) or Not Identical ( !==) comparators.

Comments

  • Leaving notes for yourself & others… // a single-line comment
    /* -------------------------------
    A super-fancy multi-line comment
    that uses some extra characters to
    enhance readability!
    -------------------------------- */

Comments are not only useful for helping yourself take notes and keep track of things in your code… they're also often the only way that another coder will be able to understand your code!

A Basic Script

var letsStart = confirm("Shall we begin?");

if (letsStart === true) {
  userName = prompt("What is your name?");
  if (userName !== null && userName !== "") {
    nameCount = prompt("Thanks! How many times should I print your name?");
    if (nameCount > 0) {
      for(c = 0; c < nameCount; c++) {
        console.log(userName);
      }
    } else {
      console.log("You must enter a number greater than 0.");
    }
  } else {
    console.log("You must enter a name. Please try again.");
  }
} else {
  console.log("I can not begin without your name. Please try again.");
}

Functions

Functions are a way to take blocks of code and save them for future use.

  • Can be defined two ways: function myFunction() { … }; var myFunction = function() { … };

Functions can define parameters that allow you to change the output of the function each time you call it, by passing in arguments.

  • Calling a function… myFunction(argument1, argument2);
var creepyChant = function(userName, c) {
    while (c > 0) {
        console.log("All work and no play makes " + userName + " a dull girl.");
        c--;
    }
};

creepyChant("Lauren", 3);

Use return to pass data back out of the function to the point at which it was called:

var getUserName = function() {
    var fname = prompt("What is your first name?");
    var lname = prompt("What is your last name?");
    return fname + " " + lname;
}
console.log(getUserName());
"Lauren Herda"

Objects

An object is a collection of data set into named slots.

  • A variable in an object is called a property. "Lauren".length;
    6
  • A function in an object is known as a method. "Lauren".substring(0, 3);
    "Lau"

NB: .log() is a method of the console object!

  • Objects can be created from a constructorvar dinner = new Pizza();

    This is done using the new keyword.

  • This creates (instantiates) a new instance of the object.
  • In JS, you can add properties and methods to object instances on the fly using dot notation. dinner.crustType = "Crispy";
  • Objects may also be defined literally…
    var familyPet = {
        species: "dog",
        breed: "German Shepard",
        name: "Abby",
        birthday: new Date(2011, 4, 11),
        age: function() {
            var millisecondsInYear = 31536000000;
            return Math.floor((Date.now() - this.birthday) / millisecondsInYear);
        }
    };
    

    Literals are fixed values—not variables—that you literally provide in your script.

Arrays

JS provides many built-in advanced data types based on objects (like Date). One of these is Array. Array has a handy constructor shortcut:

  • Create an array instance using []… var favoriteToppings = ["Pepperoni", "Mushrooms"];
  • Add to an array using a built-in method… favoriteToppings.push("Sausage");
  • Let's add this to our dinner pizza… dinner.toppings = favoriteToppings;
  • Data in an array can be accessed like so: dinner.toppings[0]
    "Pepperoni"

    Note: the values are addressed starting at 0, not 1.

  • Arrays can also store data in named slots… dinner.dinnertime["start"] = new Date(2013,09,22,17)
    Sun Sept 22 2013 17:00:00 GMT-0400 (EDT)

    These are associative arrays, and they're similar to objects!

    dinner.dinnertime.start

Working with
Web Pages

The DOM

  • The DOM (Document Object Model) is your browser’s "mental model" of how a Web page is structured—it uses it as a guide for rendering the elements on your screen.

jQuery

While JS has many built-in DOM tools, jQuery makes it all much simpler.

  • jQuery adds support for CSS-like selectors. $("span.highlight");

    The $ function allows you to select elements on the page.

  • jQuery helps you handle user events. $("button").click(<function>);

Selectors

  • All Selector $("*")

    Selects all elements.

  • Class Selector $(".classname")

    Selects all elements with the given class.

  • Element Selector $("div")

    Selects all elements with the given tag name.

  • ID Selector $("#main")

    Selects all elements with the given ID attribute.

  • Multi-Selector $(".classname, #idname, span")

    Selects a combined set of elements based on the selectors.

Document Ready!

  • We'll need to make sure the DOM is loaded. $(document).ready(<function>);
  • Now we can pass a function to .ready()…
    $(document).ready(function() {
        console.log("Ready!");
    }
    

An Introduction to JavaScript

By Lauren Herda

An Introduction to JavaScript

The basics of the JavaScript language and how to use it in your Web browser.

  • 11,523
Loading comments...