Monday, January 24, 2011

Learn How to Code Part I: Variables and Basic Data Types

By Adam Dachis

Learn How to Code Part I: Variables and Basic Data Types

Learn How to Code Part I: Variables and Basic Data Types Want to learn how to code but don't know where to start? We've got you covered. We'll be teaching you the basics all week, and here's your first lesson.

Previously we've provided you with some resources for learning to code and given you a broad overview of the process, but now it's time to get down to business: We're offering a short 101 course, step by step. You can't learn to code overnight (or in a week), but we've broken up the basics into a few lessons that will be released as the first four parts in our brand new Lifehacker Night School series. Learn How to Code Part I: Variables and Basic Data TypesEach lesson will be video-based (as you can see above), but we'll also provide you with text notes and files that you can refer to as well. Each lesson is designed to be a manageable chunk of information that you can digest in under 15 minutes (and often much less). Although we're starting off our first programming lesson at 9:00 AM PST, the following three lessons will be released every day at 6:00 PM PST. Be sure to come back and visit us at the end of the day on Tuesday, Wednesday, and Thursday this week to finish learning the basics.

Our first lesson is going to be very simple and consist of learning about basic variables and data types. For the lessons in this series, we're going to use JavaScript as a model because it's a syntax that's pretty easy to understand and it's something that anyone with a text editor and a web browser can use. Because it's an ECMA-based language, it makes understanding other ECMA-based languages (like ActionScript) much easier to learn. Even better, you'll find that knowing how to write JavaScript will make the transition to other object-oriented programming languages much easier. Basically, JavaScript is readily available to practically anyone with a computer and a browser, so we think it's a really good starting point. Once you have the basics down it should be easy to begin learning other languages.

Let's get started!

What Are Variables?

You can think of variables as labeled jars that store different types of data. While there are several kinds of variables, today we're only going to look at three:

  • String - A string variable is a string of alphanumeric characters and allowed symbols that are contained within quotation marks. For example, "Hello world, I'm 102 years old today!" is an example of a string. Strings can also be contained within single quotes, which is useful if you want to have a string with a quotation like this: '"I hate the snow," Laurel said.' Strings are basically used for storing text.
  • Number - A number variable couldn't be more straightforward because all number variables store are numbers. You don't store them within quotes like strings. Instead, numbers can just be written as they are. If you want to store the number 9 in a variable, you just write 9.
  • Boolean - A boolean variable is one of two things: true or false. This data type is kind of like an on and off switch, so you can ask true or false questions in your code. For example, you might ask "is the video currently playing?" The response you'd get would be a boolean variable. True would mean the video is currently playing and false would mean it is not.

So how do you putt a variable to your code (or declare a variable, as it's more traditionally called)? In JavaScript, all you need to do is this:

myVariable = "Hello world!";

To Var or Not to Var

In JavaScript, you can define a variable as myVariable = "something"; or var myVariable = "something";, the difference being the word var preceding the statement. When you're declaring variables in a script outside of a function, this distinction is pretty much irrelevant. When you're declaring a variable inside a function and do not use var this creates a global variable. Global variables can be accessed from anywhere in your code, whereas local variables (such as the ones defined in functions) can only be accessed within their own scope (e.g. if a variable is local to a function, only that function can use it). This is not an important distinction right this minute, but when we learn about functions later it'll be good to know.

There are a few of things to notice here. First, the name myVariable. All programming languages have something called reserved words, which means you can't use them as variable names. What they varies, but if the name is sufficiently generic, there's a chance it could be a reserved word. To avoid using reserved words and screwing up your code, just decide on a naming scheme for your variables. I've put "my" in front of my example variable, but you'll probably want to come up with something else. Second, you'll notice a semicolon at the end of the line. A semicolon is like a period at the end of a sentence in many programming languages, and that is definitely the case in JavaScript. In nearly every situation, you need to end your code sentences with a semicolon so your computer doesn't get confused when reading it. The semicolon tells the computer, "Okay I'm all done with this statement." (Note: JavaScript is forgiving, and sometimes you can get away without the semicolon, but it's good practice.)

One more thing to note is that JavaScript is a loosely-typed language. There are (basically) two kinds of languages: loosely-typed and strictly-typed. An example of a strictly-typed language is ActionScript (the language Flash apps are written in), and the same variable declaration we just wrote would look like this in ActionScript 3:

var myVariable:String = "Hello world!";

The additions you're seeing are the word var and the word String (with a colon in front of it). The word var tells the computer we're about to declare a variable. The :String attached to the variable's name tells the computer what type of variable it is and to not accept any other type. This is the reason for the term strictly-typed. A loosely-typed language like JavaScript is more flexible and doesn't require any of that. This makes your code more flexible, but some will argue it will also make it more error-prone. We're not going to get into the pros and cons of strictly- and loosely-typed languages here, but it's good to be aware of the basic differences now as you will most likely encounter them in your programming endeavors.

Now that you understand what variables are and how they work, we can try using them in some actual JavaScript code.

Creating Variables and Using the JavaScript Alert() Function

Let's create a simple HTML document that we can use to test our variables:

Learn How to Code Part I: Variables and Basic Data Types
(Right click this link and choose to save the document to download a copy of this skeleton HTML file.)

You're going to want to have a better-defined HTML document when you're actually writing code, but for our purposes this will work just fine. Save the code above as a file called myscript.html (or anything you want that ends in .html and doesn't contain spaces or special characters) and open it up in your web browser. You'll see absolutely nothing other than "My Script" in the title bar. We still have more work to do. First, let's declare a variable inside of the script tag:

myVariable = 5;

Here we've just declared a number. Let's look at other variable types we can declare

myNumber = 5;
myString = "Hello world!";
myBoolean = true;

That gives us a number, a string, and a boolean. Now let's take that myString variable and actually do something with it:

myNumber = 5;
myString = "Hello world!";
myBoolean = true;
alert(myString);

You'll notice I've added the line alert(myString);. This calls a built-in JavaScript function (we'll learn more about these later) called alert() which creates a pop-up dialogue box for users to interact with.

What is "Hello world!" all about?

Writing a simple program that says "Hello world!" is generally the first thing every programmer does when they're learning how to code. It's not necessary, but it's sort of a tradition and an initiation into the club.

You never really want to use these in practice because—as any internet user likely knows—alert boxes are very annoying, but they make for a good way to test your code, to make sure it works, while you're writing. The parenthesis following alert allow you to provide alert with data it might need. Not all functions will require that you give it information, but alert needs to know what to alert the user. In this case, we gave it myString, so the user will receive a popup notification that says "Hello world!" Try this with your other variables to get popups with a number and a boolean value.

Why give alert() a variable and and not just give it the contents of the variable? Well, if you said alert("Hello world!") you'd get the same result in this example, but variables are called variables because they vary. The idea is that the contents, or values, of these variables will change as users interact with the programs you write. In our next lesson, we'll be looking at working with variables and the neat things they can do. Tune in tomorrow at 6:00 PM PST for the next installment.


You can contact Adam Dachis, the author of this post, at adachis@lifehacker.com. You can also follow him on Twitter and Facebook.

Number of comments
  • Share this:

No comments:

Post a Comment

CrunchyTech

Blog Archive