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:
Just for fun:
'two' + 'two'
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).
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?
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.
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:
[
and ends with a
]
.
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]
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.)
Time to write our first multi-line programs!
There are lots of times you might want to run different code, depending on your inputs:
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();
}
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');
}
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.
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
$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
$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
}
}
});
});
Before you leave this room, grab two post-it notes. Write on them:
Stick them in the feedback space before you leave the room.