Skip to content

Instantly share code, notes, and snippets.

@jcbwlkr
Last active March 1, 2016 21:07
Show Gist options
  • Save jcbwlkr/2478442359d50df55f1d to your computer and use it in GitHub Desktop.
Save jcbwlkr/2478442359d50df55f1d to your computer and use it in GitHub Desktop.

JavaScript Workshop 1

Overview

  • What is JavaScript?
  • How to Run Code
  • Arithmetic
  • Variables
  • Comments
  • Methods
  • Strings
  • Calling Functions
  • Writing Functions
  • Include Code on a Page
  • Branching
  • Arrays
  • Looping
  • Getting Help

What is JavaScript?

Types of Computer Languages

Most web developers use languages from these four categories:

  1. Markup Languages
  • Structures to represent data
  • Most commonly HTML
  1. Stylesheet Languages
  • Controls display / presentation of data
  • Usually CSS
  1. Query Languages
  • Used to retrieve / manipulate data
  • Typically SQL
  1. Programming Languages
  • Performs calculations / decisions based on data
  • There are a plethora of options. This is where we typically fragment.

JavaScript is a programming language.

Where is it Used?

JavaScript is everywhere.

The vast majority of JavaScript is ran in users' web browsers. In recent years advancements have been made to allow developers to code server side applications in JavaScript. Additionally frameworks have emerged to allow developers to write HTML/CSS/JS apps for mobile phones. Even desktop applications and operating systems are being written in JavaScript.

What about Java?

You may have heard of the programming language Java. To be clear, Java and JavaScript have nothing to do with each other. This is a common misconception.

How to Run Code

In Google Chrome open the JavaScript console by typing Cmd + Alt + J. You can type code at the > prompt and the result is printed below. Type in 2 + 2; then press Enter. You should see the result 4.

Arithmetic

Let's experiment for a minute with some different equations.

  • 4 - 3;
  • 5 * 6;
  • 10 / 2;
  • 9 / 2;
  • 7 + 8 * 9;
  • (7 + 8) * 9;

Try some other arithmetic yourself. Play around with the % operator, called modulo. It will give you the remainder of dividing two numbers. Don't be fooled into thinking it has something to do with percentages!

+, -, *, and / are called operators. An operator is a special character (or characters) that indicates an action to be performed.

Try dividing 0 by 0. The result, NaN, stands for not a number. In JavaScript, NaN is actually considered a type of number (bizarre as that may seem).

Try dividing any other number by 0. The result, Infinity, is also a number in JavaScript.

Variables

Try this:

var myNumber = 45;
myNumber;

myNumber is a variable that we set equal to 45. Variables allow you to store a value in memory. On the second line, when we type myNumber and press Enter, JavaScript returns the value of the variable. In JavaScript, it's conventional to give variables names that start with a lowercase letter, and if they are more than one word, to capitalize the first letter of subsequent words. This is called camelcase, because the capitalized letters look like a camel's humps.

Sometimes you'll see a variable initially set without the var keyword, like this:

myNumber = 45;

This works... most of the time, but it can cause really bad bugs down the road. Get in the habit of using the var keyword whenever you create a new variable, and you'll save yourself some massive headaches later.

You can change the value of a variable:

var myNumber = 45;
myNumber;
myNumber = 50;
myNumber;

You can do arithmetic with your variables:

var favoriteNumber = 13;
favoriteNumber * 4;

Does the variable change when you perform arithmetic on it?

var favoriteNumber = 7;
favoriteNumber + 1;
favoriteNumber;

Nope. But what if we do:

var favoriteNumber = 6;
favoriteNumber = favoriteNumber + 1;
favoriteNumber;

Here's a shortcut: favoriteNumber += 1;

You can use more than one variable at a time, too:

var num1 = 5;
var num2 = 6;
var num3 = num1 + num2;
num3;

Comments

Consider this code:

var pointsAvailable = 44;
var passingScore = pointsAvailable * 0.75; // 75% is considered passing

In JavaScript, everything after the // is a comment, and is ignored. Comments are a convenient way to leave notes in your code for yourself or other programmers.

Methods

Now that you've got the basics of numbers down, let's learn how to manipulate them a bit. First, let's change a number into exponential notation.

If you're not familiar with exponential notation, here's how it works. Take the number 78.5. In exponential notation, we write it 7.85 * 10. Or take 356.97; in exponential notation, that's 3.5697 * 102. You can also write it as 3.5697e+2.

Exponential notation makes it easy to write very large or very small numbers. For example, 1,000,000,000 becomes 1e+9, and 0.00000002 becomes 2e-8.

We can use JavaScript to easily change numbers into exponential notation:

48432.78.toExponential();

The output is "4.843278e+4" toExponential() is called a method. You can think of a method as a message that you send to a number, and the result that JavaScript gives you as the number's response to that message.

You can also go in the other direction, and convert out of exponential notation:

4.587e2.toFixed();

The toFixed() method will round to the nearest whole number. Here's how we can tell it how many decimal places to use:

46.1.toFixed(2);

The 2 in the parentheses is an argument to the toFixed() method. Arguments provide a bit more information to methods to help them know what they're supposed to do. In this case, the argument is optional. When a method doesn't take an argument, or when the argument is optional and you aren't using it, you still need the parentheses on the end - so you have write 1.05e3.toFixed(), not 1.05e3.toFixed.

Here's another method that takes an argument:

8.12345.toPrecision(4);

You can also call a method on a variable, since the variable is just standing in for the number it represents:

var myNumber = 8.12345;
myNumber.toPrecision(4);

Strings

We've done a lot with numbers, but there's more to this world than just math. Let's look at words

"Hello world!";

The stuff inside the quotes is called a string. Strings can include letters, punctuation, and even numbers. These are all strings:

"5674";
"!?&";
"Strings are crazy! ;)";

What happens if we don't surround our string with quotes?

hello;

This doesn't work because JavaScript doesn't know what hello means when it's not a string. It looks to see if it's a variable or something similar, and then doesn't find it defined anywhere.

We can set variables equal to strings:

var myString = "Strings can contain characters like @, $, and %.";
myString

You can call methods on strings, just like you can with numbers:

"supercalifragilisticexpialidocious".toUpperCase();

Or even call the method on a variable assigned to a string:

var word = "foo";
word.concat("bar");

Methods can be chained like this:

"foo".concat("bar").toUpperCase();

The concat() method (which concatenates, or combines, two strings) returns a string, which then has toUpperCase() called on it. Then, toUpperCase() returns the final result.

By the way, here's a nice shortcut for the concat() method:

"I love" + " " + "Ad Astra";

Back to arguments. String methods can take numbers as arguments, too:

"caterpillar".charAt(5);

Did you notice something funny about this example? What's the fifth character of the word "caterpillar"? Well, with the way we normally count, "c" is the first letter, and "r" is the fifth. But JavaScript says that the character at the 5th position is "p". That's because computers start counting at zero. So "c" is the zeroth letter, and "r" is the sixth.

It might help to think of this as "The character at position 5" not "fifth".

If you want to put a quote inside a string, you have two options. Here's the first:

"Quoth the raven, \"Nevermore.\"";

The \ is called an escape. It tells JavaScript the the " that comes right after it is not the end of the string, but just a character inside the string.

You can also use single quotes:

'"Programming is fun!", she exclaimed.';

JavaScript generally doesn't care if you use single or double quotes to indicate a string. If you have a lot of double quotes within the string, using single quotes to indicate the string saves you from having to escape all of the double quotes inside.

Calling Functions

So far, none of the JavaScript we've learned has let us do anything with a web page. Let's try something a little more interesting:

alert("Hello world!");

Wow! When you press enter, the page pops open a dialog box that says "Hello world!". Exciting stuff!

alert() is a function. A function is something that performs an action. Just like a method, a function can take an argument. The alert() function pops up a dialog box with the string that you pass in as an argument.

Here's another JavaScript function:

prompt("What is the air-speed velocity of an unladen swallow?");

This dialog box lets you type in a response, and then that response is returned from the function. One cool thing we can do here is a set a variable equal to the response, like this:

var favoriteColor = prompt("What is your favorite color?");
favoriteColor;

Just like we could chain methods to each other, we can also chain methods to a function:

prompt("Type something in lowercase:").toUpperCase();

Try the confirm() function yourself, now.

You should have seen that confirm() returns one of two values: true or false. Notice that there are no quotes around these values. true and false aren't strings - they're called booleans. They simply represent being true or false.

And on that note, you might have noticed that alert() returned undefined, also without quotes. undefined simply represents that nothing has been returned from the function, or that a variable hasn't been assigned a value.

Having now used numbers, strings, booleans, and undefined, you've come across four of the five basic JavaScript data types, or primitives. The last one is null, which represents nothingness. Don't worry about null for now - we'll learn more about it down the road.

Writing Functions

Now that we know how to use a couple JavaScript functions, let's write some ourselves.

We're going to write a very simple function to start:

var sayHi = function() { alert('Hello from Ad Astra!'); };
sayHi();

sayHi() simply pops up a dialog box with the text Hello from Ad Astra!. This isn't terribly useful, so let's write a slightly more interesting function:

var saySomething = function(whatToSay) { alert(whatToSay); };
saySomething("hello");

As you know, we call "hello!" an argument to the function saySomething(). In the saySomething() function, that argument is assigned to the variable whatToSay - we call that variable a parameter. If you're confused about the difference between arguments and parameters, just remember that the argument is the information you pass in, and the parameter is the variable that receives the argument. In this case, "hello!" is the argument, and whatToSay is the parameter. The parameter can then be used just like any other variable.

Okay, on to another, slightly more complex function:

var add = function(number1, number2) { return number1 + number2; };
add(3, 5);

The return keyword tells JavaScript to return the result from that line of code. Without a return, JavaScript will return undefined from the function, which is JavaScript's way of saying something does not have a value.

Let's step through exactly what happens if we call add(3, 5):

  1. We call the add function with the arguments (3, 5).
  2. The add function is run. The parameter number1 is set equal to 3, and the parameter number2 is set equal to 5.
  3. 3 + 5 is run.
  4. The result of 3 + 5 is returned.
  5. The add function ends.

Notice our variables names: number1 and number2. We could have called them n1 and n2, and it would have taken less typing. But the name number1 very clearly expresses what the variable is for, whereas n1 will require another programmer (or your future self, when you come back to your code in a few months and don't remember exactly how it works) to figure it out from context. In this example, it would be pretty obvious what n1 is for. But if you practice choosing descriptive names now and resisting the temptation to abbreviate, you will be in the habit of doing it when you're writing more complex code where it matters more.

Alternatively

Include Code on a Page

So far we have just been experimenting in the console. If you reload the page you're on you will notice that any variables or functions you have defined are gone. Let's add some code somewhere that will stick around.

Create a simple html file index.html

<!doctype html>
<html>
  <head>
    <title>Ad Astra JS 1</title>
  </head>
  <body>
    <h1>Hello, World!</h1>

    <script src="main.js"></script>
  </body>
</html>

Create a JavaScript file named main.js right next to this file

var sayHi = function(name) {
  alert("Hello, " + name);
}

Pull the html page up in your web broser. Open the console and type

sayHi("Developer");

You should see a dialog box that says "Hello, Developer"

Branching

One of the defining features of a programming language is its ability to be used in decision making. Let's teach our code how to make some decisions. Write the following function:

var holidayDrink = function(age) {
    if (age >= 21) {
        return "Eggnog w/rum";
    } else {
        return "Hot Chocolate";
    }
}

Next, invoke the function in the console with a few different arguments

holidayDrink(43);
holidayDrink(21);
holidayDrink(16);

The new part of the JavaScript is called an if...else statement, or a branch. If the condition in the parentheses is true, then the first statement is run. If not, the statement following the else keyword is run.

The curly braces after the if statement don't end with a semicolon. This is because an if statement isn't a statement itself; rather, it's a collection of statements. Or something like that. Just know that it's a rule: no semicolons after the curly braces for if statements.

Also, once again, note the indentation: everything that inside the if and else gets indented in.

You can even make the logic a little more complex:

var holidayDrink = function(age) {
    if (age > 21) {
        return "Eggnog w/rum";
    } else if (age === 21) {
        return "Rum w/eggnog";
    } else {
        return "Hot Chocolate";
    }
}

Notice the triple equals operator. When we're asking whether something is equal, we use === (3 equal signs). When we're setting a variable equal to something, we use =. Mixing these up is one of the easiest syntax errors to make.

JavaScript also has an operator with 2 equal signs, but it is almost never used, and you should generally avoid it. It does things like return true for "2" == 2, but many of its rules are confusing, inconsistent, and hard to remember.

You can make branching as complicated or simple as you need to.

var languageType = function (language) {
    if (language === "JavaScript") {
        return "Programming";
    } else if (language === "CSS") {
        return "Stylesheet";
    } else if (language === "SQL") {
        return "Query";
    } else if (language === "HTML") {
        return "Markup";
    } else {
        return "Unknown";
    }
}

When JavaScript tries to figure out if the condition is true, it's looking for a boolean. Remember booleans - true and false? They were returned from the confirm() function. Check out what's going on here in the JavaScript console:

var age = 22;
age > 21;

TODO Additional branching topics include

  • Operators for "and" (&&) and "or" (||)
  • Nested ifs
  • Loose "true-ish" and "falsey" comparisons

Arrays

Until now, we've always dealt with one piece of information at a time: one number, one string, one element on a page. But often, we need to group things together. For example, what if we wanted to have a list of the months of the year? We'd use an array, which is just a list of things grouped together. An array looks like this:

var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "nov", "dec"];

Here are some more arrays for you to try in the JavaScript console:

[2, 5, 7, 3423, 85, 65];
["a", "d", "a", "s", "t", "r", "a"];
["word", 45, "blah", 123];

You can put variables and expressions in your arrays, or even other arrays:

var variable = "i'm a variable";
[variable, "i'm not a variable"];
[16, 62 / 2, 4 > 5];
["string", 123, ["another string", 456], 321, "yet another string"];

Just like numbers and strings, arrays have methods. Here are a couple for you to start with:

["apple", "orange", "kiwi"].pop();

Output is "kiwi"

[1, 2, 3].reverse();

Output is [3, 2, 1]

You can also add elements to an array, or combine two arrays:

var greetings = [];
greetings.push('hi');
greetings.push('hello');
greetings.concat(['hola', 'buenos dias']);

Note that concat() doesn't actually change the original array, but rather returns a new array that combines the two.

If you want to access an element from an array, the syntax is a bit different from anything we've seen before:

var letters = ["a", "d", "a", "s", "t", "r", "a"];
letters[0];
letters[4];

Just like with strings, we count array elements starting with zero. So the zeroth element of the array is "a", and the fourth element is "t".

Looping

Now that you've got the basics of arrays under your belt, let's turn to a more advanced concept: looping. Here's a very simple loop:

var languages = ['HTML', 'CSS', 'JavaScript'];
languages.forEach(function(language) {
    alert('I love ' + language + '!');
});

To type multiple-line statements into the JavaScript console, you can hold down Alt while you press Enter, so that it knows to create a new line (instead of running the line, as it does by default when you press Enter by itself). You can also use JSFiddle, a site that lets you easily play around with writing and running JavaScript.

Let's step through how this works:

  1. Create an array of strings.
  2. Call the forEach method on the array.
  3. Pass in a callback function to forEach, with a parameter called language.
  4. Take the first element in the array, 'HTML' and assign it to language.
  5. Pop up an alert that says you love HTML.
  6. Repeat 4 and 5 for the other elements in languages.

We can use loops for more interesting problems, too. For example, we've written code to add two numbers, but what if we wanted to add an arbitrary amount of numbers?

var total = 0;
summands = [1, 2, 3, 4, 5];
summands.forEach(function(summand) {
    total += summand;
});
total;

It's conventional that an array name is plural, and that the parameter to the function passed into forEach have a singular name (e.g., summands for the array and summand for the argument to the function). But for all JavaScript cares, the array could be called summands and the argument to the function could be called sofa.

TODO

  • Looping with for, while and do
  • Infinite loops

Getting Help

A great resource for web development is the Mozilla Developer Network. The MDN is one of the best sources of documentation on JavaScript, and you should start to get familiar with it. Take a look at their documentation of string methods.

By the way, MDN is awesome, but you should be wary of other resources you find online. There is a lot of bad information out there, especially on JavaScript, so you should always look to MDN first.

Stack Overflow is another good resource; it's a site for asking and answering questions about programming. You do need to be careful about what you find there, as there is plenty of bad information, but it's a great resource. Just make sure you search to see if somebody has already answered your question before posting. And give back by answering questions for other people!

Finally, if you're stuck on something, chances are, somebody has gotten stuck on it, too - try a search engine. To make sure you get up-to-date results, may find it helpful to limit your results to the past year (in Google, click Search tools in the bar above your search results, and then change All time to Past year).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment