Introduction to Programming Concepts via jQuery

Data types & conditionals

Try typing the following into your console. What do you expect to get? What do you actually get?


  2 + 2


  '2' + '2'

What's up with that?

What you're seeing here are your very first data types: in this case, numbers and strings.

The idea of data types covers two things:

  • What an object is -- strings are actually different sorts of things than numbers;
  • What you can do with it. Addition is a thing you can only do with numbers and concatenation is a thing you can only do with strings, even though we referred to both of them above as "+".

Just for fun:


No, not that Data.

  'two' + 'two'

A couple of things that will be important if you work with other languages, and/or if you really like nerdy details.
  • Languages don't always use the same names for their data types, but there are some you'll find in just about every language even if their names differ. Strings are ubiquitous. So are numbers - although Javascript just has one numeric type, Number, whereas some languages have several types representing different types of numbers (e.g. Python's int, for integers, and float, for numbers which may have fractional parts). Lots of languages have a data type representing key/value pairs, but Javascript's is called an associative array and Python's is called a dict (short for "dictionary", your favorite key-value pair in everyday life).
  • Key takeaway: don't get too hung up on what the types are called (and be prepared to look for new terminology if you study a different language). But do understand the core ideas of what a data type is and what kinds are out there - you'll see those ideas in every language.
  • Languages let you define your own data types, too. If you needed to have a data type "MARC record" that was allowed to have fields with certain properties, and that had functions like "update" but didn't have functions like "+" (because what would it even mean to "+" two MARC records)? You could do that.
  • Languages vary in how up-front they are with you about the existence of data types, and how much they make you deal with the data type machinery. This is good and bad! For instance, Javascript lets you define a new variable without defining its data type (not all languages do this). This makes it much simpler to get started, and often faster to write. On the other hand, you and the computer might end up disagreeing about what kind of data is in your variable, to unpredictable results.
  • My favorite language is Python, which hides a lot of the data type machinery - I feel like the language gets out of my way and just does what I mean to a remarkable extent. My husband much prefers C, because its strong typing system keeps him from making (certain kinds of) mistakes, especially in complex codebases too large to understand in their entirety.

Indexing, programmer-style

One function you can use on strings (but not on numbers!) is indexOf().

This function operates on a string and takes one argument, another string. And argument is a new term, so let's define it! An argument is an input that you stick into a function, and in many programming languages arguments go inside the parentheses that follow function names. Some functions (like noConflict()) don't take any arguments. Others take one, or several. Arguments may be optional (in which case the function will do something logical whether or not you provide them) or required (in which case you will see some kind of error message if you don't provide them). It all depends on what the function does and what kind of information it needs to do that.

Getting back to indexOf(): it operates on a string and takes one argument, another string. It tells you where (or if) the argument first occurs in your string. So for example:


  'jQuery'.indexOf('Q');

What got returned when you typed that?

A very important thing to notice here is that programmers can't count. Most programming languages are what's called zero-indexed: that means that, when you are counting what position you're at in a string (or other list of values), you start at 0. In the string jQuery, j is in the 0th position, Q is in the 1st position, and so forth.

It is easy to end up with so-called off-by-one errors when programming, and everyone has. If you're writing code that's counting things, slicing them, etc., and it's not doing quite what you expect, check for this.

Okay, let's try some other examples:


  'jQuery'.indexOf('ry');

  'Mississippi'.indexOf('i');

  'Mississippi'.indexOf('q');

  'jQuery'.indexOf('q');

What was up with those?

We'll be using indexOf() a lot, so make sure you have a good handle on how it behaves.

You've probably noticed by now that programmers don't use the word index in the same way librarians do, although the meanings are related. Instead of being a collection of things you might find in a text and the page numbers for where you'd find them, an index is just the number of the location where you'd find a thing. I might talk about indexing into a string or a variable - that means looking at a particular location in that string or variable, as dictated by the index.

By the way, you can go in the reverse direction, too — if you have an index and a string, you can find out what character is at that index in the string. What do you think these will return?


  'jQuery'[0]

  'jQuery'[1]

  'jQuery'[6]

Did they do what you expected?

A what? Array!

Another data type that's good to know, now that we know about indexes, is array.

An array is a list of ...stuff. Any kind of stuff! The stuff can be of type string, or type number, or any other data type you have lying around. The different items on the list don't even have to be of the same type (though usually they are).

Arrays are ubiquitous in programming because the real world is full of lists of stuff. Your ILS contains, in a sense, a gigantic list of MARC records (and another gigantic list of patron records, and another of transaction records, et cetera). It's just a handy mental model when we need to keep track of lots of things. As we'll see later, it's also handy when we need to do stuff to lots of things.

Side note!

I might accidentally call arrays "lists", because that's what they're called in Python, which is what I usually program in. You can upbraid me if it confuses you.

Here's an example array:


  var courseDataTypes = ['string', 'number', 'array']

Important things to note:

  • The array begins with a [ and ends with a ].
  • Its elements are separated by commas.
  • Arrays stay in order. If we looked at courseDataTypes later, 'string' would still be first and 'array' would still be last.

If you want to access individual elements of an array, you do so with the same indexing you saw above (remember, zero-based!). What will these lines return?


  courseDataTypes[0]

  courseDataTypes[1]

  courseDataTypes[2]

  courseDataTypes[3]

Time to make a banana split

Now that we know about arrays, we can understand another useful function: split(). The split() function operates on strings and takes one argument: the character at which you should split the list apart. It returns an array of all the substrings that were in between your separator character(s). This'll be easier to see with an example:


  'banana'.split('a')

Can you explain what just happened there?

Let's try a few more examples:


  'banana'.split('n')

  'banana'.split('b')

  'banana'.split('an')

  'banana'.split('')

  'banana'.split('q')

  'banana'.split(2)
  
  var myBanana = 'banana';
  
  myBanana.split('a')

As you have probably guessed, a useful programming technique, when you're not quite sure how something works, is to try out edge cases. Look for places where the program might do something weird, and see what happens! This will illuminate the details of its behavior (and whether they match what you expect).

When you're writing your own programs, it's important to think through all the edge cases that your data or your users might present you with, and be sure to handle them in some appropriate way. (Or, I should say, it's important to try to think them through; in practice you will probably miss some, especially if your program has users other than yourself - users are so unpredictable! This is why it's important to test programs, and good if you can revisit and improve them over time.)

Aw yeah conditionals

Time to write our first multi-line programs!

There are lots of times you might want to run different code, depending on your inputs:

  • Make the buttons grey if the cursor is hovering over them, but purple otherwise;
  • Flag a MARC record for human review if it doesn't have an ISBN, but leave it alone otherwise;
  • Make a number red if it represents a loss but black if it represents a surplus;
  • What else?

In programming, we do this with if/else statements (also called conditionals). You'll frequently see conditionals used together with booleans: if a condition is met, do something; otherwise, do something else.

The following code will execute when we click the buttons below. What will happen with each button? (.hide() does what you would guess from the name.)

By the way, $j(this) is shorthand for "whatever object is under consideration right now". If you have a function that gets called when you click on something, it's the thing you just clicked; that's how we're using it below. We'll see more examples later.


  if ( $j('.conditional-button').html().indexOf('ISBN') > -1 ) {
      $j(this).hide();
  }

Author: Marcus Sakey; Title: Brilliance; ISBN: 9781611099690
Author: Julia Serano; Title: Whipping Girl: A Transsexual Woman on Sexism and the Scapegoating of Femininity
Author: Alfred Lubrano; Title: Limbo: Blue-Collar Roots, White-Collar Dreams; ISBN: 34870005769746
Author: Alice Goffman; Title: On the Run: Fugitive Life in an American City; ISBN: 9780226136714

Question: what are some problems with this approach to flagging records? What kinds of problems will it not catch?

Here's a more complex example. What will this code do?


  if ( $j('.conditional-button2').html().indexOf('ISBN') > -1 ) {
      $j(this).hide();
  } else {
      $j(this).addClass('bg-yellow');
  }

Author: Marcus Sakey; Title: Brilliance; ISBN: 9781611099690
Author: Julia Serano; Title: Whipping Girl: A Transsexual Woman on Sexism and the Scapegoating of Femininity
Author: Alfred Lubrano; Title: Limbo: Blue-Collar Roots, White-Collar Dreams; ISBN: 34870005769746
Author: Alice Goffman; Title: On the Run: Fugitive Life in an American City; ISBN: 9780226136714

As you have seen, the overall structure of an if statement is this:


  if ( something is true ) {
      // do one thing
  } else {
      // do a different thing
  }

Make sure to take note of the parentheses and curly braces - they matter! If you find an if condition you write isn't working, this is the first thing you should proofread for.

The indentation will not make a difference to the computer, but it will make a difference to you — code is easier to read, skim, and debug if it is well-organized.

Your turn!

Here are some functions for you to practice what you've learned. I've written the outlines; your job is to replace the English descriptions with actual code. Type your code into your console and click the buttons - do you get the behavior you expect? (Don't forget to define var $j = jQuery.noConflict(); first, just in case.)

FYI, in my browser (Chrome), when I press enter the code executes immediately, which may not be what I want if I was just trying to put in a line break for readability. If you want the line break but you don't want the code to run yet, press shift-enter instead. You may find it easiest to write the code in a text editor and then copy-paste it into the console when you're satisfied.

As always, don't be surprised if you need to tweak it a few times for it to work. If you get stuck, talk to your neighbors or put a post-it on your computer. If you're done, help others or see if you can extend your code.

Reminder: the classes used to control background colors on this page are bg-purple, bg-yellow, bg-green, bg-orange, and bg-lavender.

.example-1


  $j('.example-1').on('click', function () {
    if ( $j(this) contains the phrase 'go away' ) {
        hide it
    }
  });

.example-2


  $j('.example-2').on('click', function () {
    if ( $j(this) is purple ) {
        make it green
    }
  });

.example-3


  $j('.example-3').on('click', function () {
    if ( $j(this) is purple ) {
        make it green
    } else {
        make it orange
    }
  });

.example-4


  $j('.example-4').on('click', function () {
    if ( $j(this) is purple ) {
        make it green
    } else if ( $j(this) is green) {
        make it orange
    }
  });

In the following two examples, your code will run all at once when you press the "Run code" button — you don't need to press each list item individually.

.example-5

Title list

Author: Marcus Sakey; Title: Brilliance; ISBN: 9781611099690

Author: Julia Serano; Title: Whipping Girl: A Transsexual Woman on Sexism and the Scapegoating of Femininity

Author: Alfred Lubrano; Title: Limbo: Blue-Collar Roots, White-Collar Dreams; ISBN: 34870005769746

Author: Alice Goffman; Title: On the Run: Fugitive Life in an American City; ISBN: 9780226136714

  $j('#example-5-run-button').on('click', function () {
    var titleList = $j('.example-5-title');

    titleList.each(function() {
      if ( $j(this) has an ISBN ) {
        remove it from the list
      }
    });
  });

.example-6

Title list

Author: Marcus Sakey; Title: Brilliance; ISBN: 9781611099690

Author: Julia Serano; Title: Whipping Girl: A Transsexual Woman on Sexism and the Scapegoating of Femininity

Author: Alfred Lubrano; Title: Limbo: Blue-Collar Roots, White-Collar Dreams; ISBN: 34870005769746

Author: Alice Goffman; Title: On the Run: Fugitive Life in an American City; ISBN: 9780226136714

  $j('#example-6-run-button').on('click', function () {
    var titleList = $j('.example-6-title');

    titleList.each(function() {
      if ( $j(this) has an ISBN ) {
        if ( the ISBN starts with 978 ) {
          remove the title from the list
        }
      }
    });
  });

I feedback

Before you leave this room, grab two post-it notes. Write on them:

  • Something that worked well for you today
  • Something that could be working better

Stick them in the feedback space before you leave the room.

previous next