JavaScript for Beginners
Welcome to the beginner course on JavaScript (also commonly known as JS). In this course, you will learn how to code in JS, a flexible yet powerful programming language that is used all over the web. Some of the most popular Internet companies like Facebook and Twitter extensively use JS to add functionality to and enhance their websites.
This course is designed for people who have no prior programming knowledge. In this course, you will learn about fundamental programming concepts through JS. Throughout the course, you will write code to apply what you’ve learned to solve programming problems.
Lesson 1 - Introduction
Simple Addition
Let's get coding! 2 + 3
below and press Enter to see what happens.
2 + 3
) is called an expression, and the evaluation of an expression (e.g. 2 + 3
) in JS always returns a value (e.g. 5
). - Click on the code box (the blue highlighted box above) to enter code.
- Type
2 + 3
in the code box above and press Enter to see the result.
Fun With Text
Let's try using another common element of JS: strings. A string is just a sequence of symbols or characters, like a word or a sentence. Let’s use the name of my favorite language -- JavaScript! "JavaScript"
and press Enter.
- Make sure you surround the word with two double quotes, like this:
"JavaScript"
. - Remember that strings are case-sensitive, so make sure to capitalize the J and the S in JavaScript.
- Type
"JavaScript"
and press Enter.
Combining Text and Numbers
In JS, you can combine both strings and numbers by using the +
operator. "It is currently the year " + 2013;
and press Enter.
Congratulations! You just finished the first section. Ready to move on?
- Make sure that you have the double quotes only around the string.
- Be sure to type the text exactly as shown, and make sure to capitalize the 'I' in 'It'.
- Type
"It is currently the year " + 2013;
, and don't forget the space afteryear
. Include the semicolon for good style (though your code will still work without it).
Lesson 2 - Variables and Operators
Welcome to the second section of the beginner JS course. In this section, we will cover variables and operators. Variables can be used to hold values or expressions. Creating a variable is called declaring a variable. You declare a variable by using the var keyword, like var name;
. You can assign values to variables by using the =
(assignment) operator, like var age = 20;
. Note that unlike in math, the =
operator is the assignment operator, not the equality operator.
Variable Names
JS variable names are case-sensitive (so name
and Name
are different variables), and must begin with a letter, the $ or the _ symbol, and may contain (but not start with) numbers. The common practice in JavaScript is to use lower case characters for variable names. If it consists of more than one word, the common practice is to capitalize all words except the first, e.g.: myAge
. This is know as (lower) camel case.
Operators
Operators are corner stones for any programming language. The most common operators are math operators like +
, which also acts as a string concatenation operator as well in JavaScript as we have seen in the previous lesson. Other common JavaScript operator include the assignment operator =
, and the dot .
operator which accesses properties belonging to an object. We will introduce you to more operators here.
Favorite Language, Again
First, let's go back to what we did in the previous section. "JavaScript"
. Then press Enter.
- Make sure to capitalize the J and the S, since 'j' and 'J' are different in JS.
- Make sure you surround the word with two double quotes, like this:
"JavaScript"
. - Type
"JavaScript"
exactly as shown and press Enter.
What is a Variable?
In the previous exercise, you had to type my favorite coding language again, even though you'd already done so in the first section. Imagine if Facebook had to keep asking you for your favorite music every time you logged in. Wouldn't that be annoying? We need a way to store data so we can refer to it later. Variables are one way to do this.
Let's see how we can create a variable to store my favorite programming language, JavaScript. var favoriteLanguage = "JavaScript";
and press Enter.
favoriteLanguage
. Let's try to understand what you just typed. The first part, var
, lets the JS console know you are declaring a variable. The assignment operator =
tells it that you are trying to assign a value to the variable. Lastly, the string on the right side of the assignment operator is the actual value that you are assigning to the variable. - Make sure the variable name is
favoriteLanguage
, with the same capitalization. Case matters for variable names, sofavoriteLanguage
andFavoriteLanguage
are different variables, for example. - Remember to use the
var
keyword to let the JS console know that you are declaring (creating) a variable. Put quotes around the word. Also, it's good practice to end with a semicolon, which indicates the end of a line of code. - Type
var favoriteLanguage = "JavaScript";
and press Enter to assign the value to the variable.
Your Name
Let's try another example, for practice. myName
and set it to a string containing your name.
- Make sure the variable name is
myName
, with the same capitalization. - Use the
var
keyword to let the console know you are declaring a variable. Put quotes around your name and end with a semicolon for good style. - Type
var myName ="your name here";
and press Enter to run the code.
Let's Make a Sentence
Now that you've created two variables -- one for my favorite coding language and one for your name -- let's use them to create a sentence. "My name is " + ____ + " and I am learning " + ____;
- Make sure to use the same case (e.g. capitalize the 'M' in 'My'), and be careful about what's in quotes and what isn't.
- The variable names don't go inside the quotes.
- Type
"My name is " + myName + " and I am learning " + favoriteLanguage;
exactly as shown (note the space after "is" and "learning") and press Enter. - If
myName
andfavoriteLanguage
is not defined, go back to the above exercises and define them first.
Numbers in Variables
We can use variables to store more than just words (technically strings, but we'll get to that later). You can also use variables to store numbers. myAge
that stores your age.
- Remember to use the
var
keyword to let the JS console know that you are declaring a variable. - Unlike in the previous exercises, you don't need quotes here because your age is a number and not a string.
- Type
var myAge = 22
(or whatever your age is) and press Enter.
Changing Variable Values
An important characteristic of variables is that you can change them once they've been declared. But since you've already created the variable, you don't need to use the var
keyword again to simply change its value. Now, suppose one year has passed and you're one year older. myAge
to reflect your new age?
var oldAge = myAge;
- You can simply assign a new value to the variable. Because you're updating it and not declaring it, you don't need to use the
var
keyword. - If you're currently 22 and you want to update your age to 23, you can just type
myAge = 23;
.
Changing Variable Types
As you just saw, variable values can be changed. Not only can they be changed to values of the same type, but they can also be changed to different data types. myAge
to a string that spells out your current age.
- Remember you don't need to use the
var
keyword since the variablemyAge
was already declared, and you're simply updating its value. - Remember you have to put quotes around the text to tell JS that it's a string.
- If you're 22 years old, type
myAge = "twenty two";
.
Equality
Now that we've created several variables, what can we do besides changing their values? A useful operation is to check if two variables are equal, that is, they have the same value. This is done by using the ==
, or equality, operator. Notice that there are two equal signs instead of one.
alicesAge
and bobsAge
have the same values using the equality operator.
var alicesAge = 19;
false
because Alice is 19 and Bob is 20. If they were the same age, your code would have evaluated to true
. We'covered a few operators already, but check out some other commonly used operators in the description. - You can check if two variables, x and y, have the same value by doing
x == y
. - Type
alicesAge == bobsAge
to check if they have the same value.
What's Your Type?
We've seen that variables have values, but did you know they also have types? The type of a variable is essentially the data type (e.g. string, number, etc.) that the variable stores. So how do we know if a variable stores a number or a string? We can use the handy typeof
operator to figure it out. We've created a variable for you called secret
that contains -- you guessed it -- a secret value.
secret = 42
- You can get the type of a variable by using the
typeof
operator, liketypeof x;
- Type
typeof secret;
and press Enter.
Empty Cans, Empty Variables
Sometimes you might want to create a variable for later use, but don't know the value you want to assign to it just yet. JS lets you declare variables without assigning a specific value. In this case, the variable will have an "undefined"
value. You can do this by declaring a variable and leaving out the assignment operator and any value. emptyCan
.
- You must use the
var
keyword but not the assignment (=
) operator. - This is how you'd declare an undefined variable named
x
:var x;
. - Type
var emptyCan;
and press enter.
Type Check
Now check the type of the variable using the appropriate operator.
"undefined"
.- Make sure you have entered
var emptyCan;
in the above exercise. Now use thetypeof
operator to check its type by typingtypeof emptyCan;
here.
Increment Operator
Now you know how to create and change variables. A common task in programming is incrementing the value of a variable, like we did when we increased the myAge variable by one. This is such a common task that there's a special operator for it in JS, the ++
, or increment, operator. counter
which we have already created for you.
var counter = 1;
--
, which is used to decrease the value of a variable by one. - You can increment a variable by putting
++
after it. - Type
counter++;
and press Enter.
Adding Numbers, Again
What if you wanted to increment the value of a variable by any number, not just one? There is a way to do this using the assignment operator. For example, if you want to increase the value of a variable x
by 10, you can use the code x = x + 10;
.
This works because the code on the right hand side of the assignment operator is evaluated first, then the resulting value is assigned to the variable x
. So JS evaluates x + 10
and then reassigns the result to the variable x
.
counter
by 5.
var counter = 1;
-
operator instead of the +
operator. - Type
counter = counter + 5;
and press Enter.
Another Addition Operator
Adding numbers to variables is such a common task in programming that there is a special operator for it. The +=
operator is short hand for incrementing a variable by a number. For example, instead of x = x + 10;
, you can write x += 10;
. They both do the same thing.
counter
by itself.
var counter = 21;
- Just like with the assignment operator, the right hand side of an expression involving the
+=
operator will get evaluated first, then assigned to the variable on the left hand side. - Type
counter += counter;
and press Enter.
Lesson 3 - Dive Into Strings
Welcome to Lesson 3! In this lesson we'll dig a little deeper into the world of strings, something you've already seen quite a bit of. Strings are useful for a lot of things, including storing text, website URLs, values of form fields, and more.
What Are Strings?
A string is a sequence of characters, such as letters, numbers, and other symbols. When you create strings in JS, you always place single or double quotes around them. The important thing is to be consistent. If you start with a double quote, you must end the string with a double quote. Likewise with a single quotes. Some examples of strings are: "i'm a string"
(notice how the single quote is used within the double quotes), and '123'
. myName
and assign to it a string containing your name
- Remember to put quotes around your name to indicate that it is a string.
- Remember to use the
var
keyword since you are declaring a variable. Use the assignment operator,=
, to assign a value to the variable. - Type
var myName = "your name here";
and press Enter.
Combining Strings
We've already seen in the first lesson that one of the things we can do with strings is combine multiple strings together. Remember we can do this using the +
operator. ls
.
ls="Learning"
+
operator created a new string by copying the characters from "Learn" and "ing". - You can concatenate (combine) two strings, a and b, by doing
a + b
. - Type
var ls = "Learn" + "ing";
and press Enter.
Length of a String
Remember that a string is a sequence of characters. The length of a string is the number of characters in it. Every string in JS has a length
property which stores the number of characters in the string. For example, "keep it up".length
will evaluate to 10 (remember, spaces are characters too).
ls
.
var ls = "Learning";
- You can get the length of a string by using putting
.length
after the variable name. - Type
ls.length;
and press Enter.
Selecting Characters
Imagine that you have a list of strings containing words and you want to sort them alphabetically. You'll need a way to get the first character in each string. You might even need the second or third character if there are multiple words with the same first letter.
The charAt(index)
is a handy way to get the character at a specific position in a string. Keep in mind that strings are zero-indexed, meaning the first position is position 0, the next one is position 1, and the last one is position length - 1.
For example, we can get the character at position 2
in the string "hello"
by doing "hello".charAt(2)
.
ls
?
- Remember that strings are zero-indexed, so the last index is not the length, but rather the length - 1.
- You can get the character at an index by using the
charAt(index)
function. - Type
ls.charAt(ls.length - 1);
and press Enter.
Substrings
It's great that we can get one character using charAt(index)
, but what if we wanted to get a longer part of a string? A contiguous part of a string is called a substring. The substring(start, end)
function gives us a substring starting at the start
index and going up to but not including the end
index.
substring(start, end)
function to select the first word in the string stored in the already created variable message
. It stores the string "Hello World"
.
var message = "Hello World";
- Look at the string "Hello World" and count the index at which you want the substring to end. Remember that
substring(start, end)
returns a substring that stops at one position before theend
index. - Remember that the first position in a string is position 0, the next one is position 1, etc.
- Type
message.substring(0, 5);
and press Enter.
Change to Upper Case
It's time to get angry and yell at people on the Internet! Just joking ;) Instead of holding down the Shift key or using Caps Lock, let's try to code something to do it. We can use the toUpperCase()
function to do this.
message
has been created. Find out the upper case version of it by applying toUpperCase()
on it.
var message = "i used to be lowercase but now i am uppercase";
- You can see an example of how to use
toUpperCase()
in the description section under String Utility Functions. - Type
message.toUpperCase();
and press Enter.
What is your Index?
What if you wanted to check if a string contains a particular character or substring? One way to do this is using the indexOf(value)
function. This function takes a character or string and returns the first index at which it occurs. For example, "the big bang".indexOf("big")
returns 4 because "big" starts at index 4. When the character or string provided is not present, this function returns -1.
We received an email from an unknown source. The content of the email is stored in the variable message
. The way our email application works is if the message contains the word "free", it goes to our spam folder.
var message = "this is not spam!"
- Remember that the
indexOf(value)
function returns an index if the specified character or string is present, and -1 if it isn't. - You can use the
!=
operator to see if two values are not equal. - Type
message.indexOf("free") != -1;
and press Enter.
Reversing a String
Now that we've covered some commonly used string helper functions, let's try to do something a little harder. We're going to give you a string and you're going to return the reverse of the string. For example, if we give you "gum"
, you will return "mug"
.
How do you do this? Remember that we can use the +
operator to combine two strings together, and we can use the charAt(index)
function to get the character at a given index.
The variable message
contains a three letter word. message
?
var message = "yeh";
- Because
message
is three letters long, we know that the last letter ismessage.charAt(2)
, the middle character ismessage.charAt(1)
, and the first character ismessage.charAt(0)
. - Type
message.charAt(2) + message.charAt(1) + message.charAt(0);
and press Enter.
What's the Secret?
Your friend wants to text you a secret message. But she doesn't want to send it in one text, in case your arch nemesis gets hold of your phone. Instead of just sending the secret message in one text, she's going to split up her secret and send you two messages. The first half of the first message combined with the second half of the second message will give you the full secret message.
The first message is stored in message1
and the second message in message2
var message1 = "i ate cake"; var message2 = "aakash wants your cookie";
- You can use the
substring(start, end)
function to get part of a string. Remember that the substring will go up to but not including theend
index. - The middle element of a string is at position
length / 2
. You can assume that the string has an even length. - Type
message1.substring(0, message1.length / 2) + message2.substring(message2.length / 2, message2.length);
and press Enter.
Lesson 4 - Functions
Functions are blocks of code that run only when you tell them to run. For example, in JS, you may want to call a function when a user clicks on a button. Functions are useful because they let you reuse code you've already written, and make your code easier to understand.
Examples
Here is an example of what a function looks like:function function_name() {
// function body
}
The function body resides between the curly braces. This is the chunk of code that gets executed when you call the function.
Sometimes you may want to provide (pass) some values, or arguments, into the function. When you pass these arguments in, the function can use and operate on the values. You can pass multiple arguments into a function by separating them with commas. Here's a function that takes multiple arguments:
function exponent(a, b) {
//code
}
Functions can also return values. This means that when you call such a function, you get a value back. For example, here's a function that returns the square of a number when you call it with a number:
function square(num) {
return num*num;
}
Let's take a closer look at each part of the square
function above. The first thing is the function
keyword. This tells JS that we're creating a function. Next is the name of the function: square
. Since we want this function to accept an argument called num
, the number that we want to square, we put it in between parentheses right after the function name. Now we add the curly braces and put the function body (which contains the code that the function will execute upon being called) between the braces. In order to run (or call) the function, we type its name followed by a pair of parentheses. If we need to provide arguments, we put them between the parentheses. For example, to square the number 5, we write square(5);
.
Naming Conventions
What's a good name for a function? Just as with variables, function names should be descriptive of what the function is supposed to do. For example, square
is a good function name because the square
function return the square of a number. Valid characters for function names are the same as variable names, which must begin with a letter, the $ or _ symbol, and may contain (but not start with) numbers. The common practice for JavaScript function names are same as for variable names, which is to use (lower) camel case like helloWorld
.
Global vs Local Variables
Global variables are variables that can be accessed from anywhere in the file containing the program's JS code. They are defined outside of any function, conventionally at the top of the file (or in our case, the code editor). A local variable is defined inside of a function and can be used only within the function itself. It's not good practice to use the same name for a global and local variable, but if it does happen, the local variable will override the value inside the method. What this is means is if you have a global variable and a local variable with the same name, and you refer to the variable by its name in the function, it will use the value of the local variable instead of the global variable. Let's look at an example:
var counter = 0; // this is a global variable
function test() {
var counter = 5; // local variable
return counter;
}
In this case, test();
will return 5, not 0, since the local counter
variable has the value 5.
Comments
Comments are used to explain your code to other programmers (and yourself!) and to make it more readable. Anything that is commented out are not executed. You can comment out lines of code by starting it with double backslashes (//
). For example, in the following piece of code:someCode(); // This is a comment
someCode();
will be run, but the rest of the line will not since it is commented out. You can also create multi-line comments by surrounding the code block with /*
and */
. For example: /* This is a
.
multi-line
comment*/
Simple Addition Function
Let's write our first function! Take a look at the code in the code editor. We've already written the function header, but we've left out the function body. This function takes two numbers and is supposed to return their sum.
function sum(x, y) {
function sum(x, y) {
//Write a statement below to return the sum.
}
- Remember that
//
indicates that the line of code is a comment. Make sure your statement isn't in the same line as the comment, or it will not be executed. - Use the
return
statement to return a value. Remember that you can add numbers in JS using the+
operator. - Type the following in the code editor and click on the RUN button to check your answer:
function sum(x, y) {
//Write a statement below to return the sum.
return x + y;
}
Division Problem
In the previous exercise, we gave you the function header. This time around, you're going to code a function from scratch. divide
that takes two numbers and returns the first number divided by the second.
/*Write a function below called divide that takes two numbers
/*Write a function below called divide that takes two numbers
and returns the first number divided by the second.
For example, divide(6, 2) should return 3.
Start your function on a new line below this comment block.*/
- Remember what the
sum
function looked like. Here it is for your reference:function sum(x, y) {
return a+b;
} - Use the
/
operator to divide two numbers. - Paste this code below the comment and click on the RUN button:
function divide(x, y) {
return x / y;
}
Capitalize the First Letter
capitalizeFirst
that takes a string and returns another string that is identical to the argument string except that the first letter is capitalizedcapitalizeFirst("david");
should return "David"
.
function capitalizeFirst(str) {
function capitalizeFirst(str) {
/*Write the function body below to return a string that is
identical to str except that its first letter is capitalized.*/
}
- The following string utility functions should be helpful:
charAt(index)
,toUpperCase()
, andsubstring(start, end)
. Remember thatsubstring
does NOT include theend
index. - You can use the
+
operator to combine strings. Make sure to return the result. - Type the following in the code editor and click on the RUN button:
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.substring(1, str.length);
}
Capitalize Names
You're building a website and you want to store everyone's names with correct capitalization. People use all sorts of capitalizations when they enter their first and last name, like "jOhn SMIth", "anne doe", and "david Shi", for example. You want to store names so that only the first letter of the first name and first letter of the last name are capitalized, like "Amy Sue".
capitalizeName
that takes a string containing someone's full name, with their first name and last name separated by a space like "bOb dyLan", and returns the correctly capitalized name, like "Bob Dylan".capitalizeFirst
function which you coded in the previous exercise.
function capitalizeFirst(str) {
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.substring(1, str.length);
}
function capitalizeName(name){
//The string below contains a lower case version of name. Let's use this from now on.
var lowerName = name.toLowerCase();
var spaceIndex = lowerName.indexOf(' ');
var first = lowerName.substring(0, spaceIndex)
//Complete the function body below.
}
- Use the
substring
utility function to extract the last name. - Use the
capitalizeFirst
function to capitalize the first letter of the first and last names. Remember to return the correctly capitalized full name, with the first and last name separated by a space. - Type the following in the code editor and click on the RUN button:
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.substring(1, str.length);
}
function capitalizeName(name){
var lowerName = name.toLowerCase();
var spaceIndex = lowerName.indexOf(' ');
var first = lowerName.substring(0, spaceIndex)
var last = lowerName.substring(spaceIndex + 1, lowerName.length);
return capitalizeFirst(first) + ' ' + capitalizeFirst(last);
}
Square a Number
Let's do some more practice with functions. square
that takes a number and returns the square of that number.
/*Write a function below called square that takes
/*Write a function below called square that takes
a number and returns its square.*/
- The square of a number is the number multiplied by itself.
- Remember how to create a function. You need to use the
function
keyword, followed by the function name, argument(s) inside parentheses, then the function body in between curly braces. - Type the following code into the code editor and click on the RUN button:
function square(num) {
return num * num;
}
Sum of Squares
sumOfSquares
that takes two numbers as arguments and returns the sum of the square of each number.
function square(num) {
function square(num) {
return num * num;
}
//Write your sumOfSquares function below.
- Call the
square
function within this function. - Type the following code in the code editor and click on the RUN button:
function sumOfSquares(a, b) {
return square(a) + square(b);
}
Area of Triangle
Let's write a function that might be useful if you have geometry homework. triangleArea
that takes two numbers -- base
and height
-- and returns the area of a triangle with the given base and height.
function triangleArea(base, height) {
function triangleArea(base, height) {
/*Complete the function body below to return the area of a
triangle with the given base and height.*/
}
- Remember to return the computed area.
- Type the following code in the code editor and then click on the RUN button:
function triangleArea(base, height) {
return 0.5 * base * height;
}
Just Came to Say Hello
Now we are going to code a function that says 'hello' to you. hello
that takes in one argument, your name, and returns the string "Hello, " followed by your name.
function hello(name){
function hello(name){
//Complete the function body below to say hello to name.
}
- Remember that every character matters. Don't forget to capitalize the H, and don't omit the comma or the space.
- Type this in the code editor and click on the RUN button:
function hello(name) {
return "Hello, " + name;
}
Global Variables
In this exercise, we won't be returning a value. We are instead modifying a global variable, x. Write the function incrementX
that increments the variable x
by amount
.
var x = 10;
var x = 10;
function incrementX(amount) {
//Write code to increment x by amount. Don't return anything.
}
Congratulations on completing your fourth lesson!
Thank you for trying out our new approach on language learning. That is all the lessons we have at the moment. Please shoot me an e-mail (john @ this domain) to let me know how you like this new course learning experience.
- Remember not to return anything here.
- Use
+=
to increase a variable by the givenamount
. - Type the following code below the global variable x in the code editor and click on the RUN button:
function incrementX(amount) {
x += amount;
}