navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

Foundations of Programming: Fundamentals
Richard Downs

Foundations of Programming: Fundamentals

with Simon Allardice

 


This course provides the core knowledge to begin programming in any language. Simon Allardice uses JavaScript to explore the core syntax of a programming language, and shows how to write and execute your first application and understand what's going on under the hood. The course covers creating small programs to explore conditions, loops, variables, and expressions; working with different kinds of data and seeing how they affect memory; writing modular code; and how to debug, all using different approaches to constructing software applications.

Finally, the course compares how code is written in several different languages, the libraries and frameworks that have grown around them, and the reasons to choose each one.
Topics include:
  • Writing source code
  • Understanding compiled and interpreted languages
  • Requesting input
  • Working with numbers, characters, strings, and operators
  • Writing conditional code
  • Making the code modular
  • Writing loops
  • Finding patterns in strings
  • Working with arrays and collections
  • Adopting a programming style
  • Reading and writing to various locations
  • Debugging
  • Managing memory usage
  • Learning about other languages

show more

author
Simon Allardice
subject
Developer, Web, Programming Foundations
level
Beginner
duration
4h 47m
released
Sep 22, 2011

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:04Hi! I am Simon Allardice and welcome to the Foundations of Programming: Fundamentals course.
00:10What we are exploring here are the core ideas and skills you will always need
00:13when programming on any platform with any language.
00:17Now there are dozens of programming languages you could choose from and we will
00:20see many of them in this course, languages like JavaScript, C, Ruby and Python.
00:25We will see what these different languages are good at and why you might
00:28pick one over another, but I won't be trying to make you an expert on any
00:32one of them. Instead in this course we will go through what's common across
00:36all of these languages.
00:37We will work with things like loops, conditions, variables, and memory;
00:42see how to control the structure and the flow of a program; and what you need to
00:47know about what that program is doing under the hood.
00:49And we are going to make sense of the buzzwords and jargon that you can't
00:53avoid when programming.
00:54These words might not mean anything to you right now, but they will. And we won't just
00:59talk ideas. We will get hands-on on and write programs in this course to prove
01:04these ideas and see why they are important.
01:06So that by the end of this course you would be comfortable with approaching any
01:09programming language.
01:11Welcome to the Foundations of Programming: Fundamentals.
01:15Let's get started.
Collapse this transcript
Making the most of this course
00:00In some courses I teach, I'm really picky about what people already know and I
00:05often have formal lists of required knowledge.
00:08But this course is different and here I have three things that I just don't care about.
00:14Number one, I don't care if you have programmed before. We are starting from
00:18scratch, from the very beginning.
00:20If you've never written a line of code in your life, no problem.
00:24If you don't even know where you begin to write a line of code, that's where we are starting.
00:29So if you have done some programming in the past, that's great.
00:32Maybe you have written some code, you have picked things up along the way, you
00:36have read a couple of books, figured out a bunch of stuff on your own, but you
00:39are not quite sure you got the basics down.
00:41Well, this is the right place to review those fundamentals.
00:45Number two, I don't care whether you like to work on a Mac or Windows PC, a Linux box.
00:52It won't matter.
00:53I do expect you know your way around your computer and your chosen operating system.
00:59And number three,
01:00I don't care what your background is or what age you are.
01:04Sure, I have taught programming to engineers. I've also taught it to English
01:09teachers, artists, nurses, people out of work. I have taught this stuff to kids
01:14under 10 and to people way past retirement.
01:17Now as we go through this course, don't worry about getting everything perfect.
01:22If you feel like you're picking up say 80% of things, pretty well, keep moving on.
01:27Programming is a deep subject and it rewards repeated exposure, so I invite you
01:33to come back to this course.
01:35Even if you think you have picked up everything 100%, try some of it again in
01:39three months or six or a year and I guarantee you'll find new meanings and new
01:44things to pay attention to.
01:46So programming is a powerful skill, not just useful, not just good for your
01:52career, not just a moneymaker, but powerful.
01:56And what I want for you in this course is to start being a creator of programs
02:01and stop being just a user of them.
02:04So, let's begin with exactly what that means.
Collapse this transcript
Using the exercise files
00:00If you are a premium member of lynda.com or if you're watching this tutorial on
00:04a DVD-ROM, you'll have access to some exercise files used in this title.
00:09I have them downloaded to my desktop and they are in a folder called Exercise Files.
00:14I am currently on the Mac here, but it doesn't matter if you use a
00:17different operating system.
00:19Inside that, each of the relevant chapters has its own folder and inside some of
00:25these you'll find some simple files that we will be working with during the
00:28movies and we will point the files out to you at the relevant time by just
00:32showing you the path to the file location.
00:35But they are all just for convenience. They are not required; they just might
00:38make things a little easier when you're following along.
00:41If you don't have access to the exercise files, you can follow along from
00:44scratch although you might need to pause a movie once or twice to copy something across.
Collapse this transcript
1. Programming Basics
What is programming?
00:00So what exactly is programming?
00:03Well, you may have heard a phrase like this before.
00:05A computer program is a set of instructions.
00:09Here is the problem.
00:10This sounds like one of those phrases that might be technically true and is
00:14kind of useless, like the human brain is 80% water. Because you hear this phrase
00:20but then you see a complex program like Photoshop or Flash or something playing
00:24high-definition video or a 3D game and you think, "Yeah but that can't just be a
00:29set of instructions." But that's exactly what these are, all of them.
00:35Every computer program is a series of instructions.
00:39A sequence of separate small commands, one after the other.
00:43Now there maybe five instructions contained in a program, maybe 5,000, maybe 5
00:48million. Each instruction is telling the computer to do something very small,
00:52but very specific and the art of programming is to take a larger idea and break
00:58it apart into these individual steps.
01:00And the wonderful thing is everyone can already do this.
01:04Let's imagine that you're sitting in your house in the suburbs waiting for a
01:08visit from a friend.
01:10Your phone rings, it's her, and she's asking for directions.
01:13She tells you she's at a nearby gas station and you know it. You pass it
01:18everyday, it's on your way home.
01:20So that journey point A to point B drops into your head as one piece, but you
01:27instantly know you can't communicate the journey the way you understand it.
01:32You have to break it down into simpler parts and you have to think about it to
01:36break it down because it's so natural to you.
01:39So you start to pull this apart and "You say you are going to need to turn right,
01:44then drive one mile, then you will turn left on Acacia Avenue, then you'll take
01:51the second right and then it's the fourth house on the left."
01:57Specific, individual, simple, clear, self-contained instructions.
02:03Now you know that sequence here is vitally important.
02:06You mix these up, you will get very different results.
02:09"Turn right, drive 1 mile" takes you to quite a different place from "drive 1 mile, turn right."
02:16But this same level of simple instructions,
02:19turn right, turn left, go straight, could take you around the corner or it could
02:25take you on a five-year trip around the world visiting every Starbucks along the way.
02:30You'd still have instructions like turn right and left.
02:34You'd just need a lot more of them.
02:36So with programming we are giving directions to the computer.
02:40It's breaking apart a more complex idea, a more complex task, into its
02:46smallest individual instructions and then using a programming language to
02:50write those instructions.
02:52Now, of course if you have never programmed, it's not clear right now what those
02:56instructions might be.
02:57You know it's probably not turn right and turn left.
03:00So what are those basic fundamental instruction you give a computer?
03:04Well, they are often very basic. They are things like add two numbers
03:09together, or display a letter on the screen, check to see if the user just hit
03:14the spacebar, change the color of one individual pixel. But as with driving
03:21directions, you string together enough computer instructions that will get
03:24you very far indeed.
03:26So when it might seem difficult to see how you get from basic examples you see
03:30when beginning programming to complex games or applications, well that's what
03:35you get when you have a hundred people writing these instructions for sixty
03:39hours a week for several years, combined with the ability of the computer to
03:43process them mind-bogglingly fast, means that we could, if we wanted to, write
03:49the set of instructions that could calculate every single individual pixel on
03:54the screen thirty times a second.
03:56Now think about that level of speed and think about why your instructions better
04:01be right. Because getting them wrong is like giving wrong directions to your
04:06friend when her car only has two speeds: 0 and 5000 miles an hour.
04:12You get those directions wrong, and the next call you get is her asking why she
04:16followed your instructions to the letter, but her car is now in the middle of a
04:20forest crashed into a tree.
04:22Computers will do exactly what you tell them, so the instructions you give
04:27them better make sense.
04:29In programming languages we write these instructions by writing what are called statements.
04:35Statements in programming languages are kind of like sentences in English.
04:39They use words, numbers, and punctuation to express one thought, one individual piece.
04:46Most programming statements are pretty short, just a few words.
04:50Now, exactly what words, numbers, and punctuation you use depends on the
04:54programming language.
04:56Some languages want each of your statements to end with a semicolon, like ending
05:00a sentence in English with a period, and others don't. You just go to the next
05:04line and start writing the next statement.
05:06Some languages are all uppercase, some languages are all lowercase, some
05:11languages just don't care.
05:12Now, understanding the rules of each language is understanding the syntax of a
05:17programming language.
05:19So programming is the ability to take this idea in your head, break it apart
05:24into its individual pieces, and know how to write those pieces in the programming
05:28language you are using at the time, writing your statements in the right order,
05:33using the right syntax. But what language?
05:37Well, sometimes you get to pick a language and sometimes it's kind of picked for you.
05:41We will talk about that in a moment.
Collapse this transcript
What is a programming language?
00:00There have been hundreds of programming languages since the start of computing.
00:05But at any given time there are perhaps a dozen or so that are popular and by
00:10popular I simply mean that language is used in a lot of current software, it's
00:16used by large numbers of people, and there is an active community and a
00:20significant job market for that language.
00:23Now as the years go by, different languages wax and wane in popularity.
00:27New languages do come along. Some are big hit but most of them aren't.
00:32So this list changes, but it changes slowly.
00:35Now most programmers will learn and use many languages over the course of their
00:40career. Once you have got the basics down, additional languages do become easier to pick up.
00:45A little later in this course we will dive deeper into the most popular
00:48languages, but if you're new to this, you might think why, why are there so many
00:55languages? If all we're doing is writing simple instructions for computer, why
01:00isn't there just one computer language?
01:03Well actually that language does exist, but it isn't any of these.
01:08You see the CPU, the chip, the central processing unit that is the brain of any
01:14computer, desktop, laptop, server, phone, game console, well it doesn't
01:20understand any of these languages.
01:22We might informally say when we are programming that we're writing code the
01:26computer understands, but we are not. Not really.
01:30You see the only thing that chip understands his called machine code or machine language.
01:36Now these are the real instructions that run directly on your computer hardware.
01:41So the question is why don't we just write machine code?
01:45Well because it's almost impossible to do.
01:48It's numerical operations, tiny instructions that work on the smallest pieces of
01:53memory inside your computer and even if you could write it, it's basically
01:58unreadable by anybody else.
02:00This is for the machine.
02:02It's not for a human being.
02:04And because machine code works of the level of the CPU, it would be different
02:09machine code for different models of CPU.
02:12Writing a full program in machine code would be like digging a tunnel through a
02:17mountain with only teaspoons.
02:19It's theoretically possible, but it would take you so long and so tedious that
02:23you wouldn't even try.
02:25So all of these languages, the popular ones and the others, are in fact a
02:30compromise. They are invented languages.
02:33They are just trying to bridge the gap between us as human beings and
02:37the computer hardware.
02:39Now, some of the languages are actually quite close to machine code. The closest
02:45is something known as assembly language.
02:47In general the closer a language is to machine code the more difficult it is to
02:53write and the more you have to know about the actual hardware. And this what's
02:57called a low-level language.
02:59Now as you move away from the CPU into what are called higher-level languages
03:04you worry less about the hardware.
03:07Now this code is often easier to write and to share even across different
03:11platforms, but it can be slower when running because these languages aren't
03:17necessarily optimized directly down to the CPU level.
03:21Having said that, these days speed differences are minimal and we will be
03:26focusing on the high-level languages in this course. But whatever we write has
03:32to be converted down to machine code before it can run.
03:36So while this machine code piece seems like the most important piece, we are not
03:41really interested in machine code.
03:43Sure we do need to know that that's what runs, but programming for us is all
03:49about the source code.
03:51That's what we call the statements we write, Java, C++, Ruby, Python whenever.
03:57We write the source code that will at some point be translated then into machine
04:02code, so it can run on the computer.
04:05When I say I'm writing code, it's source code, and when I say programming or I am
04:10coding, I mean the same thing.
04:12So to start writing any of these programming languages, writing these
04:17statements, writing our source code, we need to understand three things: 1) how
04:23to write it, literally where do we actually start typing this, 2) to understand
04:29how that source code will be converted to machine code, and 3) how do he
04:35actually run it, how do we execute our program?
04:39And some of this does depend on the language that we pick, but let's begin with
04:44how to actually start writing these statements.
Collapse this transcript
Writing source code
00:00Programming language source code is written in plain text.
00:04You can open up a simple text editor that comes with your operating system like
00:08Notepad on the PC or TextEdit on the Mac, and they work just fine to write any
00:13programming language.
00:15There's nothing magical about source code itself.
00:18It's just text. And that's plain text, not rich text.
00:22So here for example is a text editor with some JavaScript in it and here is one
00:27with some Perl and here is one with some Ruby and here is one with some Groovy.
00:32And yes, Groovy is a language.
00:33Now right now don't worry at all about trying to memorize any of these.
00:38That comes later. Just observe them.
00:40It's common to see different file extensions being used like .js for
00:45JavaScript and .groovy for Groovy files but they are no different from .txt
00:50regular text files.
00:52But what you don't want is a word processor.
00:55If you're writing code in a program where you see a formatting bar with bold and
01:00italic options, you are probably in the wrong place.
01:03Programming language source code does not need to be bolded or underlined or
01:08italicized or justified.
01:10So say if you're using a program like TextEdit on a Mac that can work in the
01:14either rich text or plain text modes, you want Plain Text.
01:19Now programs don't actually have to be much more than this. In fact these
01:24would all be considered very simple but technically complete programs in these languages.
01:30Just one statement, one instruction that outputs the words Hello, world on to the screen.
01:37Now Hello, world is the classic example of this simplest program imaginable in any language.
01:43So let me show you a few more.
01:45So this is a one statement program written in a language called ALGOL 68 and by
01:5268 here I mean 1968 which is when this language was released.
01:58ALGOL 68 is not a language you're ever going to need to know, but on the other
02:02hand you might want to know Python.
02:05So this is a one statement program written in Python 3 released in December
02:122008, and this is a one statement program written in a language called Lua.
02:18Yes, this particular statement is the same in all of them and in a few
02:23more languages besides.
02:25You see many languages share a common history and they are often more alike
02:29than they are different.
02:31Now just because this statement is the same in these languages does not mean
02:35these languages are identical. Far from it, but there are often significant
02:40similarities between languages.
02:43Now, some languages do need a little more than one single statement to be
02:47considered a full program.
02:49Many languages like to be given explicit starting and ending points.
02:53An older version of ALGOL, ALGOL 60, was written in all caps and actually
02:59required the words BEGIN an END to mark out your program.
03:03Languages like C and other languages based on C like C#, C++ and Java, they
03:11require what can first seem like intimidating amounts of curly braces and
03:16weird esoteric keywords just to get something simple to happen like the words, Hello, world!
03:22Now you might think, okay so am I supposed to remember all of this to write just
03:27the simplest program?
03:28Well, no, not really.
03:31You see just because you can work in a plain text editor and it is useful from
03:35time to time, doesn't mean you have to and you probably won't want to.
03:40Because with a basic text editor you're completely on your own writing the stuff
03:44and there are other applications that can actually help you write this code and
03:48make your life easier.
03:50First we have programmer's text editors.
03:53These are plain text editors with some extra features added on and there are
03:58many of them available on every platform.
04:01Some are free and some are commercial.
04:03Typical features of these involved simple things like line numbers, more
04:07powerful Find and Replace.
04:09They often have color-coding.
04:12This is not the same as formatting.
04:14Color coding happens automatically and it helps you read and recognize different
04:19parts of the language.
04:20They often have syntax checking, kind of like spell checking in a word processor.
04:25Syntax checking will let you know if it finds something wrong with your code as
04:29you're actually typing it.
04:30Some of these text editors are oriented towards a particular language, say just
04:35Java, and some others might have support for several dozen languages.
04:39Now if you do any web development you might find that your chosen web
04:43development application is also a usable programmer's text editor.
04:47And then we have Integrated Development Environments or IDEs.
04:52These are large programs and include a good programmer's text editor, but
04:57usually add on a whole bunch of features for professional development.
05:01Examples of IDEs would be Apple's Xcode on the Mac or Microsoft's Visual Studio
05:07or Eclipse, which is a cross-platform.
05:09Now in this course we are not going to worry about IDEs. You'll get into those
05:13when you start concentrating on a particular area of development.
05:17So while you don't need a special program to write your code you'll probably
05:22end up wanting one.
05:23However, once we start to write this code we then need to understand how it will
05:28be turned into machine code so it can run on the computer itself.
Collapse this transcript
Compiled and interpreted languages
00:00So we need to get our source code converted into machine code somehow before it
00:05can run and there are two main ways of doing this: what's called compiling the
00:10source code and what's called interpreting the source code.
00:14Now luckily, this is not a big decision you have to worry about.
00:17Most languages you'll deal with will naturally fall into one or the other, but
00:22it is worth knowing the difference.
00:23So let's have a simple scenario.
00:25Let's say it's just you and me. You have your computer and I have my computer
00:31and you're going to write a program that you want me to run.
00:35Now, with a compiled language, what happens is you write your source code and
00:39then you have a program called a compiler that will go through that source code
00:43and create a separate file that contains the machine code, and you just give me that file.
00:49This end result is sometimes referred to as an executable or an executable file
00:54because I can directly execute it.
00:56I can now just run your program.
00:58You keep your source code and I never see it.
01:02Now, with an interpreted language on the other hand, you don't compile your
01:06source code beforehand. You just give me a copy of it.
01:09So I'll need my machine to interpret it whenever I want to run your program.
01:15Now, interpreter is different to a compiler.
01:18It does this on-the-fly.
01:19We can think of it as going through your source code line by line and
01:23processing it on the spot.
01:24It does not save it as a separate machine code file.
01:28Now, you've used interpreted languages even if you don't know it.
01:32Whenever you've looked at a webpage with JavaScript, which if you've surfed
01:35the web for more than two minutes in your lifetime you have, this is what's been happening.
01:40The JavaScript has been sent to you over the web along with a bunch of other
01:44files like webpages and images and it's been sent as source code onto your
01:49machine, and your web browser has just interpreted that JavaScript so it can run that code.
01:55So which one is best?
01:56Well, they both have their good and their bad points.
01:59Benefits of compiled code.
02:01Once it's compiled, it's immediately ready to run and you could send it to 100
02:05or 1,000 or 100,000 different people. It's ready to go.
02:09It can be optimized for a CPU, so it can actually be faster and you don't have
02:14to send your source code to everybody, which might be a good thing.
02:18However, the downsides are if I compile it on a PC, that executable file
02:23won't work on a Mac.
02:25In fact, it often needs to be compiled separately for different kinds of CPU
02:29even on the same platform, and when you're writing code to compile is an extra
02:34step that you have to take every time you want to test your program.
02:38Now, with interpreted code, the big benefits are I don't really care what kind
02:42of machine is on the other end, because we don't provide machine code.
02:46We just send the source code and we let the other side take care of it.
02:50So it can be more portable and more flexible across platforms.
02:54It's also a little easier when testing because you just write your source code
02:58and then run it, letting the interpreter take care of converting it.
03:01There is no in-between compile step.
03:05It can be easier to debug when things go wrong because you always have access to
03:09all the source code.
03:10However, it has its down sides too, because everyone who needs to run that
03:14program on their machine has to have an interpreter for that language on their machine.
03:19It also can be slower because you have to interpret it every time the program is run,
03:23and the source code is effectively public because you're sending it to
03:27everyone who needs to run that program.
03:29Now, because there are good things about compiled languages and good things
03:34about interpreted languages, there is also a third way of doing this which is a bit of both.
03:39Instead of the compiled model where all the work is done upfront but can be a
03:44little bit inflexible or the interpreted model where all the work is done on the
03:49receiving end but can be a little bit slower, we kind of do half-and-half.
03:55Upfront, we compile it part of the way to what's called an intermediate
04:00language, which takes it as far along the way to machine code as it can get
04:04while still being portable often across platforms.
04:07You then distribute this, sending it to the people who need to run it, and
04:12each person who runs it takes it the last step to take it to machine code on their computers.
04:17This is sometimes referred to as Just-In-Time or JIT compilation.
04:21Now, this intermediate language sometimes also goes by the name of bytecode.
04:26So this process has to happen somehow.
04:29It's just how much of it happens on your machine and how much of it happens on mine.
04:34Now, while theoretically all computer languages could use any of these methods,
04:40the normal usage of any one language tends to be one or the other.
04:44So for example, C, C++, and Objective-C, these are typically found as compiled
04:50languages, so you need a compiler.
04:52Now the compiler can be downloaded for free but they're often built into
04:56integrated development environment applications.
04:59Now, languages like PHP and JavaScript and indeed most languages with the word
05:04script at the end are usually interpreted, and languages like Java, C#, VB.NET,
05:11and Python use this intermediate hybrid approach.
05:15Now, whether a language is compiled or interpreted or somewhere in-between is
05:20rarely a reason by itself to choose a language, but it can be something that
05:24you take into account.
05:25If one main priority of your program is absolute maximum speed running on one
05:31single platform, you'll probably look at a compiled language.
05:35If you're more interested in easily moving your code across multiple platforms,
05:39you're probably more interested in an interpreted one.
05:42But more usually, you're driven more by what you need to do.
05:46You need to build iPhone apps or Windows desktop apps or dynamic website,
05:50or, in our case, just learn the fundamentals of programming, and you let that
05:55decision drive the language choice and the language choice will determine
05:59whether you are compiled, interpreted, or somewhere in the middle.
Collapse this transcript
2. Core Programming Syntax
Why JavaScript?
00:00When we were putting this course together, we decided we didn't want to be
00:05conceptual, we wanted to get hands on, and we talked a lot about what would be a
00:09good language to do this with.
00:11We wanted a language that was friendly for beginners but not just a
00:14beginner's language.
00:16It needed to be real.
00:17It needed to be popular and it needed to be relevant.
00:20Overall it needs to be a language that was good to explain these concepts.
00:24Now there are a lot of languages that fit the bill here, but very importantly we
00:28also wanted one that you could get started with without installing anything on
00:34any platform and that narrows the list down quite a bit.
00:38So we decided to go with JavaScript.
00:40It's not the most powerful or the most flexible language out there, but it's
00:44certainly popular and it's certainly relevant, and it's a great language for
00:48exploring these concepts.
00:50So even if you had some other language in mind, JavaScript is a very
00:54practical language to know.
00:56But JavaScript is a language that works with and manipulates web pages.
01:00It was invented for that reason.
01:03And that does mean that JavaScript is specialized and intentionally limited.
01:09We wouldn't use JavaScript to write say desktop applications, the way that I
01:14might with C++ or Java or C# or Objective-C.
01:19And despite the name Java and JavaScript are totally different languages and
01:26are not related in any meaningful way.
01:29So programs that I write in these languages would run directly on the operating system.
01:34JavaScript wouldn't.
01:36While JavaScript is a programming language, you'll also here refer to as
01:41a scripting language.
01:43Now this is a description you hear not surprisingly for any language with script
01:47at the end like ActionScript or AppleScript or VBScript.
01:52Scripting languages are more limited programming languages that are embedded
01:56inside another program.
01:58So ActionScript for example is the programming language that we use inside Flash.
02:04VBScript can be used inside Microsoft Office applications, and similarly
02:10JavaScript also only works inside another application, the web browser.
02:16whether your browser is Internet Explorer or Safari or Firefox or Chrome or
02:22Opera, they all have a JavaScript engine, a JavaScript interpreter inside of them.
02:29Scripting languages in general aren't more limited than these general purpose
02:33programming languages, but they are often easier to pick up and they're very
02:36good at what they do.
02:39So JavaScript like most scripting languages is an interpreted language.
02:44We do not have to manually compile it to machine code.
02:47That will automatically be done by the web browser when we try and run our JavaScript.
02:53So the operating system runs the web browser and the web browser runs our JavaScript.
02:58JavaScript very importantly is a case-sensitive language.
03:03For those of you new to programming I can't get over how important that it is.
03:07Let me show you two example lines of JavaScript here.
03:10Now don't worry right now about what they do, but just know that one of these is
03:14right and one of these is wrong.
03:17What we actually have here is one is using the word Id with a lowercase d and
03:22the other has an uppercase D.
03:25This is the level of case sensitivity that we have to be aware of in any
03:29language that is case sensitive and most of them are.
03:33Even if you have a language that isn't, you probably want to make a habit of
03:36paying very close attention to it, because one of these would work and one of
03:41these wouldn't. So here is some JavaScript.
03:45This is what it looks like in general.
03:47Again, don't worry right now about what this is doing.
03:49But when we see any programming language with a lot of these curly braces being
03:55used, when we see statements that all seem to end in a semicolon, and a few
04:00of the other things we'll be exploring shortly about this,
04:03this is a clue that this language is influenced by the C programming language.
04:09C has been around since the early 70s and shapes the look of many of the most
04:13popular languages today. Some even share the name C++, C#, Objective-C ,and some don't.
04:21Java is a C style language, as is ActionScript, as is JavaScript.
04:26And knowing a C style language makes it easier to jump into any of these other languages.
04:31So JavaScript is a C-based interpreted case-sensitive language.
04:37It's highly relevant and it's pretty friendly for beginners.
04:40So let's see how to create our first program in JavaScript.
Collapse this transcript
Creating your first program in JavaScript
00:00So let's get hands-on with JavaScript.
00:03Well, we know it's an interpreted scripting language, and that is going to make
00:07it easier to experiment with because we don't have to have a compiler and we
00:11don't have to worry about creating files full of machine code.
00:14But on the other hand, we can't just write some JavaScript and have it
00:19magically run by itself.
00:20We're going to create our program that will run inside another program.
00:25It's not unusual to have multiple levels of this in programming.
00:29Think about it this way.
00:30We already have our computer and that computer is going to be running an
00:35operating system inside of it.
00:37Within the operating system, we're going to be opening up and running a web browser.
00:42The web browser itself is going to open up and run a webpage, and that webpage
00:47itself is going to open up and interpret some JavaScript.
00:51Now, if this seems like just too many levels deep, realize we always have most
00:57of this going on anyway.
00:58And we already have the computer, we already have the operating system,
01:01we already have the web browser.
01:04What we need to do is create the last two pieces.
01:07We need to create the webpage that will open up in the web browser and the
01:12webpage will be the container that's going to take care of interpreting and
01:16running the JavaScript that we're going to write.
01:19So the first thing that we need to do is have a webpage.
01:23Now, we don't need to worry here about websites or web servers or graphics or
01:29any other files. We just need a single simple webpage.
01:33An HTML file whose only reason for existence is so we can point it to our
01:38JavaScript and say "go and do this."
01:42I have a folder here with two files in it:
01:45an HTML webpage and a file that will contain my JavaScript.
01:49If you've done any web design in the past, you may find the next minute or two
01:53to be a bit of a do-over, but feel free to tag along.
01:56So this first file I've called container.html.
02:00It doesn't matter what the first part of the name is, but we're using the .html
02:04file extension just so when we double- click it, it will open up in the default
02:09web browser, whether that's Firefox, Safari, Internet Explorer, or anything else.
02:14As I can see here, it's a very simple HTML page indeed.
02:17I also have a file in this folder called script.js.
02:22The name of this file is not actually important.
02:25As we've seen, it is just a text file, but I tend to keep my file names short,
02:29or lowercase, and give them a .JS extension for JavaScript.
02:34This file is empty as I'll show you in a moment.
02:36Now, just a side note here, some operating systems can be configured to hide
02:41the file extension from you and that can be a pain when you're creating files
02:45like this, because you think you're making a file with a name like script.js,
02:50but your system might be really saving it as script.js.txt which could mess things up.
02:56However, we're good here and I'm going to open up this HTML file first in a
03:01text editor to view the HTML.
03:03So instead of double-clicking on it, which would open up in the browser, I'm on
03:07a Mac, so I'm going to right-click or Ctrl+Click and choose to open it with
03:11TextEdit. On a Windows PC, I would right-click and Open With > Notepad.
03:15Of course, if you have a favorite text editor or a web design application,
03:20feel free to use that.
03:22The only reason I'm doing it this way is just to show that we don't actually
03:25need any special software at all to do this.
03:28Now, I want to see the behind-the- scenes view of our simple webpage file, which
03:33means I actually expect to see multiple lines and lots of angle brackets here.
03:38The reason I'm still seeing something that looks like the web browser itself
03:41is because TextEdit on the Mac has a preference to open in rich text or in HTML edit mode.
03:47So I'm going to go into the preferences of that and turn that off.
03:50I just want plain text.
03:52That's all I want to see.
03:53So jumping into preferences, I'm going to first say I want all my documents to
03:57open in plain text, and just to make things a bit more readable, I'm going to
04:02say that I want my plain text font to be Monaco, let's say 14 points, close that,
04:10and then also on the second section, I'm going to check the box to say Ignore
04:14rich text commands in HTML files. Close that.
04:18I need to close that file and just reopen it again in TextEdit and this is
04:24what I want to see.
04:26The behind-the-scenes view of this webpage file.
04:29Now, if you're brand-new to all of this, you might wonder if you're looking at a
04:33programming language here.
04:34Well, no, this is a very different kind of code.
04:37HTML is not a programming language.
04:40It's a markup language.
04:41In fact, that's what it stands for.
04:43Hypertext Markup Language.
04:45Now, that might sound like nitpicky hairsplitting from me, but there is a
04:49really big difference.
04:50HTML describes a webpage, its structure, what is its title, what are the
04:55headings, what are the paragraphs in this document.
04:58It is not a program.
05:00It is not a process. This is not a programming language.
05:04But we have enough to do in this course without getting into HTML.
05:07So I'll show you the reason we came into this file at all.
05:10The important piece is this line here. This is how we point from this HTML file,
05:16this webpage, to the only thing we're really interested in here: the JavaScript
05:21file called script.js.
05:23Now, because we're just using just the name of the file, it will need to be
05:29inside the same folder that our HTML page is in, but that's what I have. So we're good.
05:33I can close down this HTML page.
05:36I don't need to do anything with it. I'm actually going to close it down in the browser too.
05:41script.js is the file I am interested in.
05:44I'm going to open that up in the TextEdit editor and I'm going to add one
05:49statement, the classic first program in any programming language.
05:54The word alert written all lowercase and the opening parentheses, a
05:59double-quote, the words Hello World, closing double-quote, close parentheses, and a semicolon.
06:08This is one JavaScript instruction, one JavaScript statement.
06:12So to run this source code, we first need to save this file. And I'm going to
06:18close it, we don't need it anymore, and then I'm going to open up the webpage
06:22in the web browser.
06:24The web browser loads the webpage.
06:26The webpage HTML file points to our JavaScript.
06:29It loads it in, and it interprets it and it runs it, and this is what it does.
06:34Pops up the really annoying JavaScript alert box.
06:37Now, other browsers might show this window slightly differently, but the
06:40effect is the same.
06:42Yes, this is a little boring, a little simple, and the alert box is after all one
06:46of the more annoying things that JavaScript can do.
06:49But this is where we begin and now we need to see how to add some more.
Collapse this transcript
Requesting input
00:00Computer programs are all about input and output.
00:04From the earliest programs where you might feed a stack of punch cards in one
00:08end to get a printout on the other end, where these days the input might be
00:12click the button, or move the mouse or even wave your hand in the air, and the
00:16output could be change what's displayed on the screen, or cause the game
00:21controller to vibrate.
00:22The different languages favor different kinds of input and output.
00:26JavaScript is all about the webpage.
00:29It doesn't read files on your hard drive.
00:31It doesn't talk directly to your printer.
00:33It's interested primarily in what's on the webpage and what you might interact
00:38with on the webpage.
00:39Now we've already got some output going on.
00:42We've got an alert box.
00:43That might not be impressive output, but it is output.
00:47It's our computer program causing something to happen on the screen, so let's
00:52get something into our program.
00:54So I have a folder with two files in it.
00:57It's the same setup as last time. In fact, it's an identical container.html file
01:02that is only there to point to script.js, a JavaScript file which I'm going to
01:08Open up in my text editor and as you can see is currently empty.
01:12I'm going to add two lines here, two JavaScript statements, and then explain
01:16what they are doing.
01:18So the first line, var name = prompt, all of this written in lowercase, open
01:24parentheses, open double quotes, the phrase, What is your name, question mark,
01:28close double quote, close parentheses, semicolon, and then on the next line
01:34alert and inside the parentheses we have "Hello, " then a plus sign, and
01:41then the word name and of course we're closing both of these lines with the semicolon.
01:46I'm going to just save this JavaScript, and because the container.html page
01:51is already pointing to it if I double- click that HTML page to open up in the
01:56web browser we should immediately load in and run that JavaScript, and indeed
02:01what we get is a prompt.
02:03Depending on the browser this may look a little different, but it should be
02:06asking, What is your name?,
02:07and giving a place to type in and I'll say it's Simon. Click OK and then I get
02:11the message Hello, Simon.
02:13Now because I'm using a fairly recent version of Firefox it's also detecting
02:17that this page is popped up two alert boxes and it's asking me, do I want to
02:21prevent this page from doing that? Well, no I don't.
02:24That's fine.
02:25It's all I was expecting to do right now.
02:27Again, very simple code, but what's it actually doing here?
02:31Well we have two JavaScript statements, but the first statement is doing two things.
02:36It's using the JavaScript prompt command to ask for a name and then it's going
02:41to store that name in a variable.
02:44This is a container, a bucket that can hold some data, and that's simply so we
02:48can use it on the next line.
02:49And if we don't tell our program some way of remembering it we won't have anyway
02:54to use it on the next line.
02:55Now usually our code will just start at line 1 and move through all the
03:00different statements as quickly as possible, but what's actually happening is
03:04when we call prompt in JavaScript, it's not just What is your name?
03:09It's What is your name? and wait for our response.
03:12So we've actually paused at this line while somebody types in an answer into
03:17this dialog box that's popped open.
03:19And only when somebody type something in and clicks OK, do we actually come back.
03:25What's happening is the value that they typed will be stored in a
03:29variable called name.
03:31Now whether that was five seconds later or five minutes later, we have paused to
03:35that point and then we run the next line of code.
03:39And that's going to combine the Hello, space, with whatever they typed in using
03:45this plus sign to combine these two parts of the message, and then pop-up
03:49another dialog box.
03:52If I open up this webpage to load it again, there is nothing to actually ensure
03:56that somebody types a name here.
03:58I could type in a number and click OK and it will just combine that message.
04:03It could have been a number.
04:04It could have been a sentence.
04:05It could have been nothing at all.
04:07If I want to run that code again, I could either close and reopen it or I could
04:11click the button in the browser to reload the current page and we'll effectively
04:15run the script again.
04:16I could even leave that completely blank and click OK.
04:19Now here it doesn't matter, but if our program, if our code, was expecting
04:25something very specific to work with like a birth date or an amount or an
04:29email address, the wrong kind of input could cause it to crash.
04:33Because again programs are all about input and output. There is an old phrase
04:38called G-I-G-O, GIGO for Garbage In, Garbage Out, whatever you're asking for,
04:44and whatever you get better make sense.
04:46Later on we'll see how to do some checking on our input.
Collapse this transcript
3. Variables and Data Types
Introduction to variables and data types
00:00As soon as we write even the simplest program in any programming language, we
00:05have to keep track of pieces of information.
00:08If we are building a loan calculator, we need to keep track of the amount of the
00:12loan, the number of months, the interest rate.
00:14If we are writing a game program, we might need to know the current score, the
00:19position of the player on the screen, how many lives do we have left, what
00:22image do we use for our player. This is all data and we create variables to hold that data.
00:30Variables are simply containers.
00:33What we're doing is going out to the computer memory and grabbing a little piece
00:38of it, giving it a name to use while our program is running.
00:42We grab this space and we name it and then we put a value in it, like an
00:47email address or a date or a position or a number, and then we can change
00:52that value as we need to.
00:54Variables can vary, hence the name.
00:57So in JavaScript you create a variable like this.
01:02The word var written all lowercase, which is part of the JavaScript language, and
01:07then we name the variable.
01:08The name of the variable is up to us and it should represent the piece of data
01:12that we want to hold.
01:14So a variable called year, or one called customerEmail, or todaysDate, or
01:19while we are experimenting, just nonsense words like foo or even a single letter like x.
01:24Now the name that you use for your variable must be written as one word,
01:29there are no spaces allowed, and it can be made of letters, numbers,
01:35the dollar sign and the underscore.
01:37No other characters are allowed but you can't actually start with a number.
01:42So this variable name for example would not work, but reversing them so the
01:48number's at the end, that would work, and we will talk more about naming our
01:52variables later on when we talk about style guidelines, but I am just going to
01:56use simple names for now.
01:59All we are doing when we create a variable is carving out a little area of
02:04memory to hold a value.
02:06Right now after this line of code runs, this variable exists.
02:11It has a name, year, but it doesn't have a value.
02:14This is regarded as undefined and undefined has a special meaning in
02:19JavaScript. But there is no point to having a variable that stays undefined.
02:25So we can define or set the initial value of the variable when we create it.
02:31We could do that as two statements.
02:33I say var year, then year = 2011, and that puts the value in the variable.
02:39Now very important. The = sign here is setting the variable to the value 2011.
02:47It is not a polite description. It is a command.
02:50Put the value 2011 in the variable called year.
02:55You can also combine these into one statement,
02:59to both define and create the variable and to set its value.
03:03Now here is a place where JavaScript will let you be sloppy. I won't.
03:09Now technically the word var is not even required.
03:13In JavaScript if you just write a line of code like this without var, JavaScript
03:18will go looking for an existing variable called year to put this value in, but
03:22if it doesn't find it, it will just make it.
03:27However, we are always going to use the word var when defining our variables.
03:31There are couple of situations where leaving var off can lead to unexpected
03:36behavior, so make a habit of always using it in your JavaScript.
03:39Now once again JavaScript is case sensitive.
03:43That means if I create a variable called x with a lowercase x, that's one.
03:48If I use the word uppercase X, that's two.
03:51These are two different variables.
03:53This second line here might have been an accident.
03:56Maybe I meant to say lowercase x, but because of the automatic creation of
04:00variables without the word var, you would now have two different variables and
04:07nothing in JavaScript would actually give you an error on this.
04:11So be careful when you're naming your variables.
04:13Now if you are creating multiple variables at the same time, you can of course
04:19do them on multiple lines like this but you can actually combine them on to one
04:24line, separating the variable names with commas.
04:27It's just a shorthand way of doing this. And similar to that if you're actually
04:32creating multiple variables and giving them all initial values you can still
04:38combine them on to one line.
04:40This makes it a little easier to read, a little shorter to write.
04:43Now in JavaScript, once you've actually created a variable you can put anything in it.
04:49Numbers, text, dates, it could start with a number, then put some text, then put
04:54a date in it, and that might not sound unusual, but a lot of other languages
04:58don't let you do that.
04:59Creating a variable in many languages does not just mean defining a container
05:04but also saying what type of container it is and what it can hold, and while
05:09that's not essential in JavaScript, it's really useful to know.
05:13So we are going to take a quick look at that idea.
Collapse this transcript
Understanding strong, weak, and duck-typed languages
00:00In many programming languages when you create a variable, you don't just give it
00:05a name but you must also say exactly what type of information is going to be
00:10stored in that variable.
00:11You must decide beforehand if it's going to store an integer, meaning a whole
00:16number without anything after the decimal point, or perhaps a floating-point
00:20number which might have a value after the decimal point or perhaps you need to
00:23store a single character, just one letter, or perhaps multiple characters, what's
00:29called a string, or is it a Boolean value, and that just means a value that can
00:33only be true or false, or it could be even more complex type of data, but you
00:38have to choose that data type.
00:41And once you have chosen it you are not allowed to change it, and that's what's
00:44known as a strongly typed language.
00:47You can create as many variables as you want but each variable must be of one
00:52particular type and that's actually enforced and it can cause your program to
00:56crash if you try to put the wrong type in a variable that wasn't designed for it,
01:00but in JavaScript we don't do that.
01:03JavaScript is what's called a weakly-typed language.
01:07We don't make a variable that's only for integers or a variable only for strings.
01:11We just create a generic variable, an empty container, and then we can simply put
01:16whatever type of value we want in it.
01:19Now if I create this variable without giving it a value, it starts off as what
01:23JavaScript calls undefined.
01:26However, then I can use the name of the variable and the equal sign, or more formally
01:30the assignment operator, to set the value of myVariable = 200.
01:33Now if I wanted to, right after this I could use the same format and set it
01:40equal to a string. That just means one more characters strung together.
01:44Now we need to use the double quotes here to say where the string begins and where it ends.
01:49Inside those double quotes it can contain spaces and special characters.
01:54Now in JavaScript you can use either double or single quotes to mark the start
01:58and end of a string. But don't mix them. Don't start with a single quote and
02:02close with a double quote.
02:03Now I tend to use double quotes because that's more common in other languages
02:08but you will see both ways.
02:10And we can also store what are called Boolean values.
02:13Boolean just means a value that's either true or false.
02:16We can use the word true or the word false and written this way,
02:19they do not need the quotes around them.
02:22JavaScript understands the word true and false written all lowercase. They are
02:27considered part of the language.
02:28So we can create a variable as undefined, then put a number in it, then put a
02:33string in it, then a Boolean.
02:34Now that doesn't mean JavaScript doesn't care about the type of data you have.
02:39It does. It treats numbers differently from strings and strings differently
02:42from Boolean values.
02:44But any JavaScript variable can hold any of these values and even more
02:48complex ones besides, like arrays and objects and functions, but we'll get into those later on.
02:54Now you might think, well it sounds much easier to be a weakly-typed language
02:58where you can put anything anywhere.
03:00One issue with a weakly-typed language like this is there is no guarantee that
03:04the variable you think you have contains the right kind of data.
03:08Most of the time when you're programming, you won't need or want to change the
03:12type of data that a variable stores.
03:14If you have a variable that you've called high score, well you would expect it to
03:19have a number in it, not the word pomegranate or the value true.
03:23If you have a variable called firstName you don't want it to contain the value
03:27of 74.5. And there is nothing that would prevent that in JavaScript, but in other
03:32languages strong typing can have an advantage by providing internal rules that
03:37stop a lot of common errors from happening.
03:40Now of course, the point of making any variable is that we are going to use them,
03:44we are going to manipulate them, to ask questions of them, but that all
03:48begins by knowing how to make them.
Collapse this transcript
Working with numbers
00:01So anytime we're working with variables, we really have two things.
00:04We have the variable, the container, the bucket, and we have the different
00:08values that we're going to put in it from moment to moment.
00:11Now, the most common kind of values in computer programs are numeric values,
00:15numbers, and really this is no surprise.
00:18Sure, these days, when we use the word computer, we think of a machine.
00:23But for hundreds of years, computer was a job.
00:26In the 17th, 18th, 19th centuries, you could be employed as a computer.
00:31It just meant a person who computes, someone who does calculations.
00:35Then these machines come along and they do it far better than the person ever could.
00:39These days we think a computer means hardware.
00:42But the reason they were invented was always about number crunching.
00:44But we need to be comfortable with our use of numbers.
00:48When we're writing programs, we're dealing with bank balances and dollars and
00:52cents, the position of a spaceship on the screen, the height and width of a web
00:57browser window, the coordinates of a device using geolocation, the amount of
01:01milliseconds we've been playing an MP3 song, even colors are represented with
01:06numeric ranges of red, green, and blue. All numbers.
01:10Now, unlike many programming languages you'll come across, where you need to be
01:14very conscious of what type of number you have--
01:17integer, floating-point, positive, negative, is it a big number, is it a small number--
01:23JavaScript instead has a very human approach to numbers.
01:27They're all just considered numbers.
01:29So let's see how to work with them.
01:31So I have an empty file here set up to write some JavaScript in.
01:36Let's start off this way, var a. Now, this statement tells JavaScript create a
01:42variable and call it a. When this line of code is executed, the value of this
01:47variable is undefined.
01:49So on the next statement, I will set that variable to the number 5.
01:54Now, when you're brand-new to programming, lines like a = 5 and b = 10 can look
02:01a little weird, particularly if the last time you saw anything like this was
02:05equations in school.
02:06But remember, when you see the equals sign here, this is not a polite
02:11description. This is a command.
02:13This is an instruction.
02:15This is saying take the value 5 and put it in the variable called a.
02:20I don't care what a was before, but after this line of code is executed,
02:24it will have the value 5.
02:26This is what the equals sign does.
02:30It assigns a value.
02:32That's why it's formally called the assignment operator.
02:35Now, notice that there are no quotes around the number 5.
02:39The number 5 here is referred to as a numeric literal.
02:42It represents the fixed value 5.
02:45The variable part of this line can change as our program runs, but the literal does not.
02:505 always means 5.
02:54What if we want to change this?
02:55What if we want a million?
02:57Well, I'll just say a = 1000000.
03:00We don't use commas in it. We just use the number itself.
03:05While in other programming languages we have to be very conscious if values are
03:09integers, meaning whole numbers, JavaScript doesn't care.
03:12If we want something after the decimal point, we just type that in.
03:17Numbers are regarded as positive by default, but they can be negative as well.
03:22If I want to make a negative number, I just put a minus sign in front of it. In this case -500.
03:29So we have five statements so far.
03:31I'm going to add a sixth.
03:32I'm going to use alert again, and in parentheses, just put a. Now, notice that
03:38I'm not using quotes here.
03:40I don't want to write out the letter a as an alert dialog box. I want to write
03:45out the value of the variable a, which is what this is going to do.
03:48So I'm going to save this and I already have a folder set up where I can just
03:53run this JavaScript by opening the HTML page.
03:57So I open that up and we get one dialog box with -500 in it.
04:02That's what we should expect.
04:04What's happening is we're opening up, our program runs, our code runs, we create
04:09the variable, we change it to 5, we change it to 1000000, we change it to
04:14123.654, we change it to -500, and then we write it out.
04:20Simple instructions created and executed one after the other.
04:24But this is how we can start to work with number variables in JavaScript.
04:30Now, as one final note, understand there's a very big difference between
04:34creating a variable like this, var b = 123, and creating a variable like this,
04:41var c =. Similar looking value, but inside quotes.
04:46Well, the first one here, var b, is a number 123.
04:51The second one, var c, is a string.
04:54Not the number 123, but the digits 1, 2, 3 and sometimes that's a pretty big
05:00difference in behavior.
05:01So let's talk about strings next.
Collapse this transcript
Using characters and strings
00:00When we want to deal with text in our programs,
00:03characters, words, sentences, email addresses, we use the term strings to
00:08describe those kind of values. Now we've seen these already.
00:12Anytime you see words contained in sets of quotes, we're dealing with strings.
00:17The first line of code that we wrote was this alert message that used the
00:21string "Hello, world".
00:23This value contained in the double- quotes is referred to as a string literal,
00:27just like the number 5 or the number 1,000,000 would be a numeric literal.
00:31We can of course use this format to create variables.
00:35I could create a new variable called message and set it equal to the
00:38words "Hello, world".
00:39I could then use that variable and pop out another alert box.
00:44So we are using the string literal to create the variable called message and
00:48then writing that variable out.
00:50Now, notice that I'm not using double- quotes around message in this second alert
00:55statement because I don't want to write out the word message.
00:59I want to write out the value of the variable called message.
01:02Now, when we are creating strings, you can use double-quotes to surround the
01:08text or the sentence.
01:10You can also use single quotes.
01:11What you can't do is mix the two.
01:15You can't for example open with a single quote and close with a double quote.
01:19Most other programming languages restrict you to just double quotes.
01:23So I tend to use that in JavaScript to just to make it easier to go from
01:27language to language.
01:28One of the reasons you might change between the two formats is if you need to
01:32have quotes inside quotes.
01:35Let me show you what I mean.
01:36Let's say for example we want the phrase Don't mix your quotes contained inside a string.
01:41Well, if we used single-quotes to mark out the start and the end of the string
01:46we're going to have a problem, because there's also a single quote in the
01:49middle of it, and that's how we're telling JavaScript where the string begins and where it ends.
01:54So what I could do here is use double-quotes with a single-quote
01:58contained inside them.
02:00That would be perfectly fine.
02:02However, that gets a little tougher when we have a more complex sentence.
02:07Let's say for example we want a phrase that contains both double quotes and single quotes.
02:11Well, there is no simple way to mark out the beginning and the end of this
02:17without doing something else here.
02:18If this is what we need, what we can do is what's called escaping the quotes.
02:23This would be the way that I'd have to write it.
02:26The entire string begins and ends with double quotes and that means if I want
02:31double quotes inside that string, I mark them by putting a backslash before the
02:37double quotes being used inside the body of the string itself.
02:40Now, one of the great benefits of dealing with strings in most programming
02:45languages is they are smart.
02:47These variables go beyond just having a holding place for some characters.
02:52We can ask things of them.
02:54We'll get into this a lot later, but just to give you a basic example,
02:57let's say I create a new variable called phrase and set it to the
03:01words "This is a simple phrase."
03:03Well, one of the things I can do is I can use the name of that variable to
03:08access or get to information about it, such as how long is it.
03:13I can also ask questions of it, like does another word exist inside it?
03:18I can convert it to upper or lowercase.
03:21As the most straightforward example here, I am going to write the line alert and
03:26then instead of just the name phrase, I am going to say phrase.length.
03:32This is allowing me to get to what is called the length property of this
03:35variable, and what's going to happen is this will pop up an alert box that will
03:40say in this case 24.
03:42We can actually ask questions of our string variables.
03:46As we get deeper into creating and working with any language, you will find this
03:50is very common, but variables by themselves aren't dumb. They can actually give
03:55us more information about the contents and about what they're holding.
03:59Now we'll get deeper into strings a little later on, but that's enough to get us started.
Collapse this transcript
Working with operators
00:00So we've seen that JavaScript has words like alert and prompt that are
00:04causing it to do things to pop up dialog boxes.
00:08But also, it's beginning to be obvious that there are symbols like the equals sign
00:12that are absolutely as meaningful as words are in a programming language,
00:17because this also causes things to happen.
00:19It can take the literal value 500, and cause it to be put in the variable called
00:24Balance and this equals sign, this assignment operator, is one of many operators
00:30in programming languages that will cause things to happen.
00:33Let's explore a few more of these operators by starting off with a few that you
00:38already know how to use.
00:40So the most obvious ones are the arithmetic operators.
00:44We have operators for addition, subtraction, multiplication, and division which
00:49we're using the asterisk for multiplication and the forward slash for division.
00:53We're usually using this in combination with the equals sign as well.
00:57But let's say we create a couple of variables, variable a = 100, variable b, set
01:02it equal to 50, and then we can use the plus sign on the right-hand side of the
01:07assignment operator to perform this operation, to add these two together, and save
01:13the result in a new variable called result.
01:15in this case this would be 150. Or we can change that plus sign for a minus
01:20sign and do subtraction.
01:23And I think you know where I am going with the asterisk for multiplication, or
01:27the forward slash for division.
01:28But what we're doing is evaluating what's on the right-hand side of the
01:33equals sign and assigning that value to what's on the left-hand side of the equals sign.
01:38Now you can use multiple operators together, but JavaScript like any programming
01:44language does have operator precedence.
01:47simply meaning, some of these operator symbols are treated as more
01:50important than others.
01:52So let's say with this simple statement, if you just read this left to right,
01:56you're going to see what's on the right -hand side of the equals sign, and you
01:59are going to say 5+5 is 10, *10 is 100.
02:04But no, the multiplication is regarded as more important.
02:09So the 5*10 is done first which is 50, and then we add 5 to it, and the
02:15result would be 55.
02:17If I want to make sure that I can impose an order on this and I have
02:21multiple operators, I simply take the important pieces and I surround them with parentheses.
02:28So in this one for example, I can make sure that 5+5 will be evaluated by itself
02:35as 10, and then multiply it by 10 and we have 100.
02:40Now, one thing that's very common is to see the same variable name on both
02:44sides of the equals sign.
02:45But remember, what we're looking at is to evaluate whatever is on the right-hand side,
02:50we take that as an expression.
02:52So the first thing we do here is we look at whatever the current value of score
02:56is and then we'll add 10 to it, and then we'll store the result in the variable score.
03:01So if its score is 100, it will now be 110.
03:05This idea to add a value to an existing variable rather than creating a new
03:09variable is so common that there is a shorthand for it which is +=.
03:14score += 10 just simply means take whatever the value of the score variable
03:18is and add 10 to it.
03:20Now, here the + and the = have to be written as one.
03:24There is no space in between them.
03:27This is considered one operator, and the same way there is a +=, we also have
03:32-=, *=, and a /= for subtract a value or multiply a value or divide a value.
03:40Not only that, but it's very common to see something like this.
03:45If we want to just add 1 to an existing variable, well we could write it out
03:50such as a = a + 1 or we have that shorthand a += 1.
03:54But the idea of an increment of just adding 1 to a variable is so common,
04:01it actually has its own shorthand which is ++.
04:05a++ simply means add 1 to the variable a. This idea is where the language
04:11C++ got its name from.
04:13It's the idea of C+1, the next version of C. And the same idea, we can
04:19subtract 1 from a variable by writing it long hand a = a - 1, or saying a -= 1 or just a--.
04:30The ++ is called the increment operator; -- is called the decrement operator.
04:35So as you can see, these symbols have as much of an importance within a
04:39programming language as the words themselves do and we have a few more that
04:43we'll explore as the course goes on, but this will be enough to get us started.
Collapse this transcript
Properly using white space
00:00JavaScript, like virtually all modern programming languages, does not care about
00:05whitespace, and by whitespace I mean spaces, tabs, line breaks. These are all
00:12regarded as insignificant, they are ignored.
00:15So if I have a file of JavaScript here with multiple statements in it,
00:19it doesn't matter if I start putting line breaks in between the lines whether at the
00:24start or the end or in the middle.
00:26This has no impact on behavior whatsoever.
00:29In the same way I've been starting every statement on the first character, but
00:32if I decided to put in a few tabs or a few spaces that doesn't matter at all.
00:37The language just doesn't care.
00:39It's ignoring the white space and just reading the characters that do occur.
00:44It's ignoring the line breaks because we use the semicolon to tell JavaScript
00:48where the statement ends.
00:50In fact, because we do it this way, if I wanted to, I could actually combine
00:54multiple statements onto one line.
00:58There is no problem with doing this in JavaScript.
01:01It does make our code tougher to read, so I am not going to do this.
01:04The general rule is one statement one line, but we could do it that way.
01:09Even inside the statements themselves whitespace is ignored.
01:14I could put multiple spaces between the different elements of that statement or
01:19on the other hand I could actually get rid of a couple of those spaces.
01:23The rule here is don't confuse JavaScript and don't confuse ourselves.
01:28While I could have this line, var b=10, squeeze down about this much, I couldn't
01:33take it one step further and get rid of this space, because now I am confusing
01:37JavaScript. What is varb mean?
01:40It needs to be able to figure out where one part ends and the next begins.
01:45So I'll need a space between the var and our variable name b. It's one of the
01:49reasons we can't have spaces in our variable names themselves.
01:53What I don't need is a space between the variable name here, b, and the equal sign.
01:59And that's because JavaScript knows the equal sign is not allowed as part of the
02:03variable name so this part must be separate, but best practice there are spaces
02:09between the different elements, the different parts of your statement.
02:13The only thing that's typical is you don't use a space before the closing semicolon.
02:19Now you could have one.
02:21This is perfectly a valid JavaScript, with one space or a dozen before the semicolon.
02:26But the way most people write JavaScript and other C-based languages is just to
02:31immediately close with the semicolon as soon as you can.
02:34It's just the way we finished the line like using the period at the end of a
02:37sentence in English.
02:39White space more than anything is simply for readability.
02:42You start jamming all the elements up against each other,
02:45it becomes tough to read.
02:46So you use as many spaces as you need to make this clear.
02:50Now there are a few customs that you may run into. Let's say we are using the ++
02:55operator and I am just doing a++ here.
02:58I could write this as a ++, but by convention, a simple line like this is
03:05just written this way, but that takes us into one more point.
03:09There are two places that white space does matter.
03:13First, if we are using an operator that has multiple characters like the ++ operator,
03:18this is one thing. While I could put a space between the variable name and the
03:23++ and I could put a space between the ++ and the closing semicolon, I cannot
03:28put a space in between the two. And that's because as far as JavaScript is
03:32concerned, this is not two addition operators.
03:35It is one ++ operator, the increment operator, the ability to add one to a variable.
03:41So you can't put a space in the middle of that, same with a --, same with
03:47operators like += or -=.
03:49You can't put a space in the middle of this just the same way you can't put the
03:52space in the middle of var or alert or prompt or a variable name.
03:57Now the second place whitespace matters is inside a string.
04:02There's a difference between what, space, is, space, your, space, name,
04:07and adding a few more spaces to it and that's because we want spaces to
04:12matter inside a string.
04:13So when you are creating string literals they will be regarded as significant.
04:18Now one question might be what if you want a line break inside a string?
04:22Well, for example here I might want to break the line between what is and your name.
04:27Now it's an easy thing to think, well, I'll just split that onto another line
04:32because after all we're ending the entire statement with the semicolon, so does this work?
04:36Well, no, it doesn't. You are not allowed to do it this way. JavaScript will get
04:40very confused about what's going on.
04:43If you want a line break inside a string, you may have to give JavaScript a clue
04:47that this is what we're doing, quite similar to adding the quotes inside a
04:52string by using the backslash.
04:54What we use is another backslash to say this is what's called an escape
04:58character, there is a special character coming up that means something other
05:01than regular text, and then I say \n. Now this looks little weird.
05:06It looks like what is \nyour name? But as far as JavaScript is concerned, these
05:11two characters here are special.
05:13\n means new line, and I am using this string literal in a prompt.
05:18So if I save this, let's test this one.
05:21I'm going to open up the HTML page that's pointing to this file and as we can
05:26see here, the message is now coming out as, What is, line break, your name.
05:31I type in Simon, I click OK, and we get the rather ugly looking
05:35message HelloSimon.
05:36Well, that's simply because I'm concatenating or combining two strings together here.
05:43I've created a variable called message that says Hello and then I'm adding the
05:48word Hello and whatever name was typed in and popping that up as an alert box.
05:53But really what I want is Hello, space, and then the name.
06:00So this would be another reason we would want this space regarded as significant.
06:05So that when we are combining strings together, they don't all jam up against
06:09each other. Saving that and trying that one again, we could just reload the
06:13page to try it again.
06:15We can see that now that space is being taken into account.
06:18Now as we start writing more and more code you'll often see a few blank lines.
06:26You'll often see lines indented with tabs or spaces.
06:30Again, JavaScript doesn't care.
06:32It doesn't pay attention to this. Whitespace has no actual meaning, no impact
06:37on what this code is going to do, but whitespace can be very useful for making
06:41our code more readable and we'll see much more of that soon.
Collapse this transcript
Adding comments to code for human understanding
00:00Once you've written more than a handful of lines of JavaScript or indeed any
00:04programming language, you are going to want to start adding comments to your
00:08code so it can remind you what you were trying to do a week ago or six
00:11months ago or a year ago.
00:13You add comments in JavaScript the same way as in the other C-based languages.
00:17The most simplest way of doing this is to actually write a line that begins with
00:21two forward slashes.
00:23Anything after two forward slashes will be ignored.
00:27So this is a single line comment.
00:31As soon as we leave that line, the rest of our code will be processed as normal.
00:35You can actually use those two forward slashes and even put them after an
00:40existing line, but it is more common to put them before the code that they are
00:47meant to be applying to.
00:48So if I was trying to split up some of my code here, I might say that this
00:53section was my Boolean variables and this previous one was my numeric variables.
00:59Obviously, these are pretty sel explanatory here.
01:03It's quite common that you will also see a blank line before the comment because
01:08it just makes it much more visible.
01:09Now what you can also do are create what are called multi-line comments.
01:17While we could use multiple lines just with two forward slashes on it, what we
01:21can also do is use a /* and now everything is a comment until we get to */.
01:34I only tend to use the multiple line format to comment out large chunks of
01:39code when I'm testing.
01:40Everywhere else I tend to use the single-line format just with the two forward
01:45slashes and that's what I'll be using for most of this course.
Collapse this transcript
4. Writing Conditional Code
Building with the if statement
00:00We've written a few lines of code, but so far, what's been happening is this.
00:05We start at the first statement, we execute it, we move onto the next,
00:09we execute it, we move on as fast as the computer can fully execute each line.
00:15Now it might pause if we're prompting for information from the user, but as soon
00:19as we come back, we move on again, top to bottom, each line in order,
00:24no exceptions, and it's kind of dumb really.
00:27You see beyond the most simple Hello World level programs, we need our code to
00:32be smarter than this.
00:33We need to start asking questions.
00:36If the bank balance is positive, calculate interest; if it's negative, charge a penalty.
00:41If they check the checkbox on the form, add them to the mailing list;
00:44if they didn't, then don't.
00:46If the position of the missile image is the same as the position of the
00:50spaceship image, then show the explosion image.
00:53We need to have code that sometimes runs, and sometimes doesn't depending on the
00:58conditions of the program at that time. This is conditional code.
01:03We begin with the classic if statement, which is found in every
01:07programming language.
01:09The if statement is written in JavaScript and is identical to this in other
01:14C-based languages using this format.
01:17Now, I've put a few spaces in here and a few line breaks just to make it
01:20clearer, but we are using the word if, then we've got a pair of parentheses, an
01:24opening and closing one, and then an opening and closing curly brace.
01:29And the general format is if some condition is true, then do whatever code goes
01:35between the opening and closing curly braces.
01:37Now, a quick aside for folks who are brand-new to programming.
01:41Bear in mind that in programming languages, we are very picky about the symbols
01:45we use and about what we call them.
01:48So just to be really specific here, when I say parentheses, I mean these; when I
01:53say brackets, and I'll usually say square brackets; I mean these ones and when I
01:58say braces, and I'll try and say curly braces, I mean these ones.
02:03They do serve similar purposes, they are mocking where something starts and
02:07where it finishes, but they are not interchangeable.
02:10Now, unlike things like say a semicolon or an equals sign, when you see
02:15parentheses, brackets, or braces, they are always found in pairs.
02:20If you have an opening one, you will need a closing one.
02:24It may be several lines later, but it needs to be there.
02:27So let's go back to the if statement.
02:29So in our case, the parentheses are used to mock out whatever our condition is
02:35and the curly braces are used to mark out what we are going to do if that's true
02:39which could be one JavaScript statement, could be a dozen of them, could be 100 of them.
02:44Okay, so what do we mean by condition?
02:46Well, we don't use the word condition. We are going to have something like if a
02:50is less than 50. We are actually asking a question, what is the condition?
02:54We want to check to see if something is true, a less than 50, or b greater than 20.
02:59Now here is the thing.
03:00Whatever is inside these parentheses must evaluate, must break down, as being
03:06either true or false.
03:08So if I am checking here if the variable b is greater than 20, I don't care what
03:13it is. I don't care if that's 21 or 25 million, or 20.000000001. All I want to
03:22know is, is this true or is this false?
03:25All conditions must boil down to simply true or false.
03:30Now, one of the things that's very common in JavaScript is you want to check quality.
03:34That's the condition that you're asking.
03:36Well, to check a quality in JavaScript, to ask if something is equal to something
03:41else, like in other C-based languages, we don't use the single equals sign.
03:45We use the double equals sign and no spaces between them.
03:48This is asking if C is equal to the number 99. That's the condition.
03:54Is that true or is that false?
03:56Now, heads up, even for programmers, JavaScript has another way of
04:01checking a quality.
04:02The triple equals sign.
04:04This is an unusual one and we'll come back and talk about this later, but
04:07realize for now that with all C-based languages, C, C++, C#, Java, JavaScript and
04:14many others, if you're in a condition, if you're asking if something is equal to
04:19something else, you will never use a single equals sign.
04:23As we saw with variables, when you see a single equals sign, that's an assignment.
04:27It's a command. It sets a value, not checks a value.
04:31We can also check inequality, that something is not equal to something else,
04:35which is the != written together as one operator.
04:40So in this case, if d is not equal to 100, is that true or is that false?
04:45Now, when you have several statements surrounded by curly braces, that's
04:50referred to as a code block and this is all that these curly braces are doing.
04:56They are grouping a section of code together; they don't have any other meaning than that.
05:00And as you'll see, blocks can be nested inside each other if you need to.
05:05Now, what you'll also see is the code inside a code block is indented.
05:10Our alert statement is about three spaces in from the if.
05:14It doesn't have to be.
05:15Again, white space is insignificant.
05:17It just makes it much easier to read.
05:20So here is an example.
05:21On the first two lines I am creating a couple of variables, variable a =
05:245, variable b = 10.
05:26Then I am checking if a is less than b, we open the code block and we're going
05:32to execute this line if that is true. Just pop up an alert, yes, a is less than
05:37b, and then we have a second if statement.
05:40if a is equal to b. Again, this must be either true or false.
05:45If it's true, we'll run that second alert message.
05:47I am going to go and execute the HTML page that contains our JavaScript and
05:53we'll get the alert box, yes, a is less than b. But we will not get the second
05:57alert message because this will evaluate as false. a is not equal to the value
06:03of b. Now, one thing to notice here.
06:06You do not have a semicolon after the closing curly brace.
06:11You will occasionally see that in say JavaScript you might read on the web,
06:14but you won't see it for an if statement.
06:16In fact, it's much rarer.
06:18A quick word about these curly braces.
06:21When you're reading other people's code, you're likely to see them in a
06:24couple of different styles, and you might be wondering, well, what's the
06:28difference between the two?
06:29The most common way that you will see it in C-based languages and in
06:32JavaScript particularly is that the opening curly brace would be on the same
06:37line as the keyword.
06:38So we've got this word if here and then we have the opening curly brace on the same line.
06:43Then we have our code indented inside the block, and then on a following line
06:48we have the closing curly brace to say this code block starts here and it ends here.
06:54However, you might also see them written so they align with each other like this format.
07:00If a is equal to b, here is where our block opens, here is the code we are going
07:04to execute, here is where our block closes.
07:07This is more common in languages like Pascal and C#.
07:11Now, programmers can get religious about brace styles.
07:14JavaScript doesn't care.
07:16It doesn't change the meaning of the code.
07:18This is regarded like everything else as insignificant white space.
07:23But most commonly, the sample JavaScript you're likely to find online or
07:28download or see in books, you will see it written this way and it does become
07:31very comfortable once you just get used to the general format.
Collapse this transcript
Working with complex conditions
00:00So I am going to create a condition and then add a little more thought to it.
00:04In this JavaScript file, I am starting off by creating a variable called
00:07balance, setting it equal to 5000, just to give us something to work with.
00:11Then I'm going to write my if statement.
00:14The condition, I am going to write here will be if balance is greater than 0,
00:18Yes, we know it is, but we are just writing some sample code.
00:22Then I need my code block.
00:23Now, it's very common that you'll see programmers when they hit the opening
00:26curly brace to also then jump a couple of lines, and do the closing curly brace.
00:31And this just verifies that I have both of them in place and I'll just come
00:36back up and start typing the code that's indented inside my code block.
00:41So we are just trying to prove a point here.
00:43So I'll do something like alert, the balance is positive, and we have a very
00:49straightforward condition.
00:50But the question is well, what if it's not?
00:53What if that was false?
00:54I could do another if statement and check balance again, but what I could also
01:00do instead is if that's not the case, I am going to add the word else.
01:05Then I'm going to do the opening curly brace for the code block again because I
01:10wrote that, do the closing one, and what we have going on is if the condition is true,
01:15we'll do whatever is in the first code block.
01:18Otherwise or else, we'll do whatever is in the second code block.
01:23So I'm going to write a line of code here, closing that with a semicolon.
01:29Now, I have introduced a very common error here and it's an error in my
01:34thinking, not in the code.
01:36We ask if balance is greater than 0, we're going to output a message saying the
01:40balance is positive.
01:41Otherwise, we'll output a message saying the balance is negative.
01:45Well, what happens if it's 0?
01:47In this case, we're going to hit the if statement. If balance is greater than 0,
01:50well that would be false.
01:52So if our balance is 0, it will give us the balance is negative message.
01:56really not what we want, but it's quite a common error to get hit with, particularly
02:00when you're dealing with things like positive and negative numbers.
02:03So be a bit too exclusive about what you're checking against.
02:08Thinking a bit deeper about it, what I want to ask here is if the balance is
02:12greater than or equal to 0. And of course what we are asking there is as far as
02:17our program is concerned, what do we care about?
02:20Let's say we are dealing with bank balances, where 0 would not count as
02:24a negative balance.
02:25Now, there is an operator for that.
02:27It's just the greater than or equals sign.
02:30This is regarded as a single operator.
02:33So it's just the two characters next to each other.
02:36What we can also do is take this a little bit further.
02:40Inside this first code block that will be executed if the balance is greater
02:45than or equal to 0, I could add another if statement.
02:52If balance is greater than 10,000, do my opening curly brace for the code block,
02:58couple of lines, and then do the closing one.
03:00And notice that what I am doing here is trying to make this apparent.
03:03I am lining up my closing curly brace with its corresponding if statement,
03:08the same way that I would line up the first closing curly brace with its
03:12corresponding if statement, and then I would indent any code inside of that.
03:21If I were to save this and then jump over to my container HTML page that will
03:28run it, we should get The balance is positive.
03:33Click OK. But we do not get this internal if statement because balance is not
03:38greater than 10,000.
03:39That would be false.
03:41So you can create multiple levels of complex conditions inside your code.
03:46Now, do be aware, don't nest too deep.
03:49JavaScript can handle a thousand levels of If statements if you started to type them,
03:53but lots of nested Ifs, say beyond three levels, can get very difficult to
03:58read and make sense of just for a human being.
04:01If we do have to have more complex logic, there are other techniques we can
04:05use to deal with it, such as working with functions which we're going to get to soon.
Collapse this transcript
Setting comparison operators
00:00So when we're writing if statements and we want to check that one variable is
00:04equal to another variable, we use the double equals sign, the equality operator.
00:09In this case, if the contents of the variable a are equal to the contents of the
00:13variable b, we're going to execute whatever statements are inside the opening
00:18and closing curly braces.
00:20But there is a mistake that's very easy to make. In fact, pretty much every
00:23programmer in a C-based language will make this at sometime in their career, and
00:27that's to accidentally use assignment, single equals, instead of equality, the
00:32double equals sign or in JavaScript the triple equals sign.
00:35What that means is let's say we create a couple of variables, variable a, set it
00:40equal to 5, variable b, set it equal to 10, using the single equals sign to
00:46assign to set the values of these variables.
00:49A little later on in the code, I might write an if statement, and I'm asking, is a = b?
00:54But I accidentally used the single equals sign instead of the double equals sign.
00:58Well, we have a problem now.
01:00What's going to happen is we're going to execute the if statement.
01:04It's going to hit that code and it will say, "Okay, single equals sign, that's
01:08assignment" and it will set a equal to the value b. This successful operation
01:15will then be regarded as true and the code inside the if statement block will
01:19always be executed, even when you think it shouldn't be.
01:22So we have just made a = b. Now, this is perfectly legal syntax in JavaScript,
01:28but it can lead to code that just doesn't work the way you expect and it's
01:31difficult to debug because it's easy to miss.
01:34What we should have done here is use the double equals sign.
01:38So remember, when you see the single equals sign, that is the assignment
01:43operator, you are telling, this is a command.
01:46When you see the double equals sign, this is the equality operator. You're
01:50asking, is one thing equal to another thing?
01:54And in JavaScript and in a couple of other languages like PHP, there is another
01:59equality operator which is the three equals sign or triple equals sign.
02:03Now even if you're an experienced programmer, you might not have come
02:06across this one before.
02:08Again, it's in JavaScript, it's in PHP, but it's not in most C-based languages.
02:13A three equals sign is what's called a strict equality operator.
02:16Now, what the devil does this mean?
02:18Well, let me show you an example.
02:21So in this simple code here, I'm creating a variable called a and I'm setting
02:26it to the number 123.
02:28Then I'm creating a variable called b and I'm setting it to the string 123.
02:34Now remember that we talked about JavaScript being a weak typed language that
02:37any variable can hold any kind of value whether it's a number or a string or a Boolean.
02:42So what's happening here is I'm asking, is a = b?
02:48a is 123, b is 123, but it's a string.
02:51They are actually different types of data.
02:53Let me run this example.
02:56I'm going to run the HTML code that contains this, and it pops up the message
03:01Yes, they ARE equal.
03:04And that's what happens if I use the double equals sign.
03:08Even though strictly speaking they are different kinds of data, JavaScript is
03:12being flexible here.
03:14It's kind of saying, "Yeah, I know what you mean, when you want to compare the
03:16two, you probably want to say this is true."
03:19However, if I used the triple equals sign here, and I'm just going to save that
03:25JavaScript, go back and reload the page,
03:28this would say, No, they're NOT equal, and this is the strict equality operator,
03:34the triple equals, which is going to make sure that not only do we have the
03:38values the same but the types better be the same too.
03:41So variable a and variable b better both be numbers. One can't be a string.
03:46To make this equality check work, I'd have to remove the quotes here.
03:50If I then save that and refresh it again, it would say Yes, they ARE equal.
03:56They are equal, they are identical, they are both 123 and they're both numbers.
04:02When you're using JavaScript, some writers recommend using the triple equals
04:06sign all the time and never using double equals.
04:10I wouldn't go that far. When I see a double equals sign in some JavaScript, I
04:13don't think it's wrong, but it's certainly not a bad habit to get into, that when
04:17you're checking equality in JavaScript, you'd use the triple equals sign.
04:21So to round those up, we have if (a == b), using the double equals sign, or
04:28not equal to, using the != sign. We have the strict equality, not just equal but identical.
04:36Similarly, we have the not strictly equal, the !==. All of this you are going to run into a lot.
04:43But we also have the other kinds of comparison.
04:47If a>b. Again, remember it doesn't really care what any of these values are.
04:54Whatever is in the parentheses just needs to be true or false.
04:57a is either greater than b or it is not. a is either less than b or it is not.
05:03We also have the >= and not surprisingly, the <=.
05:09All of these operators, if there is more than one character in them, you can't
05:12put a space in between them.
05:14They are all considered one indivisible unit.
05:18What we often then have to do is take it a step further.
05:21We need to ask multiple things at the same time.
05:24So let's say I've got four variables.
05:26What I want to ask is if the variable a is equal to the variable b and the
05:31variable c is equal to the variable d?
05:33Now, I could do this with two if statements but it's nice to combine them all on one condition.
05:39I can't use the word and here.
05:41There are some languages where you do.
05:42Things like the Basic based languages but not in the C-based languages.
05:46What we use instead is the double ampersand.
05:49Now what this means is both of these conditions, a has to be equal to b or
05:54strictly equal to b and c has to be strictly equal to d, for this whole thing to
05:59be regarded as true.
06:01Again, the entire contents of the parentheses have to be true. And sometimes we
06:07don't want to go that far.
06:08We might ask if a is strictly equal to b or c is strictly equal to d, then we
06:13want that condition to be true.
06:14Well, instead of the two ampersands, we use the two vertical bars, pipe symbols
06:19depending on what you call them, are how we say an Or inside this condition.
06:24To make it a bit clearer to read, you often enclose the separate conditions
06:29inside their own set of parentheses.
06:32You don't have to do this, but it can make it a bit more readable.
06:35So in this case, we're saying if a > b and c < d. And sometimes when you have
06:42these complex conditions with longer named variables, they can get pretty long
06:46so you can break them onto multiple lines.
06:49Although keep each unit together.
06:52I wouldn't typically take it this far, but because line breaks are
06:55insignificant, we could do it if we thought it made it more readable.
Collapse this transcript
Using the switch statement
00:00You will end up writing if statements in pretty much every program you ever write,
00:05but sometimes there's a specific situation where it's not the only option
00:09for checking a condition.
00:11Let's say you're checking a variable for a selection of very specific values.
00:15Here is what I mean by that.
00:17We create a variable in this case called grade, and somewhere in the program I
00:22want to check is it Regular or is it Premium or is it Diesel?
00:25I've got a few very specific values I'm asking for.
00:30We can do this as a series of separate self-contained if statements like I have
00:35here or we could even start using the else condition to actually start combining
00:40them altogether, but this can get a little clunky, particularly if you don't just
00:43have three or four but you have 10 or 12.
00:46Well, in this kind of situation, JavaScript and most other languages have
00:50something called the switch statement instead of the if statement.
00:54Now in some other languages, it's called the select or select case statement,
00:57but it's the ability to list in one place several situations or cases that
01:03you're looking for in a very readable format.
01:06So if I know I'm checking here for this variable being either Regular or
01:10Premium or Diesel, I'm going to delete the if version of it and create a switch statement.
01:16Now, it has a very similar format to the if statement.
01:18We've seen that the if uses this general format here. I'm not going to fill it out.
01:23But we have the word if, we have the opening and closing parentheses for our
01:27condition, and then we have the opening and closing curly braces for our code block.
01:31Well, all I'm going to do here is replace the word if with the word switch, all lowercase.
01:36Of course, all these words in JavaScript are lowercase.
01:40And switch needs to know what are we switching on?
01:42What is the important variable that we're looking at?
01:45And it is of course grade.
01:47So all I need to do is put grade inside the parentheses.
01:51It's not grade is greater than something, grade is less than something.
01:54We're just saying we're looking at the variable called grade.
01:58Then what we do is inside the code block inside the body of the switch
02:02statement, we describe the different situations, the different cases that we're
02:06looking for, and the way that I do it is this.
02:09I use the word case and we describe the first option. And in the case, the grade
02:14is equal to Regular.
02:17I don't use the equals sign or the double equals sign because we already know
02:21what variable I'm looking at.
02:23I'm looking at grade.
02:24So case "Regular" and then I use a colon, and I'm going to describe what I'm going to do.
02:29Let me just bake this out a little more and that will start to make sense and
02:32fall into place here.
02:34Now, because I'm checking a variable that contains a string, I am using the
02:40double-quotes when I am checking these string literals.
02:42If I was checking a variable that was a number, I could just say case 1, case 2,
02:48case 3 without putting them in double-quotes.
02:49Now, this is the first time we've actually used the colon here.
02:53It looks a little unusual, because we're used to the semicolon ending a line.
02:57That's not what we're doing here.
02:59We're actually saying in the case that it's Regular, we're going to do something.
03:02I just haven't described what that is yet.
03:04Well, this is how I start to fill it out.
03:06I'm going to put in the alert statement that I had a moment ago.
03:10Now, as I start to do this, hopefully it becomes apparent that this is a
03:17very readable format.
03:18It's very easy to scan this and figure out what we're actually looking at and
03:21what we're going to do.
03:24One of the benefits of using the switch statement is we can actually finish off this.
03:29We can also describe what happens if it isn't any of these.
03:32And instead of using the word case, I can finish this off with just the word default.
03:37This is not in double-quotes. We're not checking that variable for the
03:41value default. We're just saying in any other situation I'm going to do something else.
03:46In this case, alert("That's not a valid grade").
03:50now, there is one more thing I have to add to this for this to work properly.
03:58You see when we come down into the switch statement, let's imagine we're going
04:01through this line by line.
04:02We create a variable called grade, set it equal to Premium.
04:06We come into the switch statement, and it asks, what are we looking at?
04:09We're looking at the variable grade. Is it Regular? No, it isn't.
04:13So we jump down to the next case. Is it Premium?
04:16Yes, in this case, it is.
04:17We're going to run the alert, but because of something that exists in switch
04:21statement called fall-through, we will immediately then just jump down and
04:25we'll find the next statement we can execute, which is this alert statement, and
04:29then we'll do this alert statement.
04:31That's not what we want.
04:32We need to prevent fall-through in our cases here.
04:36The way that we do that is basically to add the word break.
04:39We can think of it as saying, now we're done with this case.
04:42So right at the end before the next one, we say break.
04:47And I'm going to put in three of those here.
04:49What break is going to do is jump us out of this switch statement.
04:55It will actually jump us right to the end of the closing curly brace and
04:59continue on executing any code that may come afterwards.
05:03Technically, we could put a break keyword in after the default one.
05:07We don't really need to because this one is actually just going to jump out
05:10anyway because we're right at the end of the switch.
05:13So I'm going to save this and we're going to run it and what should happen is
05:19we'll start this code, we'll create a variable called grade and set it equal to Premium.
05:23We'll come into the switch, we'll check, is it Regular?
05:26No, it isn't. Is it Premium? Yes, it is.
05:29We should pop up the alert saying it's $3.35.
05:31We should then break and then jump outside of the switch statement.
05:36Let's see if that's what's going to happen.
05:38I'll double-click the webpage that's pointing to this JavaScript file, and there we go!
05:43It's $3.35.
05:45No extra messages, no fall-through going on.
05:49This is the basics of a switch statement.
05:52Very useful in the situations where you have a range of set values that you
05:56need to check against.
05:58And you'll find that between your if and else statements and your switch
06:02statements, you have all your conditional code covered.
Collapse this transcript
5. Modular Code
Breaking your code apart
00:00As we start to add more code, you'll find that your code begins to get messy.
00:05It becomes harder to read, harder to follow.
00:08So in all languages when we have large amounts of code, we break them apart into
00:14smaller, reusable, modular pieces.
00:18Now these have different names in different languages.
00:21Sometimes they are called modules, sometimes subroutines or subprograms, or just
00:25routines or methods.
00:28Now with JavaScript and with many other languages, we call these functions.
00:33A function is simply the idea of taking a block of code whether one line, five
00:38lines, or a hundred, wrapping it up, and giving it a name so that you can call
00:43it later and you can treat this block of code as one thing.
00:49It's very common to have your functions use this verb-noun format such as
00:53calculateArea, createMessage, sendEmail, animateImage.
01:00And the way that we create them in JavaScript is that we take the code that we
01:04want to enclose, whether that's one line, ten lines, or a hundred.
01:09We surround it with curly braces to create a code block to say where this
01:14function starts and where it ends.
01:16And whatever is inside that code block is called the body of the function.
01:19Now we need to say what this function is.
01:22We need to give it a name, so we first add the word function in JavaScript.
01:26And because we could have dozens or hundreds of them, we give it a unique name.
01:31And that part, like variables, is up to us.
01:34So it could be createMessage, hideMenu, animateImage, explodeSpaceship,
01:40calculateScore. And let's just call this one myFunction.
01:44After the name of the function, we need opening and closing parentheses.
01:49These say whether this function expects to have data passed into it which
01:54we'll get to later.
01:55In this case, empty parentheses means no, it doesn't. Now that we've created this
02:02function, we can call it.
02:05So somewhere else a little bit later in the program, I can use the name of the
02:09function followed by the empty parentheses and a semicolon.
02:14This causes the function body to be called and all the code inside it is executed.
02:20Now it's worth bearing in mind, we could both do this multiple times, calling
02:24that function again and again and again.
02:27But do also be aware that if you create a function, it won't be
02:32called automatically.
02:33You have to call it yourself.
02:36Now if you have one or more functions in your JavaScript file, it doesn't
02:41officially matter where you write them.
02:44You could write your functions in any order. You could call your function
02:48and then define it.
02:49That's because the JavaScript engine will first do a quick scan of your code and
02:55figure out what functions exist before it actually tries to run anything.
03:00But it is a best practice to define your functions before you call any of them.
03:06It makes for a more readable code.
03:09So typically, define all your functions up at the top of your JavaScript file.
03:14Now in other languages, you may even find it's a rule to define your functions
03:19before you call them.
03:21So whether they use the term functions, modules, subroutines, methods, this idea
03:28of treating a block of code as a callable unit inside a larger program is a core
03:35feature of all programming languages.
03:37It makes your programs easier to write and easier to understand.
03:41You can split work among different programmers by giving them different parts to write.
03:46Now functions can of course get more complex than basic ones shown here.
03:51They might not just perform an operation, but they might return values or they
03:56might accept data, and we'll see how to do that next.
Collapse this transcript
Creating and calling functions
00:00I have got a few simple JavaScript statements here and I'm going to turn
00:03this into a function.
00:05You can do this anyway that makes sense to you. What I'll just do up here is
00:08I'll create a framework of the function and then copy this code into it.
00:12I'll use the name function and I've got to give it a name. I'll just say
00:16myFunction, not very inventive, but it will do, opening and closing
00:20parentheses and we'll get more into these later, and then the opening and
00:24closing curly braces.
00:26I am then going to grab these statements, cut them from one place and paste them
00:32inside the body of the function, and I am going to in indent them a few spaces.
00:36I don't have to do this. This will be regarded as insignificant whitespace, but
00:41it makes it easier to read and easier to see that these lines of code are nested
00:45inside of a function.
00:46Now the statements inside this function will now not be executed when this code first runs.
00:53The JavaScript interpreter will look at this file of JavaScript and say, "Oh,
00:58you have got a function called myFunction, good for you." But it will not run unless you say so.
01:03So once you've made a function, you have to call the function.
01:07In our case what I need to do is run some code that is not inside a function
01:12right now that will run when the page first loads. And all I do to call this
01:16function is I am going to say myFunction, name of the function, and again the opening and closing parentheses and
01:24a semicolon to end that statement.
01:26I am going to save that and flip over and run the container.html that's pointing
01:31to this and what happens is the page loads, it loads the JavaScript, the first
01:38line of code that is executed is this line called myFunction, which then causes
01:43all the statements inside the myFunction to be executed line by line, which
01:49causes the alert box to pop up.
01:51Now the great thing about it is what it allows us to do is, if we wanted it, call
01:57this myFunction 3, 4, 5 times. Not that this is going to be very exciting, but
02:02if I save this and then I just go back to the page and reload it, what we'll
02:05have is five alert boxes.
02:09You can call a function once, you can it call it twice, you can call it a thousand times.
02:13It's a great way of creating modular code.
02:15You can even have a function call itself.
02:18This is a process called recursion, which can allow you to do some very
02:22interesting, although that's a subject for another time.
02:25You can have as many functions as you want inside your code. You can have one
02:30function call other function, call another function, call another function.
02:33In fact, that's the general way that you will start to break up your code.
02:37So they let you have a little more control over this code and when it runs.
02:41Functions let you break apart your code into more manageable pieces, but we can
02:46take them a little further. We also want them to be able to pass information
02:50back to us, and we want to pass information into the functions when they run.
02:54So let's see that next.
Collapse this transcript
Setting parameters and arguments
00:00So I have a simple function here called addTwoNumbers.
00:03It just creates two variables, adds them together, and displays the result.
00:07And that's fine, but of course this isn't very useful because it's always
00:11adding the same two numbers together, always 5 and 10, no matter how many times we call it.
00:16Well, I'd like something a bit more flexible than that.
00:19I'd like this function to be able to take in some different information to add
00:22different numbers together.
00:24And I can do that by defining parameters for this function, to say that whenever
00:29we call it, we're going to pass information into it.
00:32That's what the parentheses are for after the function name.
00:36They allow us to say do we pass one piece of information into this or two
00:40or three or a dozen.
00:42And all we need to do here is give it the name of what will become two variables.
00:47In this case what I could do is remove my variable declaration here, var a and
00:52var b, and just say that this function takes in two parameters called a,b.
00:59If I wanted three parameters, I could say a,b,c. I can call them whatever I want,
01:06whatever is meaningful.
01:08They obey the same rules as variable names, because really what's happening is we
01:12will have variables created for us called a and b. That means the first line
01:18that I can run here is var result = a + b. Those parameters that were passed
01:23into this function will be added together and will display the result.
01:27Now of course the flip side of this is if my function expects information passed
01:32into it, well, I better pass information into it when I'm calling it.
01:35Now I could create two variables and pass in the variable names or in this case,
01:41I could just pass in 5,10. Save that.
01:45When this function is called, 5 will be passed in under the name a. 10 will be
01:50passed in under the name b. We save it, we run it, and we should have the 15
01:55alert box being popped in.
01:57The flexibility of this simply means that I could call this again, passing in
02:03different numbers. Save that, run it again.
02:12We'll get three alert boxes, 15, 600, and -2316.
02:19When you start working with defining parameters to your functions, you'll often
02:23hear the term arguments as well and parameters and arguments can seem a little
02:27bit interchangeable.
02:28There is a formal definition.
02:30When I'm defining a function, here what I'm defining here are a and b.
02:35They're my parameters.
02:37When I'm calling the function, I'm passing in 5 and 10.
02:42These are my arguments.
02:44Now often in conversation with other software developers, these terms are almost
02:48interchangeable, but they do have a formal meaning.
02:50So if you're interested in what that was, that was it.
02:53Now if you think this looks a little strange and you need time to get used to it,
02:56well, bear in mind, the very first thing that we did in JavaScript was
03:01calling a function, passing in a parameter.
03:05When I said alert("Hello, world"), I'm calling the built-in alert function in
03:13JavaScript, passing in the string literal "Hello, world" as an argument.
03:18But let's take this one a little bit further.
03:22Instead of just passing information into a function, I can also pass information
03:27back out of a function.
03:29The way that we do that is by using a new keyword called return.
03:35If I wanted to create say this result by adding these two numbers together and
03:40instead of popping up an alert box I just want to pass that result back to
03:44whoever called this function, well, what I'm going to say is return result.
03:48Now the question is, well, what does that do?
03:51Now as soon as you hit the word return, you're actually going to jump right
03:55out of this function.
03:56So one of the things you don't want to do is start say creating new variables
04:00after this because you'll never actually get to this line of code.
04:06When we call the function, we're going to be executing the first line and then
04:10the second line and when this one is executed, return result, we're going to
04:14jump back to whoever called this.
04:17So it's often the last line of the function, although occasionally you can use
04:21return to leave a function early if you need to.
04:24The question is what happens?
04:26If we say return result, well, what's going to happen now?
04:28Well, I'm just going to save this and just run this page and we'll see
04:34nothing happening at all.
04:35The function is actually being called three times and it's returning results,
04:41it's returning these numbers added together.
04:44But the problem is I'm not doing anything with those returned results.
04:48What I need to do is something like this.
04:50Create a new variable and set it equal to whatever happens when I call the
04:55addTwoNumbers function.
04:56So in this case, we're going to pass in 5 and 10. They will be added together in the function.
05:03That number will be returned, and the result will be stored in the variable
05:07called x. I could then pop up an alert box, save that over here, and run it.
05:15We should get one alert box saying 15.
05:17As you can see, even if a function returns values, I don't have to do anything
05:23with the information that's returned.
05:25But most of the time, you'll want to.
05:27And again, if this looks a little unusual, this is what we were using very early
05:32on when we called the prompt function in JavaScript.
05:38Prompt is a built-in JavaScript function.
05:41It takes in one argument.
05:44In this case, the string that's going to be displayed. And then whatever is
05:48returned from that is what we were accepting back into a variable called name.
05:53So both passing information in, passing in arguments to be received as
05:58parameters into functions, and returning values is a very core piece of any
06:03programming language.
06:04It's something you'll be using all the time.
Collapse this transcript
Understanding variable scope
00:00So one more thing you should be aware of when working with functions and this
00:03goes not just for JavaScript, but for most modern programming languages.
00:07If you create a function and define a variable inside that function using the
00:13word var, that variable is only available inside that function.
00:19This is because of something called variable scope.
00:22And every variable has a scope.
00:23That simply means where is this variable visible? Who can see it?
00:27Who can use it?
00:29So let's say we define this simple function and then we call it.
00:33What's going to happen is we will jump into the function, we will create the
00:36variable, and we will pop up the alert box with the contents of that
00:40variable which is 500.
00:42Control returns to right after we called it and if try and pop up the content of
00:47x again, this will be regarded as undefined.
00:51It will say I don't know what x means, because the x variable is not available
00:56outside simple function.
00:58This is because variables declared inside the functions are referred to as local variables.
01:04They have local scope.
01:05They are only available within the opening and closing curly braces of that function.
01:11If I need to have the contents of this visible outside, I could do a couple of things.
01:15One is I could return a value using the Return keyword and we saw that little earlier.
01:21The other way that I could do it do is to declare, to create the variable
01:25outside the function.
01:26So up at the top I create var x.
01:29That's outside all functions and that's referred to as a global variable.
01:33That means we could just use the word x to refer to it anywhere, whether I'm
01:38inside a function or outside a function.
01:41Now I want to be careful of is not using the word var to declare that variable again.
01:47So inside simple function I don't want to say var x. I just want to say x = 500.
01:53So now we could call it inside the function and it would be 500.
01:58Then we could call it outside the function and it would be 500 as well.
02:02Now in JavaScript we only worry about scope when we talking about functions.
02:07It doesn't apply to other code blocks like creating variables inside loops or if
02:11statements and so on.
02:13But with other languages variable scope can apply on those levels too.
02:17So you have to be quite careful about where your variables are defined and
02:21who can get to them.
Collapse this transcript
Splitting code into different files
00:00We can end up with hundreds or thousands of lines of code very quickly.
00:04And although we will be splitting them up into functions, they can still get
00:08difficult to read and navigate.
00:10Another way to make your code more manageable-- and this happens in every
00:13programming language--
00:14is we stop trying to keep it all in one file and we just split it up
00:18into several files.
00:19Now you wouldn't do this randomly.
00:21You wouldn't have half a function in one file and half in the other.
00:24But you might group several functions together in one file and several more in another.
00:30This also makes it easier for multiple people to work on the same project by
00:34working on separate files.
00:36And in complex applications built by teams of software developers, it's not
00:41unusual to have hundreds or thousands of separate code files for one project.
00:44Now JavaScript isn't a language that you would want to split up into hundreds
00:48or thousands of files.
00:50It's unusual to have more than a handful.
00:52The question is if you do split it up, how does the web page know where to find everything?
00:57But we have seen that the way that we tell our HTML page where our JavaScript is,
01:02is we use a script tag.
01:04This is what we've been using all along and if we split our JavaScript into
01:09multiple files we simply add more script tags. That's it.
01:14The JavaScript engine, the interpreter that's built into the browser, will load
01:18all of these and run the code inside all of these files.
01:22Now because the JavaScript engine will try and run your code as soon as it gets
01:27its hands on it, order can be important here.
01:29So let's say we are linking to three separate JavaScript files, script.js,
01:35morefunctions.js, and functions.js.
01:38Let's say we have a bunch of really important functions that are going to be
01:41called by some code in our script.js file.
01:45Well, by default what's going to happen is the JavaScript engine is going to try
01:49and run the code in script.js as soon as it loads it.
01:52If it's looking for functions that it hasn't gone to yet we are going to have a problem.
01:57So order is important.
01:59Just be aware of any dependencies that you might be creating and whether you've
02:03loaded all the code you need to load.
02:05To make sure those important functions are loaded into the interpreter first.
02:09Now having said that for us, this won't be an issue.
02:13In this course, it's perfectly acceptable to keep all the things in one script file.
02:17But for future reference, and particularly with other languages, you will see
02:21the code that you work with typically split up into different files to make
02:25it easier to work on.
Collapse this transcript
6. Iteration: Writing Loops
Introduction to iteration
00:00So let's talk about iteration.
00:02This is the programming buzzword for a loop.
00:05And here's the idea.
00:06You start writing some code.
00:08A few statements that deal with, say, looking in all the MP3 files in a folder or
00:13changing the position of an image on the screen.
00:16So we write some statements to do it once.
00:19Then we figure out we need to do it again.
00:21So we write them again and again and again.
00:24All these can get pretty tedious and rather than write it out several times or
00:29even several thousand times, I'd like to be able to write my statements once
00:34and then just say "Repeat this."
00:36Repeat it 5 times or repeat it 5,000 times, or keep repeating until told to
00:42stop, or go through all the fields on a web page or go through every MP3 file in a folder.
00:49So we might repeat two statements, we might repeat a dozen, we might repeat a hundred.
00:55And this is what we do by creating loops and you'll also hear this called iteration.
00:59Now creating loops is actually easy.
01:03The main issue with any loop is not when to loop. It's when to stop.
01:08If we need to loop 5,000 times, who's keeping track?
01:12If we need to loop until told to stop, well, where's the code to figure out how to stop?
01:16So all our loops will actually have conditions that control how long they loop.
01:23So how do you do this?
01:25Well, we've seen an if statement.
01:28If the condition is true, do whatever is in the block.
01:33In this case here I have got a variable a = 1.
01:35If a < 10 we pop up an alert box.
01:39Classic if statement here.
01:41Well, simply replace the if with the word while and we have a loop.
01:47Not if this condition is true, but while this condition is true, execute
01:53the body of this code.
01:54It could be one line in this block or a hundred lines.
01:58And whatever is in the body of the loop gets executed for each iteration,
02:03meaning every time the loop goes around.
02:06So here is what happens.
02:07We set off setting the variable a = 1 and we are storing that value in memory.
02:12We then jump down to the while and we check the condition just like with an if statement.
02:16Here, it evaluates as true. Yes, a is less than 10.
02:21So we jump into the body of the loop inside the curly braces and we execute
02:25whatever code is there, in this case just popping up an alert.
02:29Then we get to the end of the loop.
02:31The end of the loop is marked by the closing curly brace of the while statement.
02:36What will happen here is we jump back to the start of the loop and we check
02:40the condition again.
02:42And this happens automatically. Is a < 10?
02:45Well, yes it is.
02:48So we move on and we go on again.
02:49Now here's the problem.
02:51If nothing in this block changes the value of a, and a is what we are checking,
02:57we will now have an infinite loop.
03:00And an infinite loop is a very bad thing.
03:02We would now be stuck in this loop forever. Or at least until we turn our computer
03:07off or force our program to terminate.
03:11So in this loop and in most loops we are needing to keep track of something.
03:15In this case, we need to add a line to increment the variable a.
03:20So if I add an a++, and that's inside the body of the loop, then when we are going
03:25around this one again we will check is a < 10, yes, it is, we pop up the alert,
03:29we do whatever other code is here,
03:31and right before the body of the loop closes, we say a++.
03:36Meaning we add one to the value of a. a is now 2.
03:39We come back up and we will check it again. Is a < 10?
03:44Yes, it is.
03:44We'll jump back into the body loop and we'll keep going, but we are incrementing a.
03:49And at some point a will be 10.
03:52Then we ask it again, is a < 10? No, it isn't.
03:56It's 10. That's not less than 10. That is 10.
03:59So we count as false.
04:01Then we will jump out of the loop or we'll jump right to the end without
04:04executing any of that code and we'll move on and we'll execute whatever code comes after.
04:11So this while loop is the most basic loop in JavaScript and it's common across
04:18many, many language and takes this general form.
04:20It's almost identical in lot of other languages.
04:23But there are other kinds of loops as we'll see in a moment.
Collapse this transcript
Writing a while statement
00:00So I'm going to write some simple iteration code here, but before I do I have a
00:05quick question for you and this is not a trick question, it's not a riddle, but
00:10I am interested in the first answer, your gut answer that comes to mind.
00:14Here is the question.
00:15You need to build a straight fence and it must be 50 meters wide and you need
00:21fence posts every 10 meters.
00:24How many fence posts do you need?
00:26Do you have your answer? Good!
00:32Let's get into the code.
00:33So in my JavaScript here I'm going to create a simple While loop where I'll
00:38show you how to do it and I'll show you one of the most common gotchas with iteration.
00:43I want to make a variable called amount.
00:47Start off at 0 and I want to add the number 100 to it 10 times.
00:52So I'm going to create a loop to do that.
00:55So when I create a loop as I mentioned there is always three parts to it, so
00:58I'll add a few comments here just before we start to build it out.
01:01First, we're going to create the index, then we're going to have the loop that
01:06checks the condition, and at some point we need to have the ability to increment
01:12or add to the index.
01:14So these are just comments. Let's create an index here.
01:17It's very common to call your index i. But you can call it whatever you want.
01:21So we'll start off with an index of i = 1.
01:24Now I'm going to come and do my while loop. Again it takes the same format as ifs.
01:29We've got the word while then our opening and closing parentheses and then our
01:36opening and closing curly braces that represent the body of the loop.
01:41So in while we got the condition that we're going to check. Just like an if
01:44statement that needs to be either true or false.
01:47And what I'm going to say is while i < 10 we're going to jump into the loop.
01:53What I'm going to do is add 100 to amount, which I could say amount+100.
02:02I could have also used the += format here, and then what I need to do inside the
02:07body of the loop is here is where I need to increment the index.
02:12I can't wait till I leave the loop, because if I do we'll never hit that line.
02:16The increment must be inside the loop itself.
02:19I'm just going to say i++.
02:22So every time around we're going to add 1 to the variable i, we'll then hit the
02:25end of the loop, the closing curly brace, and we'll jump back up to the while
02:29statement and check the condition again.
02:31Now finally what I'm going to do is use our good old alert box and say "The value is: "
02:38and we'll write out the final value.
02:40We're only going to hit this line after we're done with the loop and we write
02:44out the value of the variable called amount.
02:47So I'm going to save that and test it. So we're going through this, we're going
02:52to add 100 to amount 10 times which should give us 1000.
02:56But no, we get 900.
02:58This is a very common mistake to make and some of you I'm sure have spotted
03:04the problem already.
03:05I started off with my index set to 1 and then I started the loop. Is i < 10?
03:12Sure it is, it's 1.
03:14We then go through the loop, we add one to it. It's now 2.
03:17Is i < 10?
03:18Sure it is, it's 2.
03:19We add another hundred, we keep on going.
03:21Now at some point i will go from 8 to 9, we'll loop around again, and then it
03:26will go from 9 to 10 and we'll loop around again.
03:29We'll check the condition. When i is 10 this will evaluate as false, so the last
03:34time we go and run the loop, we run i = 9.
03:36So we're only actually adding 100 nine times, not ten times.
03:42Now what could have worked here is either saying if i <= 10, or we could have
03:49started off with our index set to 0, because that would have looped around once
03:54before we even incremented it to 1. But of course the flip side problem here is
03:59if I did both and we try and save that and run that page again, we're now going
04:04to end up with 1100.
04:08So I want one solution or the other, but certainly not both.
04:11Now these are what is known as off-by- one errors and it's really easy to go
04:17around either one too many times or one too few if you don't have it exactly
04:22straight in your head.
04:23And it's not computers causing this issue. The issue is with us.
04:27It's an easy mistake to make even without computer is involved.
04:31One example of this is known as the fencepost error.
04:34This is the question that I asked earlier.
04:37You need to build a fence.
04:38It needs to be 50 meters wide with fencepost every 10 meters.
04:43How many fenceposts do you need?
04:44Now lot of people's gut reaction is 5, some say 7, but the answer of course is 6.
04:51And if it's this easy to make off-by- one errors when we're working with really
04:56simple concepts like 50 divided by 10 or 100 times 10,
05:00how do you think it is when you're dealing with way more complex data with much
05:04more abstract start and end positions?
05:07And this is just one example.
05:08When we start working with collections of data making sure that we're going
05:12through it exactly, it's quite easy to get wrong.
05:15Like with the fencepost error, every programmer I've ever known will admit
05:18to making off-by-one errors. So a little extra thought with your loops can go a long way.
Collapse this transcript
Creating a for loop
00:00The while loop is the classic loop in C- based languages, but after you've looked
00:05at a few you'll realize that a pattern begins to emerge.
00:10That you always have to deal with the same elements.
00:13Regardless of what code you put in your loop, whether that's one line or a
00:17hundred of them, you're dealing with setting up an index to keep track of the
00:22loop and you have to do that outside of the loop itself.
00:26Then you're going to be checking the condition and then you have to make sure
00:30that you're incrementing the index inside the loop, but at the end of it.
00:34So you always have these three pieces going on to have a successful loop.
00:39And this is such a common model.
00:40There is actually a statement that brings all these pieces together and
00:45that's called a for loop.
00:47It's the for statement.
00:49It's still follows that same basic if statement format. We've got the word for,
00:54we've got the opening and closing parentheses, we got the opening and
00:57closing curly braces, but there seems to be an awful lot going on inside these parentheses.
01:02Really what we have is the same three pieces that we use in any loop.
01:07We've got the section that sets up the index, we've got the section that checks
01:11the condition, and then we've got the section that increments the index, and
01:15these three parts are separated with two semicolons.
01:19The first time we hit this loop we'll create a variable called i, set it equal to
01:231, then we'll check to see if it's less than 10, it is, we will jump into the
01:28loop, we'll execute all the lines in the body of the loop.
01:30when we hit the closing curly brace we'll increment the index, we'll check
01:35the condition again, and we'll keep on looping until that condition is no longer true.
01:39The great thing about this is it's really readable. Everything about the loop is
01:44right there at the top.
01:46You don't have to look outside the loop to find the index being set up nor
01:49do you have to scan inside the loop for the increment to make sure that's in the right place.
01:53So it's a very clear and straightforward way of setting up a loop.
01:57You'll probably find this is more common in any code that you'll find online or in books.
02:03And you will find that while loops and for loops will take care of most of
02:08the manual looping that you ever need to write. And these are the same across
02:12all C-based languages.
02:13Now there is one more loop I'm going to explain, you won't see this an awful lot,
02:18but you will run into it from time to time.
02:21It's the do or do/while statement.
02:23The difference between this and the classic while is we actually move the
02:27condition to the end of the block.
02:30The format usually looks a little weird because it doesn't match anything that
02:34we've seen before, but we still have the same elements in place.
02:37I'm setting up an index, var a = 1, then I have the keyword do. I open up the
02:43blocks, we've got our code, I've got the incrementer of a++, but the condition
02:48that I'm checking is right at the end, while a < 10.
02:53Unlike the while statement we actually do need a semicolon at the end of
02:58the do/while statement.
02:59Now the really big difference with this format is that the block and whatever is
03:03in it will always be executed once before the condition is even looked out.
03:08So even if this condition was false, if a started off at 1000, we would execute
03:14the code in the block before we check the condition.
03:17That may or may not be what you want.
03:19So while you will see this from time to time, while loops are much more common
03:24than do/while loops.
03:26In most loops you'd expect to check the condition before you enter the loop and
03:30it's much more readable to have the condition at the top of the loop as with
03:34the while or with a for than at the bottom, which is where you see it when you got a do/while.
Collapse this transcript
7. More About Strings
Cleaning up with string concatenation
00:00So JavaScript is a weakly typed language.
00:03Meaning our variables can hold numbers, they can hold strings, they can hold
00:07Booleans, but JavaScript still cares, it knows the difference, and it treats
00:11those values differently.
00:13Let me show you an example.
00:14If I create two variables, foo and bar, and I give them numeric values,
00:20the number 5 without double quotes, then I call alert adding them together.
00:26I'm using the addition operator, the plus sign.
00:29What I'll get will be the number 10.
00:32It understands these are numbers.
00:33It adds them together.
00:35If on the other hand, I create these variables with the digit 5, but inside
00:40double quotes as a string and then I use exactly the same code, I'm using the
00:45addition operator to add them together,
00:48what's going to happen is concatenation, not addition.
00:52They are going to put them beside each other and what will be output is 55.
00:58This is a behavior you do occasionally want to have happen even when the values
01:02in your strings are what we think of as numeric.
01:05So you're working with area codes and phone numbers.
01:08You don't want to be in a situation where those will get added to each other
01:12and actually have a different number, you want them concatenated one beside the other.
01:17Now it might get a little more puzzling, but what happens if you've got one of each?
01:21So what happens if one variable is a number and the other variable is a string?
01:27Well, what's going to happen is if one is a string, that's going to take charge.
01:30You'll get concatenation will occur.
01:32Now where it can get even a bit more involved is what happens if you try and do
01:37something that just doesn't make sense.
01:40We create a variable foo = 5, we create variable bar equal to the letter B, and
01:45then we try an alert foo times bar, foo multiplied by bar.
01:49Well, concatenation it doesn't work here.
01:51What you're actually going to get is this. You're going to get the value
01:56uppercase N lowercase an uppercase N lowercase N. This is Not a Number.
02:01That's how JavaScript will represent something that just doesn't make sense, and
02:05JavaScript has this built-in idea of something being Not a Number.
02:09It's something that it understands and this can come in very useful for us.
02:14Because sometimes we have variables that we want to be a number, but aren't.
02:18 Let's say for example we've got a variable equal to the string 55, so it
02:25could be numeric, but it could be abc.
02:27It could be an exclamation mark.
02:29Perhaps we're asking somebody to type in a value into a prompt box. We hope it's
02:34a number, but it might not be.
02:36Well, what I can do first is I can create a new variable.
02:39I'll call it myNumber. I'm going to try and convert whatever is in foo into a number.
02:45Sometimes that will work, sometimes it won't. So value like 55, it would work.
02:50If it was an exclamation mark it wouldn't.
02:53Now this looks a little odd. This is a built-in function in JavaScript called Number.
02:58It's one of the few times we've seen an uppercase N here.
03:01We're passing in the variable foo and we're saying make it a number and store
03:06the result in the myNumber variable.
03:09Hopefully, this will work, but it might not.
03:12So the next thing that I need to do is check it and we use another built-in
03:18JavaScript function called is Not a Number, or isNaN.
03:22So isNaN is a built-in function in JavaScript.
03:25It accepts a variable and it will tell us, is this a number or is it not a number?
03:30Now think about what it's called, isNaN is not a number.
03:35What that means is we'll get true or false back from this.
03:40It will return true if this is not a number, and because this is in an if
03:46statement here, that's what we're asking if it's not a number,
03:49we're going to pop up an alert message.
03:51Now quite a lot of the time what you want to actually ask is if something is a number.
03:57Well, there is no isNumber function.
03:59they can only tell us if it's not a number.
04:01So if I'm asking if something is a number, I'm actually going to do a weird
04:05double negative here.
04:06I'm going to use the exclamation mark to negate the call to the function.
04:11What I'm asking is if it's not not a number.
04:14Meaning is it a number?
04:16In which case we'll then pop up the alert box saying, yes, it's a number.
04:20Looks a little strange, feels a little strange,if it's the first time
04:24you've seen anything like this, but you'll find JavaScript has a few of
04:28these little things tucked away.
Collapse this transcript
Finding patterns in strings
00:00A little earlier in the course I talked about strings in JavaScript and in a lot
00:05of other languages being smart, being able to tell us information about
00:09themselves, and even having behavior.
00:12An example of this would be if I created a variable called phrase and gave it
00:16this simple value. I can then use the name of the variable, followed with a dot,
00:22and then I can access certain built-in information about it.
00:25So I am using this .length, what's called a global property, to access this fact
00:30that it's 24 characters long, and we can pop that up in an alert box.
00:34Well, it goes a little deeper than this.
00:37If I'm working with a string in JavaScript that also has behavior
00:41and we can use the same dot operator to get to that.
00:44Strings have what are called methods and these are like functions.
00:48We've already seen functions.
00:49We call them with parentheses, but methods are like functions that belong to a string.
00:54So again, if we create a variable called phrase, what I can do is use a phrase.,
01:00and then some built-in methods like toUpperCase, which I'm calling like a
01:05function using the parentheses after it.
01:07Now because I have this in an alert box what we are going to get is that string converted to uppercase.
01:15Now I am not going to dive into every behavior that strings have.
01:20These change across different languages, but you will find in most of them
01:24strings are quite powerful and they have various built-in behaviors like
01:28converting to uppercase or converting to lowercase or allowing us to find
01:33certain pieces within them.
01:34Now a couple of things to understand about strings, where they do become a
01:38bit more complex than numbers, is because we can obviously have strings using different cases.
01:44If I create two variables, one containing the word Hello with an uppercase H and
01:49the other containing the word hello with a lowercase h, and then I want to see
01:53if they are equal to each other, well, they won't be, because uppercase H and
01:57lowercase H are not equal.
01:59But perhaps what I want to do is a case insensitive comparison.
02:04I don't really care whether it's the uppercase or lowercase.
02:08I just want to know if the same word is in them.
02:10Well, the fact that I can use these variables and convert them means that what I
02:14could do is something that might look a little annoying here, but I'm asking if
02:18the str1 converted toLowerCase is equal to str2, converted toLowerCase,
02:25then I can ask, are they actually equal?
02:27And this is a great ability of being able to ask strings to do things for us.
02:34One step further is we can find certain words that exist inside of strings.
02:39This is very, very common to want to do.
02:42So we create a variable called phrase and then what I am using is what's called
02:47the indexOf method of the string.
02:50I am using that same dot operator and then indexOf.
02:52It's an lowercase i and an uppercase O, and I am passing in another string.
02:58In this case I am passing in the word groovy, and I want to find out what is
03:03the index of groovy?
03:04Meaning, if it exists, where does it begin in the string?
03:08Now what's going to happen is if that word exists in the first string, it's
03:13going to return the position and that's zero based.
03:16So the first letter of the string, which is the uppercase W, will be positioned 0.
03:21Groovy will start at position 10.
03:23If that word is not found in the string, this will return -1.
03:29So if for example, I wanted to find out, if a certain phrase or word did not
03:33occur, I could call phrase. indexOf, passing in a DDDD.
03:39We know that does not occur.
03:41And if the result of that was -1, I could pop up an alert box that says, no,
03:45that word does not occur in the string.
03:48And of course, there are dozens of ways that you could combine these different
03:51kinds of operations to find out if a phrase was in a string or if it was not in
03:56a string, but this is one example of doing this.
03:59Now again, in a course like this, I'm not really expecting you to try and memorize this syntax.
04:06What I am wanting you to do is understand that this is possible.
04:09That understand that, yes, I can find one string and I can see if it exists in
04:13another one or I can see if it does not exist in another one.
04:17You can always look the syntax up, you can always find cookbooks and examples
04:22online, but you need to know that this stuff is possible.
04:24There is also a method called lastIndexOf. Whereas .indexOf will give us the
04:32first occurrence of the word in the larger string,
04:35.lastIndexOf will give us the last position of that in the string.
04:39So if we are working with larger amounts of text that might be useful.
04:44We can also start breaking a string apart. There are several methods for this.
04:48One of the ones I like is called slice.
04:51So we create a variable called phrase, just give it some basic text.
04:54And what I'm going to do is create a new variable called segment based on part
04:59of phrase, and I am going to use phrase.slice, and slice expects two arguments.
05:05In this case I am some passing in 6,11. What does that mean?
05:09What we are going to do is the first number is the position that we are going to
05:14start at in the phrase, and it starts from 0, so 0123456, 6 is the o of another.
05:23Then 11 would be the position we are going to stop by.
05:26So we are basically going to get 6, 7, 8, 9, 10.
05:28We will get those letters and we will store that result in the second variable,
05:36and that's how we could pull a section out of another string.
05:39There are also methods like .substring() and .substr() that do have similar ways
05:46of dealing with this, but they give us a couple of other options.
05:48I am a fan of slice, but you can look at the others if you're interested.
05:52More than ever what you should be taking from this is not necessarily trying to
05:56remember the syntax or remember the exact format, but just understanding the
06:01JavaScript, and JavaScript is a pretty lightweight language, has a whole lot of
06:06built-in functionality for manipulating strings, for getting to them, for
06:11understanding where the other words exist inside them.
06:14You'll find that across all modern programming languages and it can come in very handy.
06:21One final thing to explore is the idea of comparing strings, not for equality,
06:26but for greater than and less than. We can do this.
06:29Let's say we've got a couple of basic strings here, aardvark and beluga.
06:33Then I write an if statement. If (str1 < str2).
06:37What it's going to do is start comparing the first letters.
06:41In this case, really asking is a less than b, almost like a phonebook comparison.
06:46In this case, yes, absolutely! This would be true.
06:50However, the fact of adding in the uppercase and lowercase parts of it can make
06:55things a bit more confusing, in not necessarily the way you expect.
06:59So here in the second example, I have aardvark with a lowercase a, and Beluga
07:03with an uppercase B. Again, I ask if there is a comparison? Is str1 < str2?
07:09Most people would think, well, yes it is, but here is the problem.
07:13This would actually be regarded as false, and that's because as far as the
07:19internal structure of how we encode characters in a programming language,
07:24the uppercase letters are regarded as less than the lowercase letters.
07:30So uppercase B is regarded as coming before a lowercase a. So this will be false.
07:37A technique that I might use to ignore this would be once again using the
07:40ability of the string to be converted and calling toLowercase on both of these,
07:45before I actually compared the two.
07:48So all you can see, there are a few gotchas when dealing with strings and some
07:52of the behaviors are not necessarily intuitive when you're new to this.
07:55You can also see that strings have a lot of built-in behavior that allows you
08:00different ways of dealing with this.
Collapse this transcript
Introduction to regular expressions
00:00While strings have some great built-in functionality-- we can convert them to
00:04uppercase or lowercase, we can slice pieces out, we can find out if a word
00:09exists in the string--
00:10well, sometimes we need a different approach and what we are more interested in
00:14is the format of the string.
00:16What I mean by that is maybe I want to ask, is it an email address?
00:21Not a particular email address, but does it match the pattern for one? Or is it a URL?
00:26Perhaps I want to ask if a password has a mixture of uppercase and lowercase
00:31letters and special symbols or verify that a credit card number has the
00:35correct amount of digits.
00:36Now to do this kind of work many programming languages, including JavaScript, have
00:42something called regular expressions built into the language.
00:45Regular expressions are strange looking sequences of characters that describe
00:50and can match patterns and strings, and nobody finds regular expressions
00:55pleasant to begin with.
00:57But they're really useful and you should know what they are and what they can do.
01:01There is always two parts to working with regular expressions.
01:05First, you create the expression that describes the pattern that you're looking for,
01:10and next, you try and apply it to something and ask if it matches.
01:16So step one, we are actually going to create the regular expression.
01:19We can do it a couple of ways. One is this.
01:22It looks a little strange. We are creating a variable.
01:24I'm calling it myRE for my regular expression = /hello/.
01:27Now this looks a little odd.
01:32Where are the quotes? What do we do?
01:34Well, this forward slash.
01:36Notice it is forward slashes, not backslashes, marking this as a
01:40regular expression.
01:41This is a JavaScript shorthand for doing this.
01:45There is another way of doing it, which would be this.
01:47This is a longer way, but it's doing exactly the same thing, var myRE = and we
01:53use the word new RegExp, regular expression, and feed in the string hello into it.
01:59What we are actually doing in either of these cases is creating a new regular
02:04expression object in JavaScript.
02:06JavaScript is what's called an object oriented language, and I'm using the word
02:10new in the second example to actually create a new object.
02:15Now we haven't explicitly done much with objects yet, but we are going to talk
02:18more about them later.
02:19Now the word hello is actually as simple a pattern as you can get.
02:24What we are going to do is look for the word hello to exist in another string.
02:29So once we've created our regular expression, we then have to test it.
02:33So let's say I create a new variable called myString, and this is what I am
02:36going to test my regular expression against.
02:39So in my if statement, I'll ask if myRE.test, so .test is a built-in method.
02:46Again, it's like a function that belongs to this regular expression.
02:50And I'm passing in the variable myString to say test this, check it, does it
02:55have the word hello in it.
02:56What's going to happen is we get a Boolean response from this.
03:00Calling test will return either true or false.
03:03In this case, if the word hello exists in myString, which it does, we are going
03:08to pop up an alert and say, yes.
03:11The regular expression objects have other methods that can return different data.
03:16More complex patterns are created by using special characters.
03:20So to give you a few examples, if I create a new regular expression variable
03:23here, and I'm using the shorthand format which uses the two forwards slashes,
03:27one at the start and one at the end, and whatever is between them is the pattern
03:31that we are matching on.
03:32The actual forward slashes themselves are not part of the pattern.
03:35We've seen how to match on the word hello.
03:37Well, if I prefix this by this little character, which is the caret character,
03:41we are saying the hello has to be at the start.
03:45If instead my pattern was hello$ before the forward slash, it would have to be at the end.
03:52Using the plus inside the pattern means that the L would have to appear once or more.
03:58So it would match on these different examples.
04:01Hello with one l, with two ls, with multiple ls.
04:04hel*o means that it would be a 0 or more.
04:09So it'd match all the previous ones, but it would also match heo.
04:11The l doesn't have to appear at all.
04:14We have the question mark for 0 or 1 match, which will be a bit more restrictive
04:19on what it was matching.
04:20It would match heo or helo, but would not match more than that.
04:27Using the pipe, the vertical bar symbol, means we are actually matching
04:30either hello or goodbye.
04:33The decimal point is the period, means any character.
04:36Using a /w inside the pattern is matching an alphanumeric or and underscore.
04:42\b inside the pattern means we are looking for what's called a word boundary
04:47like a space or a new line.
04:49You can also use the square brackets to provide a range of characters to match on.
04:55In this case, what we are looking for is either crnl or d and then the ope, so
05:00it would match on cope and rope and lope and dope.
05:04As you're beginning to tell there is a lot of these and there's actually way
05:08more than I am showing here, and you can describe extremely complex patterns by
05:13stringing them all together.
05:15Here is one for example that describes a US zip code with an optional four digit extension.
05:21I'm not going to go through this.
05:23Bear in mind, you're going to begin by finding and looking for examples online.
05:29If you're looking for regular expressions to match a date or a password or
05:33credit card format, there really is no reason that you should be trying to
05:36create it yourself from scratch.
05:38This next regular expression here is one that tries to match on an email address.
05:43In fact, matching an email address is a pretty complex operation and people
05:47have been debating for many years on what the perfect regular expression for an email address is.
05:53It looks very complex, but you can actually see there's kind of a repetition of
05:57the same kind of thing going on through it.
05:59It's really because an email address can follow quite at a lot of complex rules.
06:04Email addresses are notoriously difficult to match on regular expressions and
06:08this one is certainly not perfect, but it's kind of an example of what you might
06:12see and what you might come across.
06:14You will find that sometimes with more complex patterns that you're not looking
06:18for a perfect match.
06:19You're just looking for one that's good enough.
06:21And it is worth keeping in mind with regular expressions, particularly if
06:25you're brand-new to them,
06:26that I wouldn't be at all focused on trying to memorize these formats.
06:31I'd be more focused on understanding the fact that they do exist, what they can
06:35be used for, how they're used.
06:37The syntax itself is something you don't need to memorize, not now, if probably ever.
06:43They are a tool.
06:45They're something to be used when you need them, but you'll find that they're
06:47built-in to most modern programming languages.
06:50They're certainly in JavaScript and they are in almost all of ones you're
06:53likely to come across.
Collapse this transcript
8. Collections
Working with arrays
00:00An array is a collection of values all wrapped up and given a name.
00:06Okay, so what does that mean?
00:07Well, we already know how to create one variable at a time.
00:11We use the word var, we give it a name, and then we can use the equal sign to
00:17give that variable a value.
00:18That could be a letter, it could be a number, it could be a string, it could be
00:22a Boolean, but it's one value.
00:24Now an array is the idea of multiple values but all contained in one named
00:31variable such as this one.
00:33We have a variable called myArray with multiple values in it.
00:37It's a great way to keep data together that belongs together, to keep dozens,
00:41hundreds, or even thousands of pieces of information together without having to
00:45name every single individual piece as an individual variable.
00:49But before we make one, here are a couple of concepts.
00:53See if all we have is one name for this entire array, how do we get
00:57individual pieces in or out?
01:00Well in an array each individual value, often referred to as an element, has a
01:05number, an index that identifies where it is in the array.
01:10Arrays have an internal order.
01:12Tey don't shuffle their values around randomly.
01:14So the first slot has an index of 0, the second slot or second position has an
01:20index of 1, third slot is 2, and so on.
01:24So I have got an array with seven elements in it here but there is no minimum or maximum size.
01:30You can make arrays as big as you need them. You are simply limited by the
01:34amount of memory you have available.
01:36In JavaScript, like most languages these days, arrays are zero-based and that
01:42means the first position, the first element in the array, is considered to be at
01:47position 0, not position 1.
01:50In some languages like older versions of Visual Basic used 1-based arrays but
01:550-based arrays are far more common.
01:58So we can use that number, that index to either set that value or to get to that value.
02:06So I need to use both the name of the array and the index of the element to
02:11access any one part of the array. So let's make one.
02:16In JavaScript, we can make the variable the same way we always do it, but we
02:21need to tell JavaScript this is an array.
02:23There is actually a few ways to do it, but this is the easiest one.
02:27We'll use the word var and I'm going to call my variable multipleValues. You can
02:31call it whatever you like.
02:32Then we will use the equal sign and then what we are going to use is this opening
02:38square bracket and closing square bracket, and this is the indicator that we're
02:42dealing with an array, not a single value.
02:46When you see those square brackets in JavaScript, it's a pretty good sign
02:49you have got an array somewhere.
02:51So this line and these characters here simply create a single variable called
02:57multipleValues that you can put a bunch of stuff inside.
03:01Well how do you do that, how do I get to the individual elements of that array?
03:06I use these square brackets again.
03:08So if I want this array to hold multiple values we need to be able to say which
03:13element of the array are we trying to get to?
03:15So we use the index.
03:16So here is an example.
03:18I use the name of the variable but instead of just saying equals, I am using
03:22those square brackets again.
03:24I'm saying here I want the element at position 0 to be set to the value 50 and I
03:31want the element at position 1 to be set to the value 60.
03:35I can say I want the element of position 2 to be able to the word "Hello" and
03:40notice that what I can do in this array is I can put in a number, I can put in a
03:44string, I could also put in a Boolean, I can actually put anything in there.
03:48It doesn't matter what kind of data you're putting in at the different slots in
03:52the array, but all of them are accessed using that index and that's whether you
03:57are setting these values or whether you're getting these values.
04:03It's always a 0-based index.
04:05Now what we can then do is use the same format to get to the contents of the array.
04:11So for example, if I want to write an alert message with whatever is at the second
04:15position I use the square brackets. I use the same way to access them and to set
04:21them and it writes out the word "Hello" in this case.
04:25So if this is the way that we write arrays. It's okay, it's not too bad, but it
04:30would be nice if there was something a little quicker, and in fact there is.
04:34There is a shorthand method for doing it.
04:36So instead of doing it over several statements like this, we can use those
04:41square brackets and combine all this stuff onto one line.
04:45We can just load this array up with the initial values.
04:48In this case, 50, 60, "Hello", and it will automatically create an array and put
04:55them in that position 0, position 1, position 2.
04:58You could then come along and add position 3, position 4, and so on but it's
05:03always a 0-based index.
05:05Now arrays are found in every language, and as we will see there are other ways
05:10of grouping values together.
05:12Sometimes you might not want a 0-based index but perhaps a letter-based index
05:17or some other way of accessing the elements of the array.
05:21And we can do that too.
05:22But these arrays are the classic way to get started with what we are often
05:26referred to as collections in a programming language, and this time the buzz
05:31word really is straightforward. A collection in a programming language is
05:34simply multiple values grouped together in some way, and there are often
05:39slightly different ways of creating them across languages but the overall
05:43concept is the same.
Collapse this transcript
Array behavior
00:00We are working with arrays and in JavaScript arrays are objects, and that's one
00:05of those words that sounds very generic, but it has a meaning in programming.
00:10We are going into what objects are but for now it just means they are more than
00:14dumb containers of data.
00:16Arrays are smart. They can tell us information about themselves.
00:19They have behavior. They can actually do things if we ask them to.
00:23And what do I mean by that?
00:24We have kind of seen some of this already.
00:26Let's say I create a variable that's just a string.
00:29But we have seen that we can use the .length property of that string variable to
00:35find information about the string.
00:37In this case, it would pop up the length of it being 24.
00:40I didn't have to go and count all the letters.
00:42The string itself actually knew what its length was, and we can use that same
00:47kind of format to find information about arrays.
00:49Let's say I use the shorthand format to create an array here with five elements
00:54ranging from position 0 through position 4.
00:57I could do something very similar that I did with the string and
01:00call myArray.length.
01:03In this case, it will pop up an alert box with the number 5.
01:05That's an important idea here.
01:09It knows its length is 5.
01:11That is the length of the entire array, there are five elements in it, although
01:15bear in mind the highest index is 4.
01:170, 1, 2, 3, 4, but we are using the same .length property.
01:23It's smart enough to know that when we say .length on a string, it's how many
01:27characters are in the string.
01:29When we say .length on an array, it's what's the length of the array.
01:33Now we have already seen how we use functions in JavaScript.
01:37We use the name of the function with the opening and closing parentheses.
01:41You can create them yourself.
01:43We can also use the built-in functions like alert.
01:46In this case, I am passing in information into that function. Or I can call a
01:51function, passing in information that also returns a value.
01:55So functions are used all over the place.
01:57But we also have the idea of methods and they are very, very similar, but a
02:02method is a function that belongs to an object.
02:06So instead of calling it directly, we actually use the name of the object, then
02:10a dot, then the name of the method.
02:13And when I say some method here with the opening and closing parentheses, it's
02:16very much like calling a function.
02:18But we have to say what does this method apply to, what I am doing it on, and we
02:22have seen this before.
02:24If we have a string variable, we can use the .toUpperCase method to actually
02:29convert that to uppercase.
02:31And we have several very useful ones with arrays.
02:35So I can create multiple arrays and then call the different methods on each array.
02:40So let's say I use the shorthand format here.
02:42I am creating a new array and just putting some random stuff in it.
02:45I have got an array with five elements.
02:48What I can then do is say myArray.reverse.
02:52I am using the opening and closing parentheses but I don't need to pass anything in.
02:56That will reverse all the elements of the array in place.
03:0050 had been at position 4.
03:02It's now at position 0 and so on.
03:05We have other methods like .sort.
03:07That will sort them according to the rules of JavaScript sorting, if it's all
03:11alphabetical or numerical or a mixture of the two. We have .join.
03:15That will take all the elements of the array and combine them with commas and
03:19return them as a string.
03:20We have useful little methods like .pop.
03:23If I call .pop on myArray it's going to take the last element, what's currently
03:28in there at oosition 4, and detach it and return that as a value.
03:33So we can pop something off the end of the array.
03:35Now the flip side of that, we also have .push.
03:39In this case I have to push a value on to the array and it will push it to the
03:43last element of the array.
03:45So these arrays are smart. They can tell us information, they have behavior.
03:49We can actually get to different pieces of them. And there is more that an array can do.
03:53Now one of the questions you might have is when you're learning programming you
03:56might be thinking, "Am I supposed to remember all this?"
03:59Well no, at least not initially.
04:01You'll find that you will memorize the things that you've used but no
04:05programmer tries to memorize every single method on every single object. There are just too many.
04:11So the kind of thing that you do is you find a reference guide.
04:14Now with JavaScript I'm a big fan of the reference guide
04:17you can find at Mozilla.org.
04:20These are really the people that own JavaScript so it's a good example.
04:25We jump into that Reference guide and what I will find is it breaks down all the
04:29different objects that are available, like array.
04:31I could go in and find some information about the array.
04:35it would give me a lot of descriptive stuff.
04:37But what I will find in the Table of Contents is there will be a section that
04:41says Properties, things like Length or Methods, and I could jump down to Methods
04:47and it would actually tell me, as I start to scroll down here, I have got the pop
04:51method which removes the last element from an array and returns that element.
04:54I have got the push method.
04:56That will add one or more elements to the end of the array.
04:59I have got sort, I have got splice, and this is the way that you start
05:03navigating the language.
05:05You will find a reference guide for the language that you're working with and
05:08you start to explore the different pieces of the language as and when you need them.
05:13Don't try and memorize everything, because that's just not going to work.
05:17Just know where you can find the reference of the syntax. The ability to find
05:23what you need to in a reference guide is much more powerful than trying to
05:27memorize everything.
Collapse this transcript
Iterating through collections
00:00Arrays are one of the most common things you're find in all programming languages
00:05and to get the right perspective here don't think so much of the word array, but
00:09think of the wider idea of collections and think of how many different kinds of
00:14applications you have in your computer that are really collections of things.
00:18Your email program is a collection of emails, your address book is a collection
00:22of contacts, your MP3 player containing a collection of albums and playlists,
00:28each one being a collection of songs. They're everywhere in programming.
00:32And an array is the most fundamental straightforward kind of collection you can have.
00:37Now one of the most common things you'll ever need to do is to iterate through
00:41or loop through every element in an array and this is actually a very easy thing
00:45to do. You don't really need to know much about the array to do it.
00:49So let's take a look.
00:51So let's say I have a simple array here with five elements in.
00:55It doesn't matter if it's 5.
00:56It doesn't matter if its 500.
00:58I'm going to set up a basic loop to go through this.
01:00So I'm going to create a while loop.
01:02I could do a for loop as well, but this is fine.
01:04It's got the regular elements.
01:07We need to set up the index. Although it's very important when you're working
01:11with a basic array you start the index at 0, because our arrays are zero based.
01:16Than we do the usual check condition and here's kind of the magic sauce here.
01:21When you're doing this, you don't need to know much about the array as long as
01:24just asking it what is its length.
01:27It can tell you how long it is.
01:29We don't need to know this going into it. Sure,
01:31I could write while i < 5, but it's much easier to write while i < myArray.length.
01:39And of course, this is a loop, so at the end of the body of the loop we want to
01:42increment that index.
01:44But know that every time we iterate through or loop through this we can use the
01:49index, the value of i to access the current element.
01:52Let me show you a little bit about what I mean just in case that isn't clear.
01:55If we start to move through our code and we start to execute it, we create this
01:59variable i and it's equal to 0.
02:02We then move to the next line. We say is i less than myArray.length? We'll go
02:07out and look, what is myArray.length? It's going to be 5.
02:10There are five elements in the array.
02:13If you remember that .length property gives you how many elements there are.
02:17The highest one is of course 4. So this is true.
02:20We jump into the body, we start executing any of the code, and then we might
02:23say using alert message or something else, we want to access whatever is the first element.
02:29So we'll use myArray and whatever the value of i is. Well, i is 0.
02:34So we'll get to the first element.
02:35Then we'll process further, we'll get to the end of the loop, we will increment
02:39the index, i now becomes 1.
02:41We'll jump back and check the while statement again. Is 1 < 5?
02:46Yes, it is.
02:47That we'll be true and we'll start moving through and we will keep on the
02:50looping around, adding one to this index while we go through every element in the array.
02:56But at some point we will hit i++.
02:58It will change i to 5.
03:00Then we'll say is 5 < 5? No, it isn't.
03:04It's equal to 5.
03:05So this is false and I will just jump out and continue on our merry way.
03:10So the important things here, we're starting the index at 0.
03:15When we're checking the condition we're checking against the length of the array
03:19and we're doing a less than, not a less than or equal to, and then inside the
03:23loop we're using that index to access the current element.
03:26Now you might think, well, what so great about this?
03:29Well, let me show you a kind of a real example here.
03:33So in this simple example here I'm creating an array with five elements,
03:37each with the value 500.
03:38I want to just add them altogether.
03:40Now I'm doing a for loop. So here is a version of the for loop rather then the
03:44while loop, but I'm doing exactly the same thing that I showed in these slides.
03:49Start the index of at 0, ask if it's less than the length of the array, and
03:55add 1 to it, and then every time we go through this loop I've just got one line of code.
04:00I'm going to say the variable total should be set equal to whatever it currently
04:04is plus whatever's at the current position.
04:08If I'm going on the loop for the first time it's at position 0, second time
04:11position 1, third time position 2, and so on.
04:14So we should iterate around the for loop five times and then after we are done we'll
04:18come down and pop up this alert message.
04:20Well, let's check it.
04:21We're adding 500 five times, we're hoping that we don't get an off by one error,
04:26but I can hold this in my head correctly, and yes 5 times 500 is 2500.
04:31That looks correct.
04:33Here's the great thing about programming your array iterations like this.
04:37You don't have to know how big the array is.
04:41If I come up here and change this and add in a whole bunch of other numbers,
04:47I don't have to do anything with the rest of my code, because I wasn't programming
04:52it to only go through that array five times.
04:54I'm telling it go through the array however long it is.
04:58So I can save this and all I'd change was how many elements we're in the array.
05:02I run it again and it still works just fine.
05:06So keeping those couple of simple rules in place about knowing where you start
05:10and knowing what you're checking when you're iterating around an array can make
05:13it very easy to go through all the elements in a collection like this.
Collapse this transcript
Collections in other languages
00:00It's worth a quick detour to talk briefly about collections in other
00:04programming languages.
00:05Now I don't need to get super specific about each individual language, but there
00:10are a few general things you should be aware of.
00:12First off, JavaScript allows anything in any element of the array.
00:18Numbers, strings, Booleans, you can even have elements undefined.
00:22So it supports this mixed data idea, but many languages only allow specific
00:28kinds of data in an array.
00:30It is an array of strings or an array of integers. You can't have both in the
00:35same array and this is probably more common across languages.
00:39Similarly, JavaScript allows us to create an array with say for example three
00:44elements, but we can then add to it or even subtract from it. But other
00:50languages may want your arrays to be a fixed size.
00:53You have to know how big it is before you make it.
00:56If you make an array that's five elements long, you can't change it after it's been made.
01:00Now there are a couple of words you may run into with this idea, that of a
01:05mutable versus an immutable object.
01:08If something is a mutable it can mutate, it can change, where if something is
01:12immutable it cannot change after it's been created.
01:16So in quite a lot of languages you're actually choose whether you want an
01:19immutable array or a mutable array.
01:22Now you might think, "Why an earth would I ever want an unchangeable array, why
01:27wouldn't I just want the flexibility of one that can change that I can add to, subtract to?"
01:31Well, think of a couple of examples.
01:33So you make an array containing all the days of the week or the months of
01:37the year, do you really need to add elements to that array? Do you actually
01:41want that array to support the idea of suddenly removing the second element mid-program?
01:46Probably not.
01:47One of the benefits of immutable arrays is that they're usually faster, because
01:52the language can just allocate an area of memory for that array that it knows
01:56will never change, whereas with mutable or changeable object there is always a
02:01little bit of overhead for knowing that this array may grow or shrink.
02:05We've seen that an array is an ordered list of items.
02:09We start at position 0 and go up one by one, but there are other kinds of
02:13collections where we might want something different.
02:17Let say instead of the built-in index of 0, 1, 2, we might want a, b, c or even
02:23more likely to have the idea of a key, something that's more meaningful to us.
02:28Let's see an example.
02:30Say we have a list of states.
02:32It might be very useful to have this collection, but using the abbreviation for these states.
02:37So instead of going up 0, 1, 2 we'll use AL, AK, AZ.
02:40Now this kind of an array can be created in many languages and it goes by quite
02:46a few different names.
02:47Generally, it's called an associative array, but some languages call this a
02:51dictionary or map or a table.
02:53There are even a few more names to it.
02:56For those of you who worked with databases you may think there is kind of a
02:59link between these.
03:00This of course is not a database.
03:02It's nothing to do with a database.
03:03This is still a variable in memory, but it's a very useful one to allow us to go
03:08directly to each individual piece of data.
03:11So when you move into exploring any language you're going to find it's very
03:16common for you to consider what is that language's built-in support for
03:20different kinds of collections, what does it let you do and what does it make you do.
Collapse this transcript
9. Programming Style
Programming style
00:00When we talk about style with programming languages, we're moving away from the
00:05rules, the syntax of how you must and must not write your code, into more of how
00:09you should and shouldn't write it.
00:12Now, we've talked about this a little already.
00:14It's things like what should you call your variables, what's the best place to
00:18put your curly braces, what should you call your functions, and where should
00:23they go in your code.
00:24Now all programming languages develop accepted style guidelines.
00:28There's often a lot of debate over what should be the right way to do things but
00:33even with a disagreement, they're still really useful.
00:36The main point of style guidelines is that you want your code to be readable,
00:40you want it to be consistent, and you also kind of need to play along with how
00:45everyone else in the world is writing that language because that's going to make
00:49it easier to read example code and read books and to recognize whether the code
00:54you're looking at is written well.
00:56So let's take a look at a few examples of style guidelines for JavaScript.
01:01And these, not surprisingly, are similar in many other languages,
01:05particularly C-based ones.
01:07We're going to begin with naming conventions.
01:10Now we've already seen that the rules of JavaScript say you must use letters,
01:16numbers, dollar sign, underscore, and you can't start with a number.
01:21But that doesn't mean that something like this would be a good idea for a
01:25variable or function name.
01:27This would be allowed.
01:29But we want clarity, we want readability, we want meaning.
01:33And yeah, okay, when we're learning, we often use placeholder names a lot.
01:38Create a variable called a or one called b or one called c. We can pick any
01:43letters that we like or we can use common meaningless words like var foo and var bar.
01:50But our real JavaScript variables will represent meaningful information, a name,
01:55a date, the height and width of an image.
01:59Naming conventions develop over the years and these days the dominant way
02:03JavaScript is written is this.
02:05Variables and functions, which will be most of what you name yourself, are
02:08written in CamelCase format.
02:10And what that means is that variable name starts lowercase but if you have
02:14more than one word, you capitalize the first letter of each subsequent word,
02:19like the hump of a camel.
02:21Now, some other languages separate multiple words with underscores and functions
02:27are named the same way.
02:29With functions, you typically use multiple words for clarity like
02:33calculateDistance, often in a loose verb-noun format. checkFormFields.
02:39You'll see that the internal functions inside JavaScript use this format too.
02:43createElement, appendChild, getElementById.
02:49Now in other languages, their style guidelines might suggest to use underscores
02:55to separate words instead. Or if they're strongly typed, they might suggest you
02:59prefix your variables with an abbreviation that's meant to represent the type of
03:03information in that variable like a string or an integer.
03:06And if you work in those languages, yes, use their typical style.
03:11But CamelCase is the dominant style for JavaScript.
03:14It's what's recommended by the Yahoo! style guidelines, the Google style guidelines.
03:19It's what's used by the popular JavaScript language like jQuery and Prototype
03:24and it's what's used by the built- in JavaScript DOM methods themselves.
03:29Now another style issue is something called brace style, literally where to put
03:33the opening and closing curly braces and how much to indent your code.
03:38Now, the dominant style in JavaScript is the most traditional brace style
03:42for C-based languages.
03:43If you have an if statement or a while loop, the curly brace will open on the
03:48same line as the keyword, as the if or the while.
03:51Your code is indented inside the block and the closing curly brace closes on a
03:56line by itself matching up with the keyword.
03:59Now if you're using if and else, you'll typically see else written on one line
04:05with both the closing of the previous block and the opening of the next.
04:09Now there are other ways.
04:11There are things like Pascal or Allman style where the opening brace is put on
04:15its own line and it lines up with the closing brace.
04:19This is very common in languages like C#.
04:20But with JavaScript, for its whiles and its ifs and its functions, for all of
04:28these constructs, open the curly brace on the same line as the keyword.
04:33And as we've seen, functions should be defined before they're called.
04:38So if you have code that you know is calling a function later on in that file,
04:44rearrange them to make them easier to read and easier to understand.
04:49So to review this, some simple rules to keep in mind.
04:52We use CamelCase for variables, functions, and methods; you open curly braces
04:57on the same line; you define your functions before you call them; always use
05:01semicolons to end a statement even if in JavaScript you don't have to; always
05:07use var when declaring a variable.
05:10Because JavaScript is a flexible language, it's easy to write sloppy code that still works.
05:16Sure, JavaScript will sometimes let you be sloppy, but don't be sloppy. So always use var.
05:22Pretend that var is required.
05:24Now we can go deeper than this with style, but that's enough to get started.
05:28If you want to go deeper and more formal, do a search for JavaScript style
05:32guidelines and you can find some good documents that have been created by the
05:37JavaScript developers at places like Google and Yahoo!
05:41Or search for available style guidelines for any other language you might be
05:44interested in and compare and contrast them.
05:47But the real point with any style is simply to be consistent about the way
05:52you write your code.
Collapse this transcript
Writing pseudocode
00:00It's really easy for people to get stuck.
00:04They want to write a program and they start off looking at a blank text file and
00:08they're thinking so much about syntax and case sensitivity and curly braces and
00:13all the thousand other things to remember,
00:15that it is very easy to now, actually know, how do I start typing?
00:17Well, step one is don't.
00:21Step one is instead get away from the computer, grab a piece of paper or find a
00:26whiteboard and start writing what's called pseudocode instead.
00:30Now pseudocode is not a language.
00:33It's the term for writing your computer instructions in plain English to the
00:38point where it's readable by anyone who understands the problem, whether they
00:42come program or not.
00:43Let me show you a few examples.
00:46On a whiteboard or paper I might just write something like this. Ask user for email address.
00:52If email address matches accepted pattern, add them to email list, else
00:57show error message.
00:58Something like this.
01:01Pseudocode doesn't have formal rules, but this would be quite common to see.
01:05Now where I'd said, ask user for email address, I could've said get email
01:10address or prompt for email address or if I really wanted to break it out I
01:15could even say create email variable, ask user for email address, store user's
01:20email address in email variable.
01:22Now that would be a little long. Or I could just say get email.
01:26I'm just trying to define the structure of this code, what has to happen in my problem.
01:32Now it's quite common to see programming keywords like if and else and while
01:38and for, but it's whatever makes sense. And you'll also see pseudocode often
01:42indented like I've done here, and like any indentation it just makes it easier
01:46to follow the structure.
01:48And different people write pseudocode in different ways.
01:51The longer someone's been writing a language, the more their pseudocode tends to
01:55take on the style of that language.
01:57Sometimes you'll see pseudocode written partly in uppercase like this, and it's
02:02quite common to see people explicitly marking where an if or a loop ends using
02:07a phrase like END IF or END LOOP, and it's just serving the same purpose as a
02:11closing curly brace in JavaScript or another C-based language. But there are no rules.
02:17The point is clarity and understanding.
02:20Can you read the pseudocode?
02:21Does it make sense?
02:24Here's an example perhaps of going through a whole list of numbers and
02:27adding them together.
02:28We start off with set total to zero, get a list of numbers, loop through each
02:32number in the list, and add each number to total, remark where the loop ends.
02:36If number more than zero, print its positive message, else print its zero or
02:40last message, end if.
02:42It's the kind of thing that should make sense whether you can program or not.
02:45Now if you start worrying about pseudocode syntax, it's kind of missing the point.
02:50The whole point of this is to get away from that, where you don't have to worry
02:53about braces, parentheses, brackets, off by one errors, naming conventions.
02:58It's whatever seems natural.
03:00Now it doesn't necessarily break down perfectly to one line of pseudocode, one
03:05line of real code. Sometimes one line of pseudocode like send email can cause
03:10several lines of real code.
03:13One of the best things about pseudocode is it lets you think about your problem
03:17without necessarily knowing exactly how to code it and it exposes where you need
03:21to go and learn something. Because I can describe a problem in pseudocode
03:25without having the necessary knowledge in that language.
03:28Let's say I'm trying to build a game and I know how to work with images.
03:33I've been programming some of it already.
03:35So I might write some pseudocode code like this.
03:37If a missile-image touches the spaceship -image, well, I'm going to replace this
03:41spaceship-image with the explosion-image.
03:42I want to play an explosion sound and then I better check,
03:48is the remaining-lives counter zero?
03:50Because if it is, they don't have any lives left, so I'll show the "game over" message.
03:55But if it's not zero, I'll subtract one from their remaining lives.
03:59I'll show begin message, I'll reset the spaceship to the starting
04:03position, etcetera, etcetera.
04:05Now I'm not saying this is necessarily the perfect pseudocode for a game, but
04:09we're following the steps here.
04:11But let's say I don't know how to play a sound in the language that I'm working with.
04:16It doesn't matter.
04:17I can still build my pseudocode.
04:19I can still write this problem out, because I know that sound has to happen.
04:23I can just put it on my personal task list for something to look up and find out how.
04:28I just write down "research how to play short sound effect."
04:31Go and figure that out and later I can come back and code this.
04:34So pseudocode is not just for beginners. Many very experienced software
04:39developers I know still work out a lot of their problems in pseudocode as a way
04:43of better understanding it without worrying about syntax, and it's a great habit
04:48to get into to start sketching out your programming ideas in plain English
04:52before you write code.
Collapse this transcript
10. Input and Output
Input/output and persistence
00:00Programming is all about input and output, but what that means has changed over the years.
00:05You go back a few decades and the idea was simple.
00:09The only programs we used were what were called batch programs.
00:12You started the program like it was a food processor. You'd be giving a file of
00:16data for input, you'd let the program process all of it and spit out the results
00:21to another file or even directly to the printer, and then the program stopped.
00:26You did not interact with the program as it was running.
00:29The closest thing to this for most people now is a few command line programs or
00:33the occasional utility like doing a full virus scan of a hard drive.
00:37Things which are designed to run and finish as fast as possible, but instead the
00:42shift is to programs that run with graphical user interfaces.
00:46Things like a web browser that don't just start and run all the way through and
00:50stop as quickly as possible, but they are programs that stay up.
00:54We can interact with these continuously and unpredictably over hours or
00:58even days or even weeks.
00:59And with these input and output is a bit vague.
01:03Well, yes, a mouse-click is input, something typed in a webpage is input, and
01:07changing an image on the screen is output.
01:10But that doesn't really feel the same as saving and loading files, because
01:14sometimes we still want to be able to save documents to the hard drive or load
01:19files from the hard drive or save information to the web.
01:22So describing just everything as input and output becomes a little generic.
01:27So when we talk about really saving information, running a program that then
01:32saves information to our documents folder or saves to a database or saves to
01:37the web or saves to a cloud,
01:39and I mean data that outlives the currently running program, meaning that we
01:44could close the program and that data would still be on the drive or in the
01:48database or in the cloud, then we use the term persistence. And we also refer to
01:53this as saving the state of a program. Because without deciding to persist,
01:58our data it all just disappears.
02:01All the variables we've worked with so far are just stored in the computer's
02:04volatile memory in RAM while the program is running and when we close the
02:09program everything is gone unless you plan otherwise.
02:12But here's the issue. Different programming languages support persistence in
02:17different ways and JavaScript not very much at all.
02:20There are no words in JavaScript to save a file to the Documents folder. You can't do it.
02:25Now that's by intention. JavaScript was designed to be embedded in webpages.
02:30You just don't want all the webpages you've ever viewed being able to save files
02:34directly to your hard drive.
02:36So for security those words were never built in to the JavaScript language.
02:40Now languages that are more geared to desktop development or mobile development
02:45or even mainframe development do have built-in ability to write code to save
02:50or load files to the hard drive.
02:52They often have a variety of different words to do this and we'll talk about a
02:56few of these features shortly, but first let's take a look at what JavaScript
03:00does like to do for input and output if it can't load and save files.
Collapse this transcript
Reading and writing from the DOM
00:00JavaScript is a scripting language, not a general purpose programming language,
00:05and its world is the webpage that loaded it, not your operating system, not your hard drive.
00:11Instead, it has some great functions for grabbing and manipulating what's on the webpage.
00:17JavaScript is using something called the Document Object Model or the DOM to do this.
00:22Now, I can't talk much about the DOM without also talking a little bit about
00:27HTML and webpages in general.
00:29So while the next few minutes by itself is a little specialized to be something
00:33I'd call a general programming fundamental, well, that's not really about this.
00:39It's the bigger picture here that's important.
00:41And the idea which is fundamental is that the languages you use become
00:46specialized to the world that they work in.
00:49So if you work designing mobile applications, well you'll end up being able
00:53to write code to deal with what happens if the phone rings while your program is running.
00:59But you would not find that same ability when you're writing
01:02desktop applications.
01:03Instead, you might be able to write code to deal with the printer or the USB
01:08port because that would be your world.
01:11And if you work in JavaScript, you'll find yourself being able to write code to
01:15deal with the webpage.
01:17You see, we've been focused on using JavaScript so far to illustrate the basics
01:23of programming, things like conditions, iterations, arrays, and using these
01:29annoying alert boxes.
01:31But we know JavaScript doesn't run with alert boxes all the time.
01:34Real-world JavaScript is all about reaching from our script into the webpage
01:39that we have, and causing that page to reach back into our script.
01:43And we do that by understanding this thing called the DOM, the Document Object Model.
01:48Now, this is the term that's a little odd to understand the first time you hear
01:52it because it's kind of vague.
01:54People ask me, well, what is the DOM?
01:56Is it a language, is it part of JavaScript? What is it?
01:59Well, DOM is actually a pretty simple idea.
02:03And the best way to understand it is really to pull it apart into its
02:06three different words.
02:07Document, Object, Model.
02:09So we're going to take it apart piece by piece.
02:11We'll start with the first one.
02:13What do we mean by document?
02:16Well, if I'm in Microsoft Word, document might mean one thing, whatever I'm
02:20working on there, but we're not.
02:22We're on a webpage.
02:24For us, document simply means the page.
02:28Our JavaScript was loaded by a webpage and that page is the document as far as
02:33the script is concerned.
02:34But this document can be represented in different ways. It already is.
02:38We know this.
02:39We know that our page is written in HTML.
02:41So between the two here, which one will be the document?
02:44Well, both of them.
02:45One is the browser view, and one is the HTML code.
02:49It's perfectly allowable to have the same document with a
02:51different representation.
02:53It's the same idea here, but JavaScript perceives the same webpage a third way,
02:58Same document with a different representation.
03:00So if the current page is all we mean by Document, what's the Object part of
03:05Document Object Model?
03:06Well, Object here just means the different elements, the components, the
03:10pieces of this document.
03:11If I was to talk to a user, I could say look at the headline on this page, look
03:16at the bullet point list on this page, look at the whole page, or even look at
03:21the third letter in the second word.
03:23But if you're a web developer, I could use a different perspective.
03:26I could say look at the HTML, look at the h1 that represents the headline, look
03:31at the unordered list part, look at the whole document.
03:35All these things are objects.
03:37And yes, sometimes one object contains other object. That's okay.
03:40We'll have a way in JavaScript to get to every single piece, every object at
03:46whatever level that makes sense, from being able to grab the entire document to
03:51being able to grab the smallest piece.
03:54That leads us to the idea of the model.
03:56The model simply means what do we call these individual pieces and how do we
03:59describe the relationships between them.
04:02The model here is like a business model or a data model.
04:05It's trying to represent something complex by making it abstract, making it simple.
04:09It's simply a set of terms that we can agree on.
04:13Do we call these individual pieces elements or nodes or doohickeys?
04:17What do we call them?
04:18We all have to agree.
04:20What we end up with is that the DOM in JavaScript is an agreed-upon set of terms.
04:24That's our model.
04:26That describes how to interact with the pieces of a webpage.
04:30And that's a pretty long phrase, so we call it the Document Object Model.
04:35It is not a language, it's an idea.
04:37But it's an idea that JavaScript agrees on and that the web browsers agree on.
04:41So it's available there.
04:43Using the DOM, it lets us describe and interact with any webpage.
04:47Not any one specific page, but any webpage.
04:51When I know the basic concepts of the DOM, I could write some JavaScript that
04:54would say get the title text or get the second paragraph or get the third
04:59link in the menu and make it invisible, change the background color, get all
05:04the elements in the list, find an image and move it 40 pixels to the right,
05:08and a lot more besides.
05:10And that's why if we're working in JavaScript we'd need to know the DOM.
05:14It is the way to reach into the page from our script and the way our page can
05:17reach into our script.
05:19Let me show you just one quick example.
05:21In my folder here, I have the same old couple of files.
05:24I'm going to open up this HTML page first in the browser.
05:28It's a little different, not very from what I've been looking at so far.
05:32If I open that up in the text editor, I can see that one thing I've added here,
05:38and I'm looking at both different views, is this.
05:41I've added a headline.
05:43In the web browser, it shows up as this big bold Interesting Headline.
05:47In the HTML view, it's being represented by this h1 tag, and I've given it an ID of mainHeading.
05:55This is really like giving it its own unique label.
05:58Okay, so what's the point of this?
06:00Well, part of the idea of the DOM is that understand what it means to be a
06:04named element on a page.
06:06I can grab this headline if I know this name.
06:09So I'm going to leave the HTML here and go into my JavaScript.
06:15What I can do is create a new variable.
06:17I'll call it headline and I want to grab that part of the webpage.
06:22The way that I do it is using the Document Object Model.
06:25I will say well, it's part of the document.
06:27Document is an object that actually exists anywhere in my JavaScript.
06:31Then I'm going to say that I want to get a particular element.
06:35There's a built-in function here called getElementById.
06:41It's one of the most popular functions in the whole of JavaScript.
06:45I give it one piece of information, which is, what did I call it?
06:48Well, I called it mainHeading.
06:51And as soon as this line of code runs, I'll have this handle on that
06:55particular piece of the page.
06:56Then I can use this handle, this variable name, to say well, I'm going to reach
07:01inside of it, and set its own contents in our HTML to something new, "Wow, a new headline!"
07:10Okay, not the most exciting thing in the world.
07:12But if I save this, I jump back to my folder, and I run this page again,
07:17no alert box this time, but I can see that I'm immediately reaching into that
07:21headline, and actually changing the value of it.
07:24It's not changing my actual HTML.
07:26If I look at the HTML file, it still says Interesting Headline.
07:30But what's happening is the HTML was loading, it's bringing in our
07:34JavaScript, and immediately our JavaScript is reaching back and changing the
07:39contents of this headline tag.
07:41And sure, while this by itself might not set your world on fire, if we can
07:45affect the headline, we can affect anything.
07:47We can change colors, we can change text.
07:49We are creating the contents of this page through our JavaScript.
07:54All programming languages have an area in which they become specialized based on
07:59the world that they're working in.
08:00When you're a JavaScript developer, knowing the DOM and learning the DOM, being
08:04able to navigate through the page, is the single most important skill for being
08:09proficient in that language.
Collapse this transcript
Event driven programming
00:00Right now all our code executes as soon as the page loads our script file.
00:05It runs through it as fast as possible and finishes.
00:09But that's not good enough anymore.
00:11What I want to be able to do is start to react to some input from the user.
00:16And by input, I don't just mean prompting them for their name, but just being
00:20able to react to a whole bunch of different things.
00:23Does the user clicks somewhere on the screen, does the user resize the window,
00:27do they move the mouse? What do they do?
00:30What I want to do is start responding to events.
00:34This is what's called event-driven programming.
00:37And the ability to do this is built into most languages now,
00:40including JavaScript.
00:41Now here is the great thing.
00:43These events are already happening and they've been happening all along.
00:48When the page is loaded, that's considered an event.
00:51When the user clicks somewhere on the screen, that's another event.
00:54When they move their mouse, that's a whole bunch of events.
00:57When they scroll the screen up and down, that's an event.
01:00If they click into a text field, that's an event.
01:03As they're typing, every key press is another event.
01:06When they leave the form, it's another event.
01:09So these events are going on all the time.
01:11Your job as a programmer is to say, which ones do I care about?
01:16And the way that we can do this is by writing some functions and then saying,
01:22instead of just running this function when the page loads, only run it when the
01:26user clicks a button or moves their mouse.
01:31Now we don't have to keep asking, if the user is pressing their button.
01:36The operating system is going to take care of that.
01:38We just need to say what events do we want to react to?
01:42We write what are called event handlers or event listeners.
01:47We can pick our own term there.
01:49That just means a function that's waiting for an event to happen.
01:54These events are all part of JavaScript and there are special words to describe them.
01:59And they're typically written all lowercase and they begin with the word on,
02:03like onload, onclick, onmouseover, onfocus, onblur.
02:08And what we can do is write functions and hook them up to these events.
02:13You can have one event call multiple functions; you can have one function being
02:18called by multiple events.
02:19It's up to you how you start to wire them up.
02:21There are several ways to handle an event in JavaScript.
02:24For our purposes in this course, I'm just going to talk about one because we're
02:27trying to illustrate just a general principle here.
02:30And the basic idea in any language when working with event-driven programming
02:34is there are two pieces of information that you need: what's the event and what do you want to do.
02:39But bear in mind that with events, they can happen on different pieces of the
02:43page, different pieces of your user interface.
02:45It's the idea of a click event, but that could be a click event on a button or a
02:50click event on an image or a click event on some other part of the screen.
02:53So the general format in JavaScript is not just the event name but
02:57element.event name.
02:59what element and what event.
03:01So you'll have things like this:
03:02window.onload, the load event of the window object.
03:07The window here represents the browser window.
03:09This is an event we can react to when the page loads.
03:12If I have say a complicated form with lots of text fields to fill out, we could
03:17have something like this: nameField.onblur.
03:20The onblur event happens when I leave a field. Say I'm typing my e-mail address
03:25and I click out or hit the Tab key. This event will be called.
03:29This is one of the most common ones: myelement.onclick.
03:32Now what I've called myelement here?
03:34I'm presuming that I've created somewhere using the DOM.
03:37I've grabbed hold of it.
03:38I have a variable that represents an element on the page, whether that's an h1 or
03:44an image or a paragraph.
03:46Then I say .onclick and then I have to say, okay, that's the event, so what do I want to do?
03:51Well, the typical format is this. We actually create a function here.
03:56And we've seen this before. The idea of the word function, followed by
03:59parentheses, followed by the opening and closing curly braces.
04:02Now usually when you say the word function, you also give it a name.
04:06You're creating a function giving it a name.
04:08We're not doing that here.
04:09This is what's called an anonymous function.
04:12This is actually very common in JavaScript.
04:14It might look a little odd, but all it means is a function without a name. It's synonymous.
04:19Well, we know that the function is really just a bunch of code wrapped up.
04:23That's all we're doing here.
04:24We're using the word function saying when this event happens, run whatever is
04:28inside this block of code.
04:30I don't need to name this function because naming it would be a waste of time.
04:33I'm saying exactly what it does and I'm saying exactly when it's executed.
04:38Tight here on the click event of whatever my element is.
04:41Now if you start reading more JavaScript, you're likely to see one thing that
04:45looks a little different.
04:46Usually when I declare a function, I just have the opening and closing curly braces.
04:51When you see this format, you'll typically see the semicolon after the
04:54closing curly brace.
04:56It looks a little unusual because we don't need that after a closing curly brace
05:00for an if statement or a while or even a usual function.
05:03And in fact here, we're putting that semicolon not because this is a function,
05:08but because the entire line is a statement:
05:12myelement.onclick = this function and whatever is inside it.
05:16So let me show you an example.
05:19I've got an identical two files that I had earlier.
05:22A very basic HTML page with a headline which has the ID of mainHeading.
05:28And that's my name that I just made up for that section.
05:32And then script.js, which I brought over from the previous one.
05:36What this is doing right now is grabbing hold of that headline by using
05:42document.getElementById.
05:44We're using the DOM here.
05:45And right now, it's actually changing that immediately.
05:48But I've decided I don't want that to happen immediately.
05:51I want to start reacting to events.
05:53I only want to call this line if they've clicked the headline.
05:57So here's what I'm going to do.
05:59I know that the first line of code that's executed grabs hold of the headline
06:03and then I'm going to say headline.onclick.
06:07I'm going to set up an event handler for them clicking the headline. Equals, and
06:11we're going to write an anonymous function, the word function, opening and
06:14closing parentheses, and the opening and closing curly braces.
06:18I'm going to put my semicolon in here.
06:21It would work without it, but this is the best practice.
06:24Now I'm going to grab this line of code that sets the inner HTML, the actual
06:30text value of this headline.
06:32And I'm going to paste it indented inside this anonymous function.
06:37Change this message one little bit, to "You clicked the headline."
06:43I'll save this and I'll open up the webpage that contains it.
06:49Now we're finally having code that doesn't immediately run.
06:54We're not changing the value of the headline yet.
06:56It's going to wait until we click on it.
06:58So events are actually happening.
07:00When I move the mouse, that's considered an event.
07:02If I resize this page, that's considered multiple events.
07:07But I didn't say I cared about that.
07:09The only one I care about is the click event on the element called headline,
07:14which means the only thing that's going to react to, it's no click events
07:17anywhere else on the page.
07:18I can all over the page right now.
07:20But if I click on the headline, we'll change it.
07:23We're now reacting to that.
07:25And this is the great thing.
07:26With very little code, we're now allowing the page to call back into our script.
07:32We've got an event-driven program that's communicating two ways, between our user interface,
07:37the visible part of our webpage, and our code behind the scenes.
07:41A simple example here, but it's illustrating a really powerful principle of
07:45event-driven programming.
Collapse this transcript
Introduction to file I/O
00:00It's a very common requirement to have a program need to read files on the hard
00:05drive or save files to the hard drive to persist information there.
00:10But this will be a pretty short movie if I was trying to show you how to do
00:13this in JavaScript.
00:15And again, because of security, it just doesn't do that.
00:19Now before I get a few emails telling me about a non-standard JavaScript desktop
00:23implementation or the file API of HTML5, I'm talking here about typical standard
00:30JavaScript as used on a normal webpage.
00:34This does not let you write code that just reads files off your hard drive or
00:39saves files to your hard drive.
00:41But seeing as I believe this is an important subject to talk about in the
00:45Fundamentals course I'm going to talk a little bit about file input and output.
00:50I'm going to start with couple of pseudocode examples and then show what it
00:54might look like in another language, because here's the thing.
00:58File input/output, File I/O, can actually be a little tougher than it first
01:02sounds, because to read the most basic of files, we need to know the path, we
01:08need to open the file, we need to read the contents of the file, and we need to close it.
01:12So if I just wrote this as simple pseudocode, we'd say open file at path myfile.txt.
01:18This is allowing us to grab hold of it, to treat it as ours.
01:22Then I could read the contents of the file into a string variable and then I do
01:27need to close the file.
01:28It's always a rule to close the file when you're done with it.
01:31But here is the issue.
01:32There is a whole bunch of ways this could go wrong.
01:35What if there is no file at that path?
01:37What if some other program has that file already open?
01:41What if they've already grabbed it?
01:42What if that file is huge?
01:44Can we just read it all into a string variable?
01:47And you'll often find that dealing with file input/output, there is a lot
01:51more conditional code going on just to check all the things that could possibly go wrong.
01:56But let's say we're not going to worry about it.
01:59Let's say we just want to read in a small text file that we know exists.
02:04Well, here's an example using the programming language Ruby.
02:07And as usual, don't worry too much about the syntax.
02:11It's not what we're focusing on here.
02:13Just the overall approach.
02:15Can you scan this code and see where the file path is?
02:19Can you see where we're probably opening the file?
02:21Can you see where we close it?
02:23It's not about whether you could turn around and write this down yourself.
02:26It's about that you understand the general approach here.
02:29So this will open the file called simpleexample.txt.
02:33Because I didn't put any other path information here, this file should be in the
02:37same folder as the program itself.
02:39Now the next line, we have File.open using that filename.
02:44And we're using this r in quotes here.
02:47This r means open this file in read-only mode.
02:51If we wanted to open this file so we could write to it, we could use w, or for
02:56both reading and writing, we could say r+.
02:59Now it's very common for different programming languages to support opening
03:04files in different modes.
03:06One mode for reading, another mode for writing, another mode for read and write.
03:11You might have a mode for overwrite this if the file exists already or another
03:16mode for append to it if the file exists already.
03:19These are all very common.
03:20And we choose modes because it's helpful.
03:23Opening a file in read-only mode has less impact on the system and it allows
03:27other people to open it too.
03:29Then we've got a couple of curly braces being used.
03:32Yes, it's not exactly the same as a JavaScript block, but it does appear to be
03:36some kind of container.
03:38What this is doing is reading each line and using puts, p-u-t-s, which is put
03:44string in Ruby to display each individual line.
03:49Then on the last line we're saying f.close.
03:51We're actually closing the file that we opened on line 2.
03:54So here's an example in Ruby of writing a string out to a file.
03:59So we start off by creating a string called message.
04:02Again, it doesn't look exactly the same as a variable in JavaScript, but close
04:06enough that we can understand what's going on.
04:08Same thing with the filename = 'myoutput.txt'.
04:12Then we call File.open.
04:13I'm using a slightly different format here.
04:15I can see that I've got the w, which is open in write mode, and the last line we
04:21have here is this end.
04:22What this is going to allow us to do is have an automatic close of the file that
04:27I opened a couple of lines beforehand.
04:29Again, don't worry about the syntax.
04:32just get the overall approach here.
04:34We need the path, we need to open the file, we need to write the contents, we
04:38need to close the file.
04:40Now I will say here Ruby is one of the simplest languages for reading and writing files.
04:46If I'd shown you these examples in C++ or Java or C#, we would have had a lot
04:52more lines to deal with.
04:53Now there's a big difference between reading a typical text file and reading a
04:57file of binary data like audio or video.
05:01It's very common when you start working with files that you'll find yourself
05:04needing to break things up a bit.
05:06In most languages you rarely read an entire file at once unless you know
05:11it's going to be small.
05:12Instead, you read the file one chunk at a time.
05:15You break it up into pieces.
05:17One example would be that rather than reading a text file all at once, you
05:21process it one line at a time.
05:24Some pseudocode here might be that we open the file at the path myfile.txt and
05:29then we're going to have a loop that says while the file has lines left, we will
05:34read one line, we'll display that, and then we'll end the loop.
05:37We'll loop around again.
05:38Does it still have lines left? Yes, it does.
05:41We'll read another line, display that line, and just go piece by piece
05:45through the entire file.
05:47Then finally, we'll close the file.
05:49And if we're opening the file, we close the file.
05:52With many languages, even higher-level ones like C#, Java, and Objective-C, you
05:57can end up working with files by working with what are called streams.
06:00The idea of a stream is quite simple.
06:03It just means a stream of bytes like a conveyor belt of bytes.
06:07And it can sound complex, but it really isn't. When working with streams, we just
06:12get to take them one chunk at a time.
06:15And they're great because they allow you to stop caring where this data actually is.
06:19You don't really mind anymore.
06:21Is it on a file on your hard drive? It could be.
06:23Maybe I'm reading it off a network, off a website. It doesn't matter.
06:27It's just a stream of data that I need to deal with.
06:31But a typical task for a programmer new to any language is finding out how that
06:36language likes to work with file input and output.
06:39You'll find that most languages deal with the same concepts in slightly
06:43different ways, but they all have substantial built-in functionality for reading
06:48and writing different kinds of files.
Collapse this transcript
11. When Things Go Wrong
Introduction to debugging
00:00When you're new to programming, it's usually difficult to write even a single
00:04line of code that works correctly.
00:06Programming languages are so specific and it's very easy to use the wrong case,
00:12to use a colon instead of a semicolon, to miss a closing quote, to use the wrong
00:16operator, the wrong name.
00:18when you write programs that aren't trivial, once you get beyond hello, world,
00:23it's really tough to write more than a few instructions without tripping up
00:26over your own logic.
00:28So yes, you expect your code to work and it's natural to get frustrated when it
00:32doesn't, but here's the thing that experienced programmers know that non-programmers don't.
00:38We don't expect our code to work anymore.
00:41Seriously, we don't ever expect to just write a program that works correctly the
00:46first time through. Our code still breaks all the time.
00:49You see programs aren't just written. They are edited into existence, they are
00:55built slowly, piece by piece and every programmer expects to spend far more time
01:01debugging their code than actually writing their code.
01:04We write a few lines, we check it, we fix it, we then write a few more, we
01:09check them, we go back and fix the first ones we just broke, and we keep
01:13repeating the process.
01:15The thing is yes, it is easy to make mistakes, so don't worry about making mistakes.
01:21Go make a thousand of them, and then fix them, then make a few more.
01:24Now, we're going to debug our code. We're going to find out what went wrong and
01:29we're going to fix it.
01:30I am talking here of everything from just getting your program to run in the
01:34first place to six months down the road, you thought it was working fine but
01:38you're getting some odd behavior.
01:40So how do we start to think about this?
01:44When we have errors in our code, they really break down into two main categories.
01:49The first and most obvious are syntax errors and then we also have logic errors.
01:54So let's talk about the difference.
01:57The most obvious kind of problem is with syntax. Something is wrong with the
02:02actual format of what we wrote.
02:05You spelled a keyword with the wrong case letter, you used a colon instead of a
02:10semicolon, you forgot to close a quote on a string, and if it's that easy to do
02:16it on the simplest statement there is, just think about what it's like when
02:19you've got a lot more code, thousands of lines of this.
02:23Even experienced programmers will from time to time just have to go through
02:27letter by letter figuring out, what did I miss here?
02:31It's quite common to count the opening and closing curly braces to make
02:35sure that they match up.
02:36Now, one of the benefits of using programmer's text editors and having things
02:40like syntax highlighting is it can point some of these things out.
02:44Let's say I am working in an editor and I know that green means a comment.
02:48So if I see a big block of code like this, I can immediately think, hang on,
02:52there's a problem here, and what I can see is I accidentally opened a multi-line
02:56comment, making everything after this an actual comment, whereas what I wanted
03:00was a single line comment that looks like this.
03:03So color coding can really help when you're just scanning your code to
03:06find syntax problems.
03:08But these are the kind of problems you will do less of as you get familiar with
03:12any language. You will still make them but you will make less of them.
03:16One of the benefits of using a compiled language rather than an interpreted
03:20language is these syntax problems are found before you even try to run the
03:25program, because you have to run your code through a compiler. But with an
03:29interpreted language like JavaScript, you often have to attempt to run it to
03:33find out what's wrong.
03:35Then we have logic issues.
03:37These are really the main problems for any program and this is where the code
03:41you wrote is correct in syntax and if you're working in a compiled language, it
03:46will even compile, but there is a flaw in the logic.
03:49The fencepost error that we talked about early in the course is one small
03:53micro-example of a logic error.
03:56You've got a loop that just isn't going round enough times.
03:59It's one time too many or one time too few.
04:02Another example would be creating a function and that might have a lot of code
04:07in it but somewhere in the middle, you've got a return statement.
04:10Well the problem is, if you hit a return statement and a function, you'll
04:14immediately jump back out of the function into whoever called it, which means
04:19any lines after the return statement would never be executed. And these are just
04:23three very obvious examples of logic errors. The problem with most of them is
04:28that they can be extremely difficult to find.
04:32There are some logic errors that even fall into their own category like
04:36problems with arithmetic.
04:38What do we mean by this?
04:39These are also correct in syntax but they just don't make sense.
04:43So if I create some code like this, a variable called a, set equal it to 100 and
04:48then var b = 0, var result = a/b. The syntax here is correct: the right case,
04:56the right operators, we have the semicolons.
04:59The problem is this doesn't make sense.
05:02a/b here is 100/0. Divide by 0 is not allowed.
05:09It logically doesn't make sense, so the computer can't do it.
05:13Now, in JavaScript this might just get you a weird message from the alert statement.
05:17But in many other programming languages, the line that tries to divide by 0 will
05:22cause your program to crash completely.
05:24And yes, these are just a few examples of the things that can go wrong.
05:28The logic errors will be the most significant problem you'll ever have as a programmer.
05:33But in any debugging situation, the first step is always reproduce the problem.
05:38Does the same error occur the same way each time?
05:42Hopefully it does, because that's going to make it easier to find.
05:46After this, we need to figure out where in our code the problem actually is and
05:50that can be more difficult than it seems.
05:51For that, we need to figure out if our program is actually running the way we think it is.
Collapse this transcript
Tracing through a section of code
00:00So let me show you a simple low-tech way of debugging some JavaScript code and
00:05this concept also works in other languages.
00:08I am going to open up an example file of JavaScript that I have.
00:12There are a few lines here but there's not a lot of complex stuff going on,
00:15we've talked about every single piece here.
00:17I am defining four functions at the top of my JavaScript.
00:21firstFunction, secondFunction, thirdFunction and fourthFunction and they're
00:25basically just calling each other in order.
00:28The reason that I am doing this is I want to follow a flow.
00:31The final function will actually change the HTML of the headline.
00:35So the functions that are defined when the page loads, these won't be executed, but
00:40it will know about them.
00:42The two lines of code that I will run is this one where I am grabbing that
00:46headline element and then I am adding an event handler to it.
00:49I am saying when somebody clicks the headline, call firstFunction.
00:55firstFunction should call secondFunction, secondFunction should call
00:57thirdFunction, thirdFunction should call fourthFunction, and fourthFunction
01:01should change the value of that.
01:03Yes, this one is a little convoluted, but that's intentional, because here's the idea.
01:09There is a mistake here but let's say I don't know where it is.
01:12I am going to run the page.
01:14It looks okay. And then I am going to click the headline and expect it to
01:17change, and it doesn't.
01:20No matter how many times I click it, I have no idea why it's not changing.
01:26So how do I fix this?
01:28Well, let's go back into the JavaScript.
01:31I don't know if the problem is in my event handler. Maybe it's not even calling
01:35firstFunction, but maybe my problem is in the firstFunction, or maybe it's in
01:39secondFunction or in thirdFunction or in fourthFunction. Maybe I am even
01:44grabbing the wrong headline element. I have no idea of what's wrong here.
01:47Perhaps my HTML page is not even pointing to my JavaScript file. So here's the
01:52really low-tech way of dealing with that.
01:55I do believe that this line should be being called as soon as we load the
01:58page, but maybe it isn't.
02:00How can I prove it?
02:01Well, one way is pop-up an alert message.
02:06Save this, go back over, open the page up.
02:09Okay, we're getting our alert message. I'm in the file.
02:12I know then for sure we are actually pointing to this JavaScript file and the
02:16code at least is getting here.
02:18I could leave that in or I could take it out.
02:20Well, I still don't know perhaps if this event handler is working. Maybe I've
02:25done something wrong here.
02:26I am going to add another alert.
02:28I could have done it before the call to firstFunction or I could add it after.
02:35Save that again, go over, and what I can do here is just refresh the page.
02:41Bear in mind, I've reloaded, I am not getting an alert message, but that's okay,
02:45because this is my event handler.
02:48It shouldn't happen until I click the headline, so let's see what happens. I click it. Nope.
02:54I am not getting anything going on here.
02:57But that itself doesn't necessarily prove that the problem is here, because
03:02think about what happens. I am trying to call firstFunction, which itself calls
03:06secondFunction, then thirdFunction, then fourthFunction, then this one and after
03:13each function is called it will return control to the previous one to go back up
03:17the stack, back here.
03:19What I really want to do here is start to put in another alert message and this
03:26is very common, that tells me in this case, just about to call first function.
03:32Now, I am going to save this, refresh this page. Now I click the headline.
03:41Okay, so I know I am getting in the event handler.
03:43I am just about to call first function. I did then go into this line. Something
03:49happens between this alert and this alert, so something is certainly happening
03:54in the chain of calls here.
03:56Now, this as I mentioned is a very low-tech way of doing it.
03:59It's what referred to as tracing.
04:01We're actually injecting messages, we are outputting some information
04:05saying yes, we got to this point, we got to this point, we got to another point,
04:09and it's quite common that what ends up happening is there's a lot of trace messages.
04:17In fact, some languages even have the word trace.
04:19We're going very low-tech with JavaScript and I could put in some more messages here.
04:29Let's indent this properly just to make it readable. And yes, I am going a
04:33little bit overboard here to prove the point, that I am putting in an alert
04:37message before just about every single thing that I do.
04:40But if I save this, then what I can do here is by refreshing the page, I
04:46can follow the flow.
04:47So I click the headline. I'm just about to call first function, looks good, just
04:53about to call second function, okay, just about to call third function.
04:57We're looking good, we're looking like we're going all the way through, just
05:00about to call fourth function. Great!
05:03Okay, so what happened was I got this trace, I got this trace, I got this trace,
05:13but I didn't get this one.
05:15So something happened after this alert message. Say we call fourth function.
05:20And I should have just jumped in here, but as I am looking a bit closer to it I
05:24suddenly realize, oh, I have got a typo.
05:28The name of the function is fourthFunction with an uppercase F of Function. This one isn't.
05:35Here's where the problem is. We never got into the fourth function.
05:39So now I am going to save this, jump back over, refresh the page, click the
05:45headline, follow the traces, first, second, third, fourth, just about to
05:50change the headline, and then we change the headline and then it finally comes
05:54back and said yes, now the control had been returned all the way back to our event handler.
06:00Now our code is working and the really tedious thing is I have to go back and
06:05take out all these messages, what are typically referred to as trace messages.
06:09Yes, we're using an alert to do it but the concept is what's known as a trace.
06:14I could also comment them out if I thought that I wanted to leave them there for future use.
06:21Following the flow of your program by doing this, by doing trace messages
06:25often referred to as logging to the console as well, is a very, very common way of doing this.
06:31And while it can be a little tedious, you often find that you'll actually
06:34discover the bugs as you're putting in your trace messages.
06:38It is a low-tech technique, but one of the benefits of it is it doesn't
06:42require any special tools.
06:44It doesn't require special debugger programs or you to do anything other than
06:48add a few lines of code into your program.
06:51But it wouldn't be something that I'd necessarily want to do in 10,000 lines of code.
06:56So for that, we have great programs called debuggers that can help us go through
07:01our code line by line as it's running and we'll see those in a moment.
Collapse this transcript
Understanding error messages
00:00Most programming languages will end up bombarding you with error messages when
00:04you're writing your code.
00:05This might be annoying, but you actually want this. You want it to tell you what's wrong.
00:10JavaScript is one of the few areas where we don't get automatically bombarded
00:14with error messages about syntax and that's because of the nature of where it's used.
00:19If you have errors in your JavaScript and I'm looking at script with exactly
00:23the same problem here,
00:25it's not showing up by default in the web browser, because you don't really want
00:30every user who is on your website seeing all the errors you might have
00:33accidentally put into your code.
00:35So most browsers do realize when there are errors in JavaScript, but they
00:40hide them from you.
00:41We have to tell the browser we want to see the errors.
00:45Now, each web browser does this a bit differently, but what I'm about to show
00:49you does have its equivalent in Internet Explorer, Safari, Opera, Konqueror, all
00:54modern web browsers, but I'm going to show it in Firefox, which is my preferred
00:58browser for debugging JavaScript.
01:00So I'm on Firefox 6.
01:02I'm going to go up to the Tools menu, and find the Web Developer area, and find
01:07this thing called the Error Console.
01:10Things do get rearranged, so you may find it under a slightly different menu but
01:13you're looking for the Error Console in Firebug.
01:15What will happen is it will pop up this separate window.
01:19I'm going to clear that and just keep that open in the background while I'm
01:24experimenting with the page.
01:25So it's not showing me anything right now, but as I move this page, I'm going to
01:29go around and say click on this.
01:32I click on Interesting Headline three times and over here in the Error Console
01:36I've got three errors.
01:37Now, it's actually telling me, the error is fourthfunction is not defined.
01:41Meaning, you're trying to use something called fourthfunction, I don't know what that is.
01:45In fact, I even have a link to the file where the problem is and it's telling
01:50me the issues on line 9.
01:51If I click the link, it opens up a view of that and even highlights the line for me.
01:57So I can go straight to that line and figure out, okay, there is the problem,
02:01and hopefully I see that it's because I'm spelling fourthfunction with a
02:05lowercase f, whereas the actual definition of the function uses the uppercase F
02:10for the word Function here.
02:12If you have other errors in syntax, you may find several of them showing up as
02:16soon as you load the page.
02:18General rule of thumb, if you've got multiple ones, go from the top down.
02:22Fix the first one first, because early errors can actually upset the rest of your code.
02:27Well, that's the Error Console in Firefox.
02:31There is also an option called the Web Console which is equivalent, but actually
02:37gives you this window at the top of the page and as I click in here, we get the
02:40same message. fourthfunction is not defined.
02:43This also gives you extra information about your HTML and your CSS and so on.
02:49New in Firefox 6 is something that they've called the Scratchpad, which is
02:53actually an area we can just type or paste in some JavaScript, and then run it
02:58directly from this Execute menu.
03:02As of when I'm recording this, this is still early days, but it might be a nice
03:06environment just to play around with some sample code.
03:08These things are really useful, but they will only take us so far. For anything
03:13that's a bit more involved than simple syntax problems, we need a real debugger
03:18and with Firefox, we can get that too.
Collapse this transcript
Using debuggers
00:00In all programming languages these days, there are tools that will actually help
00:04us to debug our code when it's a bit more complex for just a trace or a quick
00:09scan of the syntax to work.
00:11I'm going to show you a debugger in JavaScript just to show you the kind of
00:15things you'd expect from a debugger in any language.
00:18JavaScript of course is a language that lives in a web browser and that's really
00:23where our debugger needs to live to.
00:25What I am going to use is probably the most well-known debugger for JavaScript,
00:30which is something called Firebug.
00:33This is a free extension for the Firefox web browser, so it adds extra
00:38functionality into the web browser.
00:40And after it's been installed, you can turn it on for any page or any website
00:44that you are looking at.
00:45So I am looking at my page here.
00:47I'm going to go up to my Tools menu and turn Firebug on, just open it up.
00:52It opens up in the lower part of the screen.
00:54Although you can choose to open it in a separate window. You can adjust this and
00:59have more or less of your regular page if you want to.
01:02This is fine for me.
01:03Now Firebug is a general purpose Web development tool.
01:07It's not just a JavaScript debugger, but that's the part that I'm
01:10most interested in.
01:12So it has several different tabs I can get to.
01:15The only two I am interested in here are the Console, which is right now disabled.
01:19So I am going to enable it and it tells me to reload it and enabling the
01:24JavaScript debugger. I am going to reload, there we go!
01:27And also the Script section, which I'm also going to click the button to enable.
01:32Now as soon as I do that, what it's doing is showing me the actual script that
01:37this page is linking to.
01:38I have added a few more lines there but we will go through that in a moment.
01:41Now just for our purposes this font is a little small, so I am going to change
01:45some of the settings of Firebug and just zoom into that a bit more.
01:50So I can change the text size of what I'm looking at.
01:54And this should make it a bit easier to read.
01:56Now you might think, "Okay big deal, we can actually look at the code, but so what?
02:01I can already look at the code."
02:03Yes, but here is the thing.
02:05It's meant to diagnose problems.
02:07So if we've got the same problem that we had before, which is when I click the
02:11headline, it's not doing what I thought it should be doing, which is changing it.
02:15I can use the Firebug extension to help me find out why.
02:19And the classic example here is I can set a breakpoint.
02:22So if I think that here I should be calling firstFunction, I can set a
02:28breakpoint, which will say stop whenever you get to this line.
02:32What I do is click on the gray bar to the left of it. Well, then what?
02:37Oh, it doesn't look very impressive, but what happens of course is this should
02:41only be hit when I click up here, so I am going to click.
02:44And as soon as I do, the breakpoint is hit in our code and it says okay, I
02:50have paused execution.
02:51Usually what JavaScript would try and do is run through this code as quickly
02:55as possible, to call firstFunction and move into the code that's inside that function.
03:00But we said no, break, pause before it.
03:03So we get this little arrow that's pointing and saying okay, we are paused right
03:08before this line of code should be executed.
03:11Well, what is this line of code?
03:12Well, it's a call to something called firstFunction, which is defined up at
03:18the top of our code here. firstFunction is over there. It could be in a
03:21completely separate file.
03:24Now back down here what I'm going to do is say okay, let's start going
03:27through line by line.
03:29That's the power of a debugger: stepping through our code as it's actually
03:33running, not just looking at it on paper.
03:36So up here what we have is when we are in this break mode, we have got the
03:39ability to rerun code, to just hit Continue and just continue on to the next breakpoint.
03:45And we go to variety of Step Into, Step Over, and Step Out, which allows us to
03:52go into functions or jump out of functions.
03:55The one you typically use most of the time is this one called Step Into.
03:58I am going to click that button.
04:01And what it's going to do is execute this line of code, which should move us
04:06into the function called firstFunction.
04:08So I click it once. Jump.
04:11We jump into the first line of the function.
04:14Notice that we don't jump to line 2 where the actual function name.. It is because
04:18that's not really a statement.
04:19It doesn't do anything.
04:21We're jumping into the first bit of code, the first part of the function that
04:24actually does anything.
04:25We are just going to create a variable called a and set it equal to 5.
04:29But we are paused before this line is executed.
04:32So right now I can actually move over a and it's going to do this little tooltip
04:37that says does a have a value.
04:39And it says right now it's undefined.
04:41And in fact, over here on the right- hand side we have what's called the Watch
04:45panel, which says yes, as far as I know, there should be three variables in this
04:49function, a, b and c, and they're all undefined.
04:51None of them have values.
04:53So I'll go back up to my Play controls and I am going to say Step Into,
04:56which just goes forward.
04:58a is now equal to 5.
04:59We are waiting to create b. I Step Over. b is now equal to 10.
05:06I can see those values either in the Watch panel over here or by mousing over them.
05:11Now we are at line 5, which is going to be a call to second function.
05:15So what should happen is if I click Step Into, we will jump onto line 9 which is
05:20the first line of secondFunction.
05:22And indeed that's where we are.
05:23Create another variable, set it, make a call to thirdFunction, we jump to
05:29line 14, and to line 15.
05:31Now notice that we go from line 15 to line 17, when we have a blank line, there
05:36is no meaning there.
05:37We don't execute a blank line of code.
05:39It's insignificant whitespace.
05:42That's why it's also grayed out in the bar here, because it would make no sense
05:46to try and set a breakpoint there.
05:47Now one of the issues sometimes with stepping into your code and going though it
05:52line by line is sometimes it can be kind of tedious.
05:54We have got a while loop here.
05:56It's going to go around 100 times.
05:59Well, it might be a little annoying if all I had to do is just keep clicking and
06:03clicking and clicking and clicking and clicking and clicking.
06:06I can actually see my counter, i=16, total is 1600, and I have still got 84 clicks
06:11to go, so I really don't want to do that.
06:13So I will go ahead and I'll create another breakpoint here outside of the loop
06:20before we are calling fourthFunction.
06:22And instead of saying Step Into, I am just going to hit Continue.
06:27What happens is it zooms around the loop.
06:29I can actually go over here to the Watch panel and see that it did go around 100
06:33times and total ended up getting set to 10000.
06:36And then here's our call to fourthFunction in which we do have a slight problem,
06:41so I try and execute that.
06:42It's not going to work and in fact over here in the Console, we have got
06:46these problems here: fourthFunction is not defined.
06:50So what JavaScript did is it said "I don't know what to do, so I'm jumping back
06:54to where our thirdFunction was called."
06:56And now if I click Step Into, we are actually going to go back all the way up
07:00from secondFunction to firstFunction and then jump back to where it was called.
07:04And if I click Step Into one more time, what happens is we shift out of break
07:10mode because our event handler finished running.
07:12We're now back to the normal view.
07:14No JavaScript is running now.
07:15Now of course the debugger can get a little deeper than this, but if you think
07:19of these being the core pieces, allowing you to see your code as it's executing,
07:25being able to see the values of the variables as your code is running, being
07:30able to set breakpoints to jump into functions, to jump out of functions.
07:35That's the power of the debugger.
07:37One of the great things it allows you to do is just follow your code. Does it
07:40actually work the way you expect it to?
07:43These are the core pieces of a debugger and you will find them in every language.
07:47Most of the time, they're built into applications like Integrated Development
07:51Environments, things like Xcode or Eclipse or Visual Studio.
07:54But whatever language you use, you will find debuggers can be a tremendous help
08:00in clearing up problems with your code.
Collapse this transcript
12. Introduction to Object Orientation
Introduction to object-oriented languages
00:00Most programming languages developed in the last 30 years are what are called
00:05object-oriented languages.
00:06Now this wasn't always the way.
00:08My first programming job over 25 years ago was writing assembly language,
00:13FORTRAN, and COBOL on ICL mainframes.
00:16Now these languages were not object-oriented languages.
00:19They were instead straight procedural languages where the program really is
00:24written as one long procedure.
00:26Even though it might contain functions and subroutines to make it more modular
00:30and maintainable, it's really a long piece of code combining data and logic
00:35all mixed in together.
00:37Now in an object-oriented language, this program would instead be split apart
00:42into self-contained objects, almost like having several mini programs.
00:48Each object is representing a different part of the application and each object
00:53contains its own data and its own logic and they communicate between themselves.
00:59Now if that sounds like it could be a little bit confusing, the idea here is
01:04that these objects represent the way you would talk and think about the actual problem.
01:10It's meant to make thinking about your program easier.
01:13The objects don't represent mysterious abstract ideas.
01:17They first represent things like employees, images, bank accounts, player
01:22objects, car objects, whatever actually exists in your program.
01:26So object orientation is an idea and it's an idea that it's supported in many languages.
01:32And for you it's a shift to thinking about the objects in your program are
01:37not just the process.
01:39And while object-oriented programming can bring a lot of jargon into the table,
01:44there are really only a couple of terms we need to be comfortable with to
01:47move forward with it.
01:49The first two terms we need to understand is the difference between a class and an object.
01:54And these two terms go hand in hand with object-oriented languages.
01:58A class is a blueprint.
02:01It's an idea, it's a description, it's a definition.
02:04It describes what something is, but it isn't the thing itself.
02:08It's a well-defined idea, like say a blueprint for house.
02:11And classes will exist for different parts of your program.
02:15So if you are writing a restaurant review website, you might create classes that
02:19represent a restaurant and a review or a user.
02:23Classes could also represent visual parts of your program, things like TextBox
02:29and Button and Window.
02:30And they can also represent invisible things like dates and times and anything
02:35that can be a well-defined idea.
02:37A lot of languages come with many classes already defined, even advanced things
02:42like VideoPlayer classes, and you can also define your own.
02:46Now all classes describe and define two things:
02:51Attributes and Behavior.
02:54What are some things characteristics, its attributes, and what can it do,
02:58what's its behavior.
03:01So in this case, let's say we are describing a class to describe a person.
03:05We might say that the person attributes are name, height, weight, gender, and
03:09age, whereas the person's behavior is walk, run, jump, speak, sleep.
03:14Think about it this way that the attributes are really your data, your variables.
03:19And the behavior is what can you do, your functions.
03:22And actually attributes and behavior in most object-oriented languages are
03:27actually described with other names, which is properties and methods.
03:32These are the most common ways of describing these.
03:34But the class is describing these things in abstract.
03:39And what I mean by that is it says that a person has a name and it has a
03:44height, but it doesn't say what the name is because the class is just the
03:48description of something.
03:50But just like there's no point creating a blueprint if you never intend to
03:54make a house, there's no point defining a class unless you're going to make an object.
04:00So that's the relationship between the two.
04:03The class is the idea and the object is the thing itself.
04:07We create objects based on the class like creating a house based on the blueprint.
04:15Not only that, but you can create multiple objects based on one class in the same
04:21way you could create multiple houses based on one single blueprint.
04:25Now while there is a lot of jargon associated with object orientation,
04:30encapsulation is the key idea.
04:33This the idea that classes are self- contained units that represent both the data
04:39and the code that works on that data, that we take our properties and our
04:44methods and we box them up, we encapsulate them.
04:48JavaScript is an object-oriented language.
04:51Although it is quite casual with it, there are some other languages where object
04:55orientation is very formal and you can do very little without thinking deeply
05:00about classes and objects.
05:02So while some languages like C are not at all object-oriented, if you're working
05:07in Java, C#, Ruby, Python, VB.NET, Objective-C, you can't avoid object
05:14orientation in most modern programming languages.
Collapse this transcript
Using classes and objects
00:00The best way to start getting familiar with classes and objects is to begin by
00:05using classes that are already defined in your language and just creating
00:10objects from those built-in classes.
00:13We can later define our own classes and create objects from those classes.
00:17Now this sounds complex. It really isn't.
00:19In fact, we've already done it.
00:21So in JavaScript, when you make an array variable, you have made an object.
00:27When you make a regular expression variable, you've made an object.
00:30These are both built-in objects in JavaScript.
00:33Now on the other hand, when you make a variable that's a number or a
00:36variable that's a Boolean, these are not objects. These are what can be
00:40referred to as primitives.
00:43Primitives really just store a value. That's it.
00:47But as we've seen, when you have got an object, this is not just a
00:50dumping ground for data.
00:52When you have an array, you can ask things of it.
00:55They have properties like length and they have methods.
00:58We can ask them to sort themselves or reverse themselves.
01:01With regular expressions, we can call the test method on a regular expression
01:06variable to see if the pattern matches another string.
01:09They're smart and they have methods and they have properties.
01:12And that's what we mean by an object.
01:14One of the great things is they are independent of each other.
01:18Objects might be based on the same class, but I can have a thousand array
01:22objects and work with each of them separately.
01:24Now there are a few other objects in JavaScript.
01:28One of them is the Date object.
01:30This would be the way we would create a new Date object variable.
01:33Let's say var today = new Date.
01:36The variable today would now contain today's date, not as a string but as a Date object.
01:42We can create new Date objects with a particular data.
01:46And actually because this object definition stores time, we could even create a
01:51new Date object with a year, month, day, hours, minutes, seconds in it.
01:55Now you might think, but so what?
01:57Well, of course the great thing is these are objects. They have properties,
02:01and they have methods.
02:03We can start using the name of one of these variables like today or y2k and
02:08calling parts of it.
02:09We can say today.getMonth and it would return 0-11 for the month.
02:15today.getFullYear returns the normal year.
02:19.getDate, .getDay, .getHours, and so on.
02:25So there is a lot of behavior that the Date object can give us to start
02:29pulling apart dates.
02:30And not only that, but they have the flip side of the get method, which are our set methods.
02:37We can create a new Date object and then use it to say .setMonth or
02:43.setFullYear or .setDay.
02:47And usually it makes it much easier to work with dates which can be a little
02:51complex if you just decide to store them as individual variables representing a
02:55year and a month and a day.
02:57There is also a Math object built into JavaScript.
03:02This one is a little different.
03:03While objects like arrays and dates, we can think of them as mainly holding data
03:09and it's just nice that they have a little behavior that comes with that,
03:12 the Math object on the other hand is there mainly to contain behavior.
03:16you don't really store data in it.
03:18What you might do is first say create a variable called x and I am setting this to 200.6.
03:23And I would like to round this number.
03:26This is the way I do it.
03:27I would create a new variable called y and create it by calling Math.round,
03:34passing in that variable x. That would give me 201. It would round it up.
03:39So we often just use the Math object directly.
03:42Say we create several variables. One is 200, one is 10000, one is 4, but at some
03:48point in my program, I don't know which one is which and which one is higher.
03:52I can create a new variable called biggest, which will be whatever gets returned
03:57from calling Math.max and passing in those three numbers.
04:01In fact, Math.max will take as many numbers as you want to pass into it and
04:06always return the biggest one.
04:07If we have a .max, it would be nice if we had a .min.
04:11And not surprisingly, we do.
04:13So the Math object is there and has many built-in methods and properties for
04:18giving us Pi, calculating random numbers, rounding things up or down, calculating
04:23logarithms, sines and cosines and so on.
04:26So JavaScript has an Array class, it has a RegExp class, a Date class, and a
04:32Math class, and several others.
04:34Now to find out, you'd go to a JavaScript reference guide.
04:38But JavaScript really doesn't have very many.
04:40Other languages have hundreds or even thousands of predefined classes available
04:45grouped into different categories.
04:46Now what's very common in object- oriented languages is using the name of the
04:52class when you create the object.
04:54That's what we're doing here.
04:55We are creating a new variable.
04:56It's called today and it will be a Date object based on the Date class.
05:02Now when you use the name of the class, by convention in JavaScript it has an
05:06uppercase first letter.
05:08There is nothing magical about that.
05:10It just helps us recognize it.
05:11That's how it was defined in the language.
05:14And if we make our own, we will probably use an uppercase first letter too.
05:18But you might think "Well, when I made an array, I wasn't using the word Array."
05:23Well, no, that's because JavaScript has a lot of shortcuts, but you can.
05:28So the easy way to make an array is this one, just using the square brackets.
05:32But you can also create an array this way.
05:35Using the word Array, which is the name of the class, and the word new.
05:39In the same way when we are creating a regular expression, I can use the
05:42shortcut form in JavaScript to create a new regular expression object or I can
05:47use the name of the class, which is RegExp.
05:51And this word, new, is used in many object-oriented languages as an explicit
05:56indicator that what we're doing is creating a new object based on a class.
06:02Now some of you might be wondering about strings.
06:05Well, strings are objects in most object-oriented programming languages.
06:09In JavaScript they do behave like objects.
06:11They have properties and methods we can access, although technically they're not.
06:16Technically they're primitives.
06:18That's really because JavaScript is not the purest of object-oriented languages.
06:23So let's talk about some languages that are pretty pure and what the difference is.
Collapse this transcript
Reviewing object-oriented languages
00:00Object-oriented programming is above all an idea, and because of this, there's
00:05always been a lot of debate over what it means to be a pure object-oriented
00:10language and what languages best meet that definition?
00:13One of the basic questions might be, does the language just support the
00:17creation of objects or does it take it one step further and demand that
00:22everything must be an object?
00:23Now, words like polymorphism, encapsulation, inheritance, and abstraction
00:29gets thrown around a lot, but this course is not the place to get into those discussions.
00:35What it is worth knowing is what the current state of things is.
00:39Earlier in the course, we talked about this loose list of currently popular
00:42programming languages.
00:43Now, object-oriented programming has been such a successful idea that all the
00:48languages on this list except one use it.
00:51C is not an object-oriented language as it predates the time of
00:56object-oriented programming.
00:57But several languages on here can be thought of as really object-oriented
01:02versions of C. C++ for example had the original name of C with classes.
01:09Objective-C is also just C with additions to support classes and objects, and C#
01:14and Java are both languages that take a lot from C and add object orientation.
01:19Now, on the looser side of things, Perl was not originally an object-oriented
01:24language, but now does support some features. And as we've already mentioned,
01:28JavaScript is object-oriented loosely as is PHP and Python.
01:33Ruby is perhaps the purest object-oriented language here.
01:36So unless you're only going to program in C, this idea is something that you
01:40absolutely need to become familiar with and as you explore any language, start
01:45by figuring out what built-in classes exist.
01:48Bear in mind, finding out about existing class is not a thankless task.
01:54It's always a win for you as a programmer, because the great thing about a
01:58language with a lot of existing classes is that somebody else wrote behavior
02:03that you don't have to.
02:05So in JavaScript examples, we've seen classes that represent simple things
02:10like arrays and dates.
02:11But when you start working with languages like Objective-C, Java, C#, classes
02:17are also there to represent text boxes and images and buttons, and more than
02:22that, you'll find them for files and video players and cryptography
02:26functionality and pretty much anything else you can imagine.
Collapse this transcript
13. Advanced Topics
Memory management across languages
00:00There's one thing we haven't talked about so far in any detail, and that's memory.
00:06Well, that's really because in JavaScript, we don't have to talk about it.
00:09We create our variables and our objects, we use them, and we forget about them.
00:14But this isn't always the case.
00:17In several languages, you can't just create an object, use it, and forget about it.
00:21You have to manage the memory that, that object uses, manage the lifetime of that object.
00:27If I was to show you some pseudo code examples, it would be that instead of just
00:33creating an object, we first have to manually allocate an area of memory.
00:37We have to grab hold of a piece of RAM and say, "I am going to use this."
00:42Then we can create our object and we can point it to that area of memory.
00:46We say, "That's what you are using.
00:48That's where your data is being stored."
00:50We use that reference what's called a pointer to that object and just use the
00:55object, call its methods, access its properties.
00:58But at some point what we are going to have to do is realize that we are
01:01not using it anymore.
01:03We don't need that memory, so we free the memory.
01:05It doesn't sound too hard, but when you start passing around these objects, you
01:10start calling functions, you start having a long lived program,
01:14this can get quite difficult.
01:16A very common mistake is this.
01:18We allocate some memory, we then create an object, we start using that
01:23object, and then nothing.
01:26We actually don't need the object anymore, but we forgot to free the memory, or
01:31we thought we were freeing it, but we didn't free it probably.
01:33Well, that gives us a memory leak.
01:36Not a problem if you only do this once, but if you have a long-lived program
01:40that creates thousands of objects, as our program runs, it's going to get
01:44slower and slower and take up more and more memory, and at some point may even
01:48crash because of it.
01:49But the memory leak isn't the only problem we can have.
01:52If, for example, we go back to our first object where we've already freed up
01:56that memory, well there might still be a variable that's actually pointing to
02:00that area of memory.
02:01It's what's called a pointer.
02:03And if we try and use that variable because we think the object still exists but
02:06it doesn't, we have what's called a dangling pointer, and that can actually
02:10cause our program to crash.
02:12And because memory management is difficult code to write, what's happened is
02:17as more high-level languages have evolved, there's been different methods for dealing with it.
02:23If you remember early on in the course, we talked about the idea of low-level to
02:26high-level languages.
02:28The languages like assembly language and C were actually quite close to the machine code.
02:34You had to know a lot about how the machine operated, whereas things like Java,
02:39C#, and VB.NET were further away, you didn't have to think about that as much.
02:43Well, memory management is one of those areas.
02:45If you're working with assembly language, and C, you have to do a lot of manual
02:50work to allocate and free areas of memory that you're using.
02:54As you start to get into the more modern high-level languages, there are
02:58techniques for dealing with it.
03:01Objective-C and C++ can choose to use something called reference counting.
03:06This is preferable to manual memory management and it allows us to keep a
03:10counter of who is using the object, but rather than manually free the memory, we
03:16just allow the system to free it up when it realizes that counter has reached 0.
03:20If we move into languages like Java, C#, and VB.NET, there is a memory
03:25management technique called garbage collection.
03:28Rather than keep track of individual objects, what happens is the system itself
03:33keeps track of how much memory your application is using.
03:37And at certain times in your program's lifetime, what it's going to do is scan
03:41through all your objects and figure out which ones are still relevant, which
03:45ones are still being used.
03:48So it might take a sweep through a thousand objects, clear up 500 of them, and
03:52leave 500 of them around.
03:54It's called garbage collection because it bashes this up.
03:57It doesn't happen all the time.
03:58In fact, you can't even guarantee when it will happen.
04:01When you're dealing with these languages, sometimes as a programmer, you can
04:05kind of suggest to the garbage collector that it might be a good time to go and
04:09clear up areas of memory, but you don't have to work on the individual level of
04:14the individual objects.
04:15And further up, when you get into more scripting languages, it's really fully automatic.
04:21You have either no or next to no control over when memory will be reclaimed.
04:26Now, you might think well, the automatic one sound great. The issue is of
04:30course that the more automatic it is, usually the slower it is, the less efficient it is.
04:36Because while writing manual memory management code is tedious, it's difficult
04:41to do, if you can do it right, it leads to the most efficient use of memory, and
04:46if that's your goal, then you might be looking at languages that allow you to do
04:49manual memory management.
04:51However, for productivity, and particularly because we're in a world where we
04:55really don't have to worry about memory quite as much as we used to going back a
05:00couple of decades, you will find that the higher level languages using things
05:04like garbage collection, they usually win for being able to create code and
05:08create programs faster.
Collapse this transcript
Introduction to algorithms
00:01There is a term you will come across in programming called an algorithm and when
00:05you hear it described, it sounds similar to a program itself.
00:09An algorithm is a series of steps to accomplish a task, but usually when we are
00:14talking about it in programming,
00:16we mean a small procedure, part of a program, rather than the whole program
00:20itself. Perhaps even just a function.
00:22Yes, it does something specific, but there is an understanding that there may be
00:27many different ways to accomplish the same task, many different algorithms.
00:32So let me give you an example.
00:34Let's say we have a series of numbers we need to sort. It could be 5.
00:38It could be 5000.
00:38Now, there is a whole bunch of different ways we could do this, but here is one of them.
00:43I am going to compare two numbers at a time.
00:47So I will take the first two numbers and compare them.
00:49If the first one is bigger than the second, I am going to flip them.
00:52Then I will move up and I'll compare the next two.
00:55Again, if the first is bigger than the second, we will flip them.
00:58In this case, it's not.
00:59I will then move up again, compare the next two.
01:02Is the first bigger than the second? Yes, it is.
01:04And taking them step-by-step means we can take the biggest number on the first
01:09pass and move it all the way up to the top.
01:12So when we get to the end of this first pass, we know that the highest number is at the end.
01:18However, they are still not all in order.
01:20We need to make another pass.
01:22So we go back to the start, compare those two numbers.
01:25If the first one is higher than the second, we will flip them.
01:28It's not, but then the second to it is, so we will flip those, and move up
01:32again, and we will flip those.
01:35Now, this time I know I don't need to go all the way to the end, because I
01:39already bubbled up the highest number there.
01:42So we need to go to the last number, but one, we are already there.
01:45So I can just return to the start.
01:47Again, comparing the numbers, I don't need to flip those two.
01:51I do need to flip those two.
01:53And after multiple passes, I won't need to flip anymore.
01:56If I go through a password, I don't need to flip anything,
01:59I know they're all in order.
02:01This is what's referred to as a bubble sort.
02:04It's a simple sorting algorithm.
02:07We make multiple passes and bubble the larger numbers up to the top of the list.
02:12And here's the pseudo code for this.
02:14It really isn't all that bad.
02:15You can write a bubble sort in just a few lines of code, and it wouldn't matter
02:20whether you fed five numbers into it or 5000 or 5 million.
02:23It's a simple straightforward algorithm, and unfortunately, it's almost always
02:28an absolutely terrible choice, because bubble sorts are so inefficient.
02:33If you have to work with large lists of data, they're one of the most
02:36inefficient ways of sorting that that you can imagine.
02:38Well, the question might be, well, are there other ways of doing this? Well, absolutely.
02:44The question might b,e how long have you got?
02:46There are many sorts, bubble sorts, heap sorts, quick sorts, insertion sort,
02:51merge, selection, permutation sorts, and these are just some of the best-known
02:56and most famous sorting algorithms. There are many more than this.
03:00And one of the great things as you'll find that in most languages now, there are
03:04sorting functions already built into the language.
03:07When we are working with arrays or other collections, you can almost expect them
03:12to have a built-in sort functionality to them,
03:15that's already been written been written,
03:17that's already been configured and tested, but it's the idea here that's important.
03:22The simplest algorithms to think of and write are not necessarily the most efficient.
03:27Having said that the most efficient algorithms might be really hard to write,
03:31tough to understand, tough to maintain, and this is one reason why computer
03:35programming has often been called an art rather than a science. Because if you
03:40give ten experienced programmers the same problem, you're likely to get 10
03:44completely different solutions.
03:47So understand that there never is just one way to solve a problem.
03:50The first way that comes to mind may work, but there may be better ways and in
03:54programming it's often a tough choice deciding between ease of use, ease of
03:58development, speed, and elegance.
Collapse this transcript
Introduction to multithreading
00:01You already know that your operating system can run multiple programs at the same time.
00:05This is what's typically called multitasking, but there is also this idea of
00:10doing multiple things inside one program and this is multithreading.
00:15Now, multithreading is something you often do to keep your program
00:18responsive, and particularly in desktop or mobile applications with a
00:22graphical user interface.
00:24we've all interacted with programs where you click a button and it seems to make
00:28the application freeze and then a few seconds later come back.
00:32Well, multithreading is designed to get you past that.
00:36By default, your program has what's referred to as a main thread of execution.
00:41All your code runs on one thread, one conveyor belt that's taking care of
00:45instruction after instruction.
00:46With multithreading, you might for example call a function, but instead of
00:50calling it normally, which means jumping into that function on the main thread,
00:54you call it and tell it to start on another thread, a custom thread, and your
00:58main thread continues processing while the secondary thread has another thing to do.
01:04However, there are a few things to be aware of with this.
01:07One challenge is multiple threads competing for the same resources.
01:11It would be a bad thing for two different threads to be saving to the same file,
01:15for example, or using the same variable to keep track of a counter.
01:19So when working with multiple threads, there are often restrictions that any
01:23variables made on a custom thread maybe limited to that thread for example.
01:27It's also very common that only the main thread is allowed to change the user interface.
01:32Now, most scripting languages, including JavaScript which we've been working with
01:37so far, have poor or nonexistent support for multithreading.
01:41Now, in the future, JavaScript will have some ability to do a little of this
01:46with something called the Web Workers feature of HTML5, but it isn't widespread yet.
01:51Full multithreading is typically only found in a general purpose programming
01:55language, but you'll find support for it in all major desktop and mobile
01:59programming environments.
Collapse this transcript
14. Exploring the Languages
Introduction to languages
00:00So let's finally dive deeper into the languages that are available to us.
00:05Again, there are hundreds of them out there, and we only have time to explore
00:09some of the more popular.
00:11You may even disagree with this list here.
00:13It's actually a pretty difficult task to genuinely decide the popularity of a language.
00:18If you just took current usage, we might still put a language like COBOL on this
00:23list, before Ruby or Python.
00:25COBOL is an older language.
00:26It's not a fashionable language, but it's still widely used and it's running on
00:30mainframes and data centers around the world.
00:33If you make credit card or banking transactions, the likelihood is you'll pass
00:38through a COBOL system somewhere. But a lot of that is older legacy code
00:43that's been in place for decades and there is not as much new development going on
00:47in COBOL, as there is in these other languages.
00:50So this list is no slight against those other languages.
00:54I've worked with a few that have fallen off the popularity list and I'm very
00:58fond of a couple more that never made it onto it, but let's talk about why you
01:02might choose or even have to use some of these.
01:05Now as we go through them, now pay attention to a few basic things. Are they
01:11compiled or interpreted languages, are they object-oriented? You'll find
01:15them most of them are.
01:16Are they weakly typed or strongly typed languages, are they better at one
01:21particular thing or perhaps even designed for one particular thing, or are they
01:26general purpose languages?
01:28Now I'll also talk a little bit about where the language came from,
01:32the complexity of it,
01:34show you a couple of examples and how you might get started with it if it sounds
01:38like a language that you're interested in.
Collapse this transcript
C-based languages
00:00I'd be remiss if I didn't first tip my hat to the most influential language on this list, C.
00:07Invented in the early `70s at Bell Labs and still in tremendous use around
00:11the world, C has influenced every language on this list.
00:14Not just the obvious ones like C++, C# and Objective-C, but also languages like
00:19Perl and PHP owe a tremendous amount to C.
00:23Now C is a pure structured language, as I mentioned before.
00:29It's the only non object oriented language that was on the list.
00:32It's not about classes.
00:34It's not about objects.
00:35It is a fairly low level language that you do have to work with manual memory
00:39management quite a bit.
00:40It is typically a compiled language and strongly typed in the sense that you
00:46don't just create generic variables; you create variables of type integer or
00:51type float or Boolean variables.
00:53Well, it's not too hard to get started with C, the typical skill level is
00:57intermediate to advanced, to even very advanced if you're getting very
01:01detailed with this language.
01:03And part of the reason for that is what is C used for?
01:07Well, I put up the top here everything, and it is, you will find C used for
01:11everything, but probably the majority of the use these days is in more advanced
01:16situations, in games and building 3D engines, in building embedded systems.
01:22Writing programs that are actually saved onto a DSP chip or writing operating
01:26systems. You'll even find C being used to build compilers for other languages.
01:32So if your requirement is you are wanting to build desktop apps or mobile app
01:37or web applications, where you're looking for a high productivity environment,
01:41it's probably not your typical choice.
01:44Although you will find that many of those environments let you use C programs if
01:49you want to write something that's very fast and very compact.
01:52So what does it look like?
01:54Well, we should be able to recognize the basic structure of it from just what
01:58we've seen during the rest of this course.
02:00It uses the curly braces to surround code blocks.
02:03It uses the semicolon at the end of the line.
02:06It uses the two forward slash for the comment.
02:10JavaScript of course takes all these things from C. Now when we were creating
02:15variables in C we don't just say var, we say something like int X not var X,
02:20because we're creating an integer variable or a character variable, so we have
02:24to be specific about the kind of data that we're working with.
02:27Now like JavaScript, C does used functions, although we don't use the function
02:32keyword. In fact, this main word here is telling me that this is the single most
02:36important function in a C program, and in fact, in a lot of C-based languages.
02:42Main here is the name of a function, and it's the function where the program begins.
02:48That's how C and most C-based languages know where to start, is because there's
02:52a block of code with the word main attached to it, and a very common thing that
02:57you'll see in a C program is a statement like this include <stdio.h>.
03:04As we explore more languages, you'll see several things like this.
03:07It's very common for general purpose languages to link to external libraries.
03:13Basically saying in this file there is a whole bunch of code that somebody else
03:17wrote, a whole lot of functions, a lot of useful things that I can make use of
03:22in my program and I want to link to it. And you'll find that with most general
03:26purpose languages, it's less about the language itself and more about all these
03:31external files, these libraries of code that you can actually use and link to.
03:36So if you did want to take a look at this how would you get started?
03:39Well C is one of your classic languages that you really don't need much.
03:43You need a text editor, you'd need a compiler.
03:47The classic compiler is something called GCC and it's an Open Source compiler
03:52used by a lot of different IDEs or Integrated Development Environments.
03:56So you'll often find C compilers built into programmers' text editors and other
04:01IDEs. Because C predates the web, there is no one website to go to to get
04:07information about it, although gcc.gnu.org is as good as any place to find some
04:13central authoritative information.
04:15In fact, the most important single resource that I would point you to on the C
04:20programming language is the book called The C Programming Language, often
04:24referred to as the K&R book by the two lead authors Kernighan and Ritchie.
04:29This is one of the best books ever written on the subject to programming,
04:34and even if you don't intend to become a C programmer, it's worth having on your bookshelf.
Collapse this transcript
The Java world
00:00The next language we're going to take a look at is Java.
00:04This is heavily influenced by C, but came along over 20 years later.
00:08This was released in 1995 and was developed by Sun Microsystems.
00:13It is an enormously object-oriented language.
00:17It's all about classes and objects and it comes with an enormous library called
00:22the Java Class Library.
00:24Effectively meaning a whole bunch of prewritten code that you don't have to write.
00:28There is an enormous amount of functionality already in there for you.
00:32It is a high-level language.
00:33We don't really have to mess around too much with memory management.
00:36It has a built-in garbage collector.
00:38Java is a language that uses the hybrid compilation model.
00:42It's neither straight compiled nor is it interpreted.
00:45It compiles and sends to something called bytecode.
00:49One of the reasons for that was the idea of being a very
00:52cross-platform language.
00:54There was a slogan that Sun used called "write once, run anywhere."
00:58Now as it's a partially interpreted language that does mean that people do have
01:02to have the interpreter for Java on their machine.
01:05What's called the Java Virtual Machine or JVM.
01:08You've almost certainly seen that yourself, that some application on your machine
01:12has wanted to install Java.
01:14That's probably a good clue that one of the things it's famous for is for
01:18desktop applications.
01:20You can write a desktop application in Java and have it run on a Mac and have it
01:24run on a Windows PC, have it run on a Linux box.
01:27Recently, one of the big uptakes in Java was for developing mobile applications
01:32that run on the Android platform.
01:34So it's a C-based language.
01:36Well, what does it look like?
01:38Well, one thing that jumps out is again this word main.
01:41This is how we tell a Java program where to begin.
01:44Now that seems to be an awful lot going on here.
01:48I can see that I have int myInt = 55 line.
01:52Once again unlike JavaScript which uses the word var, we have to be specific here.
01:57We're using the word int.
01:58Not a general variable, but an integer variable.
02:01The line that begins System.out.println is how we output the words Hello World!
02:07to the screen. But this is an object- oriented language and in Java everything
02:12is in a class which is why we have to surround the code that we want in this
02:17class HelloWorldApp.
02:18It looks like an awful lot to do, but bear in mind most of the development
02:23environment you will use will provide this framework for you.
02:26You just have to come in and fill in the gaps.
02:29And as I mentioned before, although there is a passing resemblance because of
02:33the curly braces, because of the semicolons, Java is not JavaScript.
02:39The languages have very little to do with each other.
02:42If you're interested in getting started with this language you're probably
02:45looking at getting a full IDE, a full development environment for Java.
02:49Two are the most popular are Eclipse and NetBeans and because this language is
02:54owned by Sun and developed there java.sun.com is the most authoritative website to go to.
03:02Sun is now owned by Oracle.
03:03So you may be redirected, but you'll always be able to find a lot of
03:07information there on getting started and tutorials and the basics of starting
03:11to work with Java.
Collapse this transcript
.NET languages: C# and Visual Basic .NET
00:00Next, I am going to talk about two languages at once.
00:03C# and Visual Basic.NET.
00:06These are the two flagship languages if you're developing on the
00:09Microsoft platform.
00:11I talk about them at the same time because although they do look different, what
00:15you do with them and how you approach them is almost identical.
00:18Now, these two languages were released in 2003 by Microsoft.
00:22Although Visual Basic had a longer history than that, it was really
00:26reinvented at that time, and this was when Microsoft released something called
00:30the .NET framework.
00:32We can think of this as an enormous library of prewritten code, huge amounts of
00:37functionality that we can tap into if we use either of these two languages.
00:41Now, actually there are other .NET languages as well, but these are by far the most popular.
00:47Both of them are object oriented. They are all about using classes and objects,
00:52and both of them share the same characteristics. They are high-level, they are
00:56strongly typed, they use garbage collection so we don't have to worry too much
01:00about memory management, and they both use the hybrid compilation model like Java does.
01:05They are neither strictly compiled, nor strictly interpreted. They go halfway.
01:11When you compile a C# or a VB.NET application, it compiles to something called
01:16Intermediate Language or Microsoft Intermediate Language.
01:19That then can be distributed across a whole range of different machines with
01:24different CPUs and each machine takes it the final step to go down to machine code.
01:29Just as Java requires something called the Java Virtual Machine on every
01:33computer that's going to run a Java program, .NET languages require something
01:38called the .NET Runtime to be installed on every machine.
01:41Now, of course they're classically associated with developing on the Microsoft
01:46platform, whether that means Windows server or a Windows desktop system, or even
01:51a Windows phone. All of it can be done with these .NET languages.
01:55They both have the same capabilities for building desktop applications.
01:59You can build dynamic websites using these languages.
02:03Now, when we talk about building a website on the Microsoft platform, it's
02:07usually lumped under the term ASP.NET.
02:10It's easy to think, well, that must be another language, but it isn't.
02:13ASP.NET is really just a useful phrase that means you're building a dynamic,
02:18smart, interactive website using Microsoft technology, and if you're doing it,
02:23you are almost certainly using either C# or VB.NET.
02:27And these languages can both be used for developing mobile applications that
02:31work on the Windows phone operating system.
02:34So while they are closely associated with the Microsoft world, they are up and
02:38down that entire stack of the Microsoft world.
02:41So what do they look like?
02:42Well, C# not surprisingly is a C- based language. It probably looks closer to
02:47Java than anything.
02:49We have the curly braces. We have the semicolons to end the statement.
02:53We also have another use of Main.
02:55This is how we're telling the .NET Runtime where this program begins.
03:00What's the first line that should be executed?
03:04Well, in this case it's System.Console.WriteLine.
03:08And again, don't worry about the syntax.
03:11This is just a way of getting the text Hello World out to the console, just
03:16outputting a message.
03:18Like Java, we can see that the whole thing is wrapped up with this phrase
03:21public class Hello1.
03:23That's because C# is a thoroughly object oriented language and everything is a
03:28class in it, and that means to create even the simplest application, we have
03:32to say, here's our class, here's our section called Main, this is the line
03:37that I want to execute.
03:39Now, you might have noticed that the use of curly braces is a little different
03:43here and that's because in C#, the common usage of them is to line them up to
03:49have them each on their own line matching the opening and closing curly braces.
03:54This is what sometimes referred to as Pascal or Allman style.
03:57It's just become the accepted style in the C# world.
04:01Like other C-based languages, C# is whitespace insensitive.
04:05It doesn't matter where you put them but this is the way you are likely to see them.
04:09Well, what about Visual Basic.NET?
04:11Well, this is not a C-based language, so we don't see the semicolons at the end
04:17of a statement, we don't see the curly braces. We do still see the use of Main.
04:22Now, once again this is how we say what's the actual code that I want to run
04:26when this program begins, and we see this would end being used a lot.
04:31Because we can't mark out where blocks of code begin and end with curly braces,
04:36we have to say if there is an If, we need an End If.
04:39If there is a Sub, which is kind of our way of doing a subroutine like a
04:42function, we have an End Sub, or a Module has End Module.
04:47By themselves, they don't actually cause anything to happen; they're just
04:50mocking out a logical area of our program.
04:54We also have this System.Console.WriteLine.
04:58This line is exactly the same as it was in C# except for the semicolon at the
05:04end of the line, which is required in C#, and that's because although the
05:08overall format of the language is different, the things that you do, the
05:12statements that you execute in a .NET language are often almost identical to
05:16each other because you have the same libraries available to you, the same
05:20functionality available to you.
05:22Most people who can code in C# can read VB.NET just fine and the other way is true as well.
05:29So how might you get started with this?
05:30Well, Microsoft make it fairly easy to do this.
05:34You can go and download Visual Studio.
05:36That is their flagship integrated development environment and you'll find there
05:41are several different versions of it including versions that are completely
05:45free, what are called the Visual Studio Express editions.
05:48Visual Studio includes a great text editor, a compiler, a debugging tool,
05:54all the things that you need to actually get started with any of these languages.
05:58Although, there are versions of Visual Studio that are commercial and even
06:01cost several thousand dollars, you can get started and experiment and play
06:06around with these languages and even create websites and desktop applications
06:10without spending anything.
06:11So if you're interested in this, take a look at microsoft.com/express.
Collapse this transcript
Ruby
00:00Let's take a look at one of the newer languages on the list, Ruby.
00:03This was developed in Japan in the mid 1990s and most people would consider it a
00:08very pure object oriented language.
00:11In Ruby everything is an object, even variables that might be considered
00:16primitives in other languages like Booleans or integers.
00:19Everything is an object.
00:21It's a high level garbage collected language.
00:24We don't really need to think about memory management and it's
00:26completely interpreted.
00:28We don't need a compiler for Ruby.
00:30We do need an interpreter.
00:31It doesn't compile to intermediate language like Java or the .NET languages.
00:36Most people find it very easy to approach.
00:39There isn't a lot of prerequisite knowledge required to get started with Ruby.
00:44So it's fairly friendly for beginners.
00:46The question is what it used for?
00:48Well, it is a cross-platform language.
00:50There are installers and interpreters available on every OS and you'll actually
00:56find it built into the last few versions of Mac OS X. It's probably become most
01:01famous recently for it to use in what's called Ruby on Rails.
01:04This is a web framework that uses the Ruby language.
01:09Aside from that it's a great language for writing small utilities, text processing
01:14applications on the desktop.
01:16So what does it look like?
01:18Well, it is not obviously a C based language.
01:21We don't need a main section.
01:23This would be considered an entire working Ruby program.
01:27Puts for put string "Hello, world!
01:30No semicolons at the end of the line, but this doesn't really tell us too much about it.
01:35So I'll add a few more lines here.
01:37I'm going to define what we call a function here.
01:39I can see that we use comments, not with the two forward slashes, but with the
01:44pound sign or hash sign. And then creating this function or method here,
01:49I'm using the word def for define. We're calling this welcome saying it takes
01:53a parameter of name and then we're going to output hello comma, whatever the name is.
01:59We don't use curly braces to mark the end of the function. We use the word end
02:03instead and then below it I say x = bob.
02:06This is how I'd create a variable which is a string and then I just call this
02:10function or method saying welcome and passing in x.
02:15Again, don't worry about memorizing syntax.
02:17The idea here is that you're just looking at the overall structure.
02:21Ruby is a fairly compact, fairly clean language to get started with. And if
02:26you're interested, what do you need?
02:28Well, not really a lot.
02:29If you're working on a Mac you already have the Ruby interpreter there.
02:34There are several different editors that you might use. TextMate and RubyMine on
02:38the Mac, Aptana is cross-platform.
02:41There're quite a few that have Ruby support.
02:43Probably the most two important websites are rubyonrails.org, which is all about
02:49that web based framework that uses the Ruby language, and ruby-lang.org.
02:55Both of these have fantastic resources for getting started with Ruby, either the
03:00Ruby language by itself or as a web based framework.
Collapse this transcript
Python
00:00Next let's talk a little bit about Python.
00:03This is a language that's often mentioned in the same breath as Ruby as it's a
00:07very clean and concise object oriented language.
00:11We're beginning to see a pattern here it's another language that comes with a
00:14really large library.
00:15In fact, that's one of the benefits of this language.
00:17There is a whole bunch of prewritten functionality we can just type into.
00:21Again, like Ruby it is an interpreted language.
00:25It's garbage collected.
00:26We don't have to worry about compilers. We don't have to worry about memory management.
00:30And although, it's really powerful it's a very easy language to get started with.
00:34So what it is used for?
00:35Well, one of the great things about Python is totally cross-platform.
00:39There are Python interpreters on every platform that are well supported.
00:43It's a very easy language to build web applications with and ties in particular
00:48well with the Apache web server, but you'll also see it being used a lot as an
00:51embedded scripting language inside other applications.
00:55And it's used a great deal for building applications and web apps by companies
00:59like Google and Yahoo!
01:01So we want to know what does it look like.
01:03Well, again it's one of these programs where we could have an entire valid
01:07program in one statement like with Ruby.
01:10We don't need a section called main. We don't need the semicolons.
01:14This is perfectly acceptable.
01:16But it doesn't teach us a lot.
01:17So let me add a few more lines.
01:19I can see that like Ruby we use the pound sign and hash mark as a comment and we
01:24use def for a define for describing a function, but here's an interesting thing.
01:30I'm defining a function here called sayhello that takes one parameter of name.
01:34The question is where does it end?
01:36Well, Python is interesting, because it is one of the languages that does pay
01:40attention to indentation.
01:43We don't use the curly brace to mark the end of a function;
01:46we just indent the lines that are inside the function.
01:49So in this case, it's just one line. It says print 'hello' and follows it
01:53with the name parameter.
01:54So then down below this I can just call this function.
01:58Python knows the function has ended, because there are no more indented lines.
02:02Now that looks a little different, if you're used to either the word end
02:06or you're used to those curly braces, but it's leads to a very clean readable syntax.
02:10Unlike Ruby, this is a very concise readable language that's easy to get started with.
02:15So how would we get started?
02:17Well, there are several IDEs and editors that support Python.
02:22Two common ones would be the Eclipse IDE with the extension PyDev that helps for
02:28Python development and Komodo as well.
02:31Although you'll find many programmers' text editors will support Python.
02:35Python interpreters are available on every platform and actually built into
02:40recent additions of Mac OS X, but the single best resource for getting started
02:45would be the website python.org.
02:47This is the official Python website and has a great amount of installers, help,
02:52and tutorials for how to get moving with this language.
Collapse this transcript
Objective-C
00:00Objective-C is one of the older languages on the list.
00:04Invented in the early 80s as an object oriented version of C, it really is the C
00:10language with some extra stuff added to it.
00:14That extra stuff makes it object-oriented.
00:17The way it's used these days one of the benefits of using Objective-C is it
00:21comes with a large library referred to as Cocoa which we will talk about in a moment.
00:25It is a compiled language.
00:27Not interpreted and not one that uses intermediate bytecode.
00:32And although, it's a high-level language, it is one where you need to be a bit
00:35more aware about memory management than things like Java or the .NET languages.
00:40It uses something called reference counting, where we keep track of the objects
00:45that we create and whether we're done with them or not.
00:48Although advances in the language means that this is becoming less and less of
00:52an issue, but because of that I wouldn't say it's a particularly friendly
00:56language for beginners.
00:57You really need kind of an intermediate level of skill to be messing with Objective-C.
01:02However, you maybe highly motivated to do this.
01:05Because one of the reasons that Objective-C has grown enormously in popularity
01:09is that this is the language we use for Apple development, whether that's iOS
01:13development like the iPhone or the iPod or a Macintosh desktop development.
01:19And it's the language that was used to build the OS X operating system or
01:23at least large parts of it.
01:25So it's not going anywhere anytime soon.
01:27So here is the question: what does it look like?
01:30Well, as the name might suggest quite close to C. We have the curly braces, we
01:34have the semicolons at the end of the line.
01:37However, it's one of the stranger looking languages, because there are a quite a
01:41few things that aren't shared across other languages.
01:44We still have the main section which is denoting where our program begins.
01:49But while you'll see are a lot of words that begin with NS everywhere and this
01:54is really an old history lesson.
01:57Objective-C was used by the company NeXTstep to build their operating system and
02:01when that was bought by Apple, it brought a lot of that with it.
02:06So when you see example programs written in Objective-C, you will often see this NS
02:11letter all over the place.
02:12You will also see a lot of square brackets being used.
02:16Now usually we'd assume they were denoting arrays, but here that's not the case.
02:22Because Objective-C is actually built on top of the C language and what I mean
02:26by that is not influenced by C. It is C with extra stuff.
02:31The way that we start to use the object- oriented features is we have to mark them
02:35out by using things like square brackets.
02:39So Objective-C can look a little strange to people used to other languages.
02:43Another odd feature is it's very common to see the @ sign in front of a string.
02:48And that's how we actually tell Objective-C that we are working with a string
02:51object in that language.
02:53And like C we also have a lot of import statements.
02:57One of the powers of using Objective-C is we can link to a whole bunch of big
03:02libraries full of interesting code that we can get access to.
03:06Because Objective-C has been used so long by Apple, they've built enormous
03:11amounts of pre-written code that we can used to build Macintosh desktop
03:15applications, iPhone applications, and these are wrapped up under the
03:19general name of Cocoa.
03:21And if you're interested in getting started with this language, well,
03:24there is one key editor or IDE and that is XCode.
03:28That is Apple's own integrated development environment for building desktop
03:33applications or iPad or iPhone applications or even just simple command line applications.
03:40And because this is so Apple oriented, not surprisingly the one key website here
03:45is developer.apple.com.
03:48This is where you'll find downloads, reference guides, tutorials, and a lot of
03:52information about getting started with Objective-C.
03:55If you're interested in writing applications that run natively on Apple
03:59hardware, this is the language you want to be looking at.
Collapse this transcript
Libraries and frameworks
00:00If you've watched some of the language introduction videos you would have seen a common thread.
00:05With most of them I taught less about the language and more about the benefits
00:10of the libraries that were available.
00:12And these are sometimes called libraries. Sometimes they are wrapped up into the
00:15term framework instead.
00:17But it really means the same thing.
00:19Huge amounts of code already written, already tested, ready for you to link to and use.
00:25Say with C# in VB.NET you have the .NET framework.
00:29With Java, you have the Java Class Library.
00:32With Objective-C, you have Cocoa or Cocoa Touch, depending on if you're focused
00:37on the desktop or on the iPhone and iPod.
00:39With Python, you have the standard library and so on.
00:43This is another thing that programmers know that non-programmers don't.
00:47It's not really about the language.
00:49It's about the libraries.
00:52So when you are learning C#, you might wonder if there's anything that can help
00:55you connect with database.
00:57And yes, there is, but it's not part of the language itself, but it's in
01:01the .NET framework.
01:03If you're experimenting with Objective-C, you might wonder if there's a built-in
01:07video player class for the iPhone, and of course there is.
01:11It's already been written by Apple and it's in the Cocoa Touch framework.
01:15You can link to it and use it.
01:18If you're using Python and your program needs to be able to save to a file and
01:22unzip that file up, well, you will find that in the Python Standard Library.
01:27And those are the skills to develop.
01:30Knowing not just the language, but what you can do with it without having to
01:33write it all yourself.
01:35Now when you are just beginning, it can be somewhat intimidating to figure out
01:39yeah, there might be hundreds or even thousands of prewritten classes available
01:43to the language that you're looking at and you wonder, am I meant to learn them all?
01:48Well, of course, you are not.
01:50It's like being in a real library.
01:52The point is not that you're going to read every book. The point is to be able
01:55to find your way around, to be able to navigate through the stacks and find if
02:00what you're looking for exists, and if so, how do you get to it.
02:04What you'll find is there are reference guides whether it on paper or more
02:08usually on websites.
02:10So Microsoft has the .NET Framework Class Library where we can actually start
02:16scrolling through all these different areas.
02:18They break their classes down into different places like classes that deal with printing.
02:24Going back up we have whole sections that deal with classes of globalization.
02:30So these range from the very generic to the very specialized.
02:34If you are working with Java, it's the same idea.
02:37These are grouped together into what are called packages.
02:40We have packages for dealing with math.
02:44We have packages for dealing with security.
02:48We have packages for dealing with the sound and midi, which themselves break down
02:52into classes that deal with say instruments or tracks.
02:57And this is all already there.
02:59You have the Python Standard Library.
03:01With its own set of classes you can use and of course, the iOS Developer Library.
03:07And that's why as you learn any language, when you've gotten past the basics of
03:11the syntax you're going to find it just as important to know your way around
03:15the reference guides to find out what libraries are available to you and what's in them.
03:20And that will accelerate your learning way more than focusing on syntax.
Collapse this transcript
Conclusion
Where to go from here
00:00I hope you've enjoyed this Foundations of Programming Fundamentals Course. So now what?
00:05Where do you go from here?
00:07Well, this course was designed to introduce you to the basic concepts, the
00:10terms, the core ideas of programming, how to think about it, understand more
00:15about the process, introduce you to best practices, and the kind of issues and
00:20possibilities you'll run into.
00:22You now need to go and explore a language.
00:24Now, learning a programming language is like learning a musical instrument.
00:28You can read and watch to learn the basics, but to get comfortable with it,
00:32there is no substitute for hands-on practice.
00:34So get clear about what language, what environment, and what area you are
00:39going to start with.
00:40Pick a problem to solve and find a way to solve it, and of course, take a look
00:44at some of our dedicated language courses here at Lynda.com.
00:48We have Essential Training courses on C#, Objective-C, JavaScript, Python,
00:53Ruby and more, and keep an eye out for more titles in the Foundations of Programming series.
00:59Thanks for watching!
01:00See you next time!
Collapse this transcript


Suggested courses to watch next:

JavaScript Essential Training (5h 31m)
Simon Allardice


Objective-C Essential Training (6h 35m)
Simon Allardice

Java Essential Training (7h 17m)
David Gassner


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked