Prerequisites

Introduction

Welcome to this course on JavaScript, the programming language around HTML and the web.

Let's get started by displaying what we're in here for.

var part1 = "We're in here for ";
var part2 = "JavaScript";
console.log(part1 + part2);

//Output Below

We're in here for JavaScript

Look at that! Together, we've created a little script that displays a sentence. But what exactly is a so-called script?

Scripts

Scripts are programs that accompany webpages. They run in web browsers and make web pages more dynamic and powerful.

This time, let's put the script in a webpage and tell the whole world what we're up to.

//HTML Document

<!doctype html>
<html>
 <body>
  <script>
   var part1 = "We're in here ";
   var part2 = "for JavaScript";
   document.write(part1 + part2);
  </script>
 </body>
</html>

//Inside a Web Browser

Fantastic! Now that we've made our intentions clear, we're ready to dive in.

Psst: if you've mastered the course on HTML, these angle brackets will look very familiar.

Variables

Variables are containers that help us remember information for later.

We create them with the word var and a name, or identifier, and give them a value with the = sign.

var name = "Kwesi";
var age = 42;
console.log(name);

//Output Below

Kwesi

See that? name and age are variables that contain information, or data. When we put them in the parentheses of console.log(), we reveal their content.

This is off-limits!

These identifiers have to be unique and should start with a lowercase letter. Some words, however, aren't available as identifiers.

Let's find out what happens if we break that rule!

var var;

//Output Below

Uncaught SyntaxError: Unexpected token function

Whoa, what a strange message! Let's not use these reserved words, then!

Console output

There are a bunch of ways to display data in JavaScript. In this course, we'll use the browser console and actual webpages.

console.log("Kwesi");
document.write("I'm on the Web!");

//Output Below

Kwesi

See that? Anything we put in the parentheses of console.log() displays in the browser console. What we pass to document.write() displays on the web page.

String-ing along

There are different types of data. We've already seen strings, which are sequences of characters.

Let's create a string together.

var name = "Joe";
console.log(name);

//Output Below

"Joe"

Strings can have pretty much any value, as long as we write it between single or double quotes.

Numbers

Do you remember the age variable? It's proof that we can store numbers as well.

Let's try it out!

var name = "Kwesi";
var age = 42;
console.log(age);

//Output Below

42

Way to go! These numbers can but don't have to have a decimal point.

Semicolons

Have you noticed how we put a semicolon at the end of every line we wrote? Basically, these semicolons mark the end of a statement.

var name;
var age; 
name = "Kwesi";
age = 42;
console.log(name);
console.log(age);

//Output Below

Kwesi
42

Sweet! Unless we write multiple statements in a single line, these semicolons are optional. Nevertheless, it's good practice to use them.

Comments

What if there are things we want to tell everybody who reads a script we wrote?

/* Script by Joe */
var name = "Kwesi";
var age = 42; 
console.log(name);

//Output Below

Kwesi

That's it, we can provide comments! They can contain pretty much anything, because they're ignored by the browser.

Single-line comments span from // to the end of a line. Multi-line comments start with /* and end with */.


Declaring

Let's talk some more about variables! In order to create a variable we need to create it with the var keyword. That's what we call a declaration.

So let's declare the name variable!

var name;
console.log(name);

//Output Below

undefined

Good stuff! But why does name seem to be undefined?

Assigning

Ah, yes: it's undefined because it doesn't have a value! We use the equal sign to give, or assign, values to variables.

var name = "Kwesi";
var age;
age = 42;
console.log(name);
console.log(age);

//Output Below

Kwesi
42

Sweet! We can either assign a variable when we declare it or assign it later.

Psst: interestingly enough, undefined is a value. We'll talk about that a little later, no worries!

Strings

Strings are a data type that we've already touched upon. In order to create a string variable, we assign a series of characters in quotes to, well, a variable.

var string = "Kwesi's string";
console.log(string);

//Output Below

Kwesi's string

We use single or double quotes even inside a string, as long as they don't match the surrounding quotes.

Integers

As we already know, numbers can be whole numbers or have a decimal place. Whole numbers are also known as integers.

Let's create an integer variable, shall we?

var age = 42;
console.log(age);

//Output Below

42

What a cute little integer variable!

Floats

For the sake of completeness, let's assign a float, a number with a decimal place, to the height variable!

var height = 1.72;
console.log(height);

//Output Below

1.72

Nice! The maximum number of decimal places JavaScript can handle is 17, so we won't find the last digit of Pi this way.

Psst: behind the scenes of JavaScript, every number is a decimal.

Data types

So we know about data types. What if we want to know what type of data a variable contains?

var name = "Kwesi";
var age = 42;
var height = 1.72;
console.log(typeof(name));

//Output Below

string

See that? While "Kwesi" is a string, 42 and 1.72 are numbers, despite the fact that age is an integer and height is a float.

Arithmetic operators

So what are numbers good for? For example, we can use them for arithmetic operations.

var r = 4 + 2;
var pi = 3.141592653589793;
console.log(2 + r * pi);

//Output Below

20.84955592153876

See that? We can use +, -, * and /, which we call arithmetic operators, to perform these, well, operations.

Shortcuts

The ++ sign, which is also known as the increment operator, increases a number by 1. The decrement operator, on the other hand, decreases a number by 1.

Let's try to increment the age variable here.

var age = 42;
age++;
console.log(age);

//Output Below

43

Incrementing and decrementing is easy with these little shortcuts.

More shortcuts

Certain assignment operators can change values as well. The += sign, for example, adds a number. How might we subtract a number, then?

var height = 1.72;
height -= 0.2;
console.log(height);

//Output Below

1.52

Nice! The height -= 0.2 statement is a shortcut for height = height - 0.2.

Psst: there are *= and /= operators as well.

\"Hello\" + ?

Just like adding a number to a number, we can add strings to each other.

Let's give it a go!

var a = "Today, the weather is ";
var b = "delightful";
var c = a + b;
console.log(c);

//Output Below

Today, the weather is delightful

Sweet! Adding strings together concatenates them. Of course we can't use the - operator on strings.


Equality

There's an important data type that we didn't talk about so far, which has something to do with comparisons.

var equality1 = 3 == 3;
var equality2 = "Apples" == "Oranges";
console.log(equality1);
console.log(equality2);

//Output Below

true
false

Whoa! The == sign determines equality between values. If the values are equal, the comparison returns true; otherwise, it returns false.

Psst: be careful not to confuse the == operator with =, the assignment operator.

Greater or less

true and false are boolean values. When we check if a value is greater than or less than another, we also get a boolean value in return.

var boolean = 3 > 6;
console.log(boolean);

//Output Below

false

The > operator, for example, determines if a value is greater than some other value and results in true if it is.

Greater or less or equal

While we're at it, we can also use the >= and <= operators to compare values. Would you mind?

Let's try and log true in the console.

var boolean = 3 >= 0;
console.log(boolean);


Output Below


true

Nice! Again this comparison results in a boolean value.

Inequality

The != sign is a comparison operator that'll result in true if the values we're comparing are different, or not equal.

Let's try and log true to the console.

var boolean = 3 != 1;
console.log(boolean);

//Output Below

true

See that? If the values are the same, on the other hand, the != operator will return false.

Psst: when we compare a number with a string, JavaScript will silently convert the string into a number.

Equal value and type

Before we go out and play, let's turn to a special kind of comparison operator that requires the value and the type to be equal.

What might it look like?

var boolean = 3 === "3";
console.log(boolean);

//Output Below

false

Fantastic! === will only result in true if the value and the type are exactly the same, which isn't the case when we compare a number with a string.

Logical and

If we want to make sure that more than just a single condition is met before we return true, we can use the logical and.

var b = 5 < 10 && 10 < 15;
console.log(b);

//Output Below

true

Great! The logical and uses the && sign and needs every condition to be true in order not to be false.

Logical or

Alternatively, if we only require one out of two comparisons to be true, we can use the logical or.

var b = 5 > 10 || 10 > 15;
console.log(b);

//Output Below

false

See that? || returns true as soon as one of the two comparisons result in true.

Opposite day

There's a logical operator, and the final operator that we'll cover, that changes the value of a boolean to its opposite.

var boolean = true" class="literal;
var opposite = !boolean;
console.log(opposite);

Great! That exclamation point is called the logical not. If a condition is true, then the logical not operator will make it false and vice versa.

Conditional operator

What about another shortcut? The conditional operator assigns a value to a variable based on a condition being true or false.

var time = 7;
var advice = time >= 10 ? "Go to bed" : "Stay up";
console.log(advice);

//Output Below

Stay up

Good job! This operator assigns values to variables based on conditions. If they're met, it uses the value after the ? sign; if not, it uses that after the : sign.

Psst: this operator is also known as the ternary operator.

Stranger strings

While it's possible to compare strings with each other using operators other than == and !=, it can lead to unexpected results.

var b = "4" > "33";
console.log(b);

//Output Below

true

Strange, isn't it? When we compare strings, JavaScript uses an alphabetical order. Therefore, "4" is greater than "3", the character that "33" starts with.


If

Now that we know about booleans, how about we put them to action?

The if keyword allows us to execute a piece of code based on a condition, a boolean value.

var temperature = 50;
if(temperature > 100) {
 console.log("Boy, it's hot!");
}

See that? The code block in the braces is executed if the condition we've specified in the parentheses is true.

Else

We can use the else keyword if we want to execute a different code block when the condition in the if statement returns false.

var temperature = 100;
if(temperature > 100) {
 console.log("Boy, it's hot!");
} else {
 console.log("Pretty normal.");
}

//Output Below

Pretty normal.

You're onto it! An else statement will only run if the if statement isn't met.

Else if

What if two scenarios just aren't enough? Well, we can use the else if keyword to bring in another condition.

var temperature = 20;
if(temperature > 100) {
 console.log("Boy, it's hot!");
} else if(temperature < 32) {
 console.log("Jeez, it's cold!");
} else {
 console.log("Pretty normal.");
}

//Output Below

Jeez, it's cold!

Look at you go! An else if statement allows us to evaluate another condition if the condition after that follows the if keyword is false.

Unlimited else ifs

We can have an unlimited number of else if sections.

var name = "Richard";
if (name == "Richard") {
 console.log("Hello Richard");
} else if (name == "Erlich") {
 console.log("Hallo Erlich");
} else if (name == "Jian-Yang") {
 console.log("Ni hao Jian-Yang");
} else {
 console.log("");
}

//Output Below

Hello Richard

See that? If statements have to start with the if keyword and end with else. In between, however, we can throw in as many else if sections as we want.

Nesting

We can also put an if statement into another if statement in order to reduce the number of times we check a condition.

Let's see if number is a digit between 0 and 9!

var number = -5;
if (number >= 0) { 
 if (number < 10) {
  console.log("It's a digit!");
 } else { 
  console.log("It's not a digit!");
 }
}

See that? The inner if statement is only relevant if the outer if statement evaluates to true. This practice is also known as nesting.

Logical operators

Sometimes, however, we can get the same functionality with a simpler method: logical operators.

Again, let's see if n is a digit between 0 and 9!

var n = 5;
if (n >= 0 && n < 10) {
 console.log("It's a digit!");
} else { 
 console.log("It's not a digit!");
}

//Output Below

It's a digit!

Sweet! With the logical and we can further reduce the complexity of this conditional statement.

Switching it up

However, if we have so many conditions that look at the same variable, it might make sense to use switch, or a switch statement, instead.

var name = "Richard";
switch (name) {
 case "Richard":
  console.log("CEO");
  break;
 case "Erlich":
  console.log("Board member");
  break;
 case "Jian-Yang":
  console.log("Intern");
  break;
 default:
  console.log("Unknown");
}

//Output Below

CEO

Fantastic! Switch statements look for matches in the cases we define with the case keyword. At the end of a case, we use break to exit the statement.

Psst: the default case, which uses the default keyword, is triggered if none of the other cases are a match.

Switching again

Why is the break keyword so important, though? Well, without it, the switch statement will run all the way to the end of the block.

var name = "Richard";
switch (name) {
 case "Richard":
  console.log("CEO");
 case "Erlich":
  console.log("Board member");
 case "Jian-Yang":
  console.log("Intern");
 default:
  console.log("Unknown");
}

//Output Below

CEO
Board member
Intern
Unknown

Whoa! That's why we normally use the break keyword in every case, except for the default case.

Non-boolean values

When we use non-boolean values, they're automatically converted into boolean values.

var value = "Kwesi";
if (value) {
 console.log("Triggered!");
} else {
 console.log("Not triggered!");
}

//Output Below

Triggered!

Excellent! If these non-boolean values have a real value, the condition returns true.

More non-boolean values

Does that mean every non-boolean value returns true when it's part of a condition?

var value = 0;
if (value) {
 console.log("Triggered!");
} else {
 console.log("Not triggered!");
}

//Output Below

Not triggered!

No. Values like 0, "" and undefined, which have no real value, return false. However, "false" is treated like any other string and, therefore, returns true.



Concat!

Strings are more powerful than we might think. Let's take a closer look at them, shall we?

We already know that we can add strings together with the + operator. There's another way to concatenate them, though.

var part1 = "When Harry met ";
var part2 = "Sally";
var s = part1.concat(part2);
console.log(s);

//Output Below

When Harry met Sally

Awesome! If we want, we can use the concat() method instead of the + operator.

Length

Strings also have a length property to tell us how many characters they have.

var part1 = "When Harry met ";
var part2 = "Sally";
var s = part1 + part2;
console.log(s.length);

//Output Below

20

Sweet! Everything between the quotation marks, even the spaces, counts as characters.

Single or double?

When we use double quotes to create a string, we can't use double quotes within the string. When we use single quotes, we can't really use apostrophes.

var quotes1 = "Rick's Café";
var quotes2 = '"I know that I know nothing." - Socrates';
console.log(quotes1);
console.log(quotes2);

//Output Below

Rick's Café
"I know that I know nothing." - Socrates

See that? For example, if we'd use single quotes for "Rick's Café", we'd cut it off right after 'Rick' and, what's worse, we'd get an error.

The Great (String) Escape

A better way to get around this problem is to place a \ sign before the quote that's within the string, a practice that we call escaping.

var quotes1 = 'Rick\'s Café';
var quotes2 = "\"I know that I know nothing.\" - Socrates";
console.log(quotes1);
console.log(quotes2);

//Output Below

Rick's Café
"I know that I know nothing." - Socrates

Way to go! With the \ sign, or escape character, we can use apostrophes and quotes within strings.

Slicing

With the slice() method, we can extract a piece of a string.

var s = "Hi there! My name is Kwesi.";
console.log(s.slice(21, 26));

//Output Below

Kwesi

See that? The numbers that we pass to slice() are the start and end position of the string we want to extract.

Psst: if we use negative values, the position is counted from the end of the string.

Substring

The substr() method behaves like slice(), except that the second value we give it specifies the length of the piece we want to extract.

var s = "Hi there! My name is Kwesi.";
console.log(s.substr(10));

//Output Below

My name is Kwesi.

Excellent! Again, the second number is optional. If we don't provide it, the piece spans all the way to the end of the original string.

Searching and replacing

Also, we can use the replace() method to search and replace occurrences of a string within a string.

Let's change this generic greeting and make it greet you!

var g1 = "Hello World!";
var g2 = g1.replace("World", "You");
console.log(g2);

//Output Below

"Hello You"

See that? replace() searches for the value we give it and, in return, gives us a string within which the occurrences are replaced.

Changing cases

We can change a string to use lowercase letters using toLowerCase(). Might there be a way to convert a string to uppercase letters as well?

var g1 = "Hello World!";
var g2 = g1.toUpperCase();
console.log(g2);

//Output Below

HELLO WORLD!

Sweet! There's nothing better than a greeting in uppercase letters.



Numbers

Let's talk some more about numbers! We won't go deep into math but, as it turns out, they have properties and methods as well.

var age = 42;
var height = 1.72;
console.log(typeof age);

//Output Below

number

Sweet! As we've seen, there's only a single type of number in JavaScript: number.

Type conversions

When we try to use a value of a data type that isn't made for a certain operation, JavaScript tries to convert it to a data type that is.

var number = "10" + 10;
console.log(number);

//Output Below

1010

See that? The results of these automatic type conversions aren't always what we'd expect.

NaN

Another curious concept of JavaScript is NaN, which tells us that a value is not a number. But why is NaN a thing?

Let's get to the bottom of this question with another experiment!

var number = 20 / "Kwesi";
console.log(number);

//Output Below

NaN

Huh! While we can divide by "12", trying to perform arithmetic with a non-numeric string like "Kwesi" will result in NaN.

Psst: even though NaN stands for not a number, its type is number.

Parsing

We can turn numeric strings into numbers either by using parseInt() for whole numbers or parseFloat() for floating-point numbers.

var s = "49.99 USD";
var price1 = parseInt(s);
var price2 = parseFloat(s);
console.log(price1 + " " + price2);

//Output Below

49 49.99

See that? These strings can contain non-numeric characters as long as they start with a number.

Psst: parsing is the process of analyzing and, well, processing a string.

Rounding

We can use the Math.round() method to round a number up or down to the nearest whole number.

var pi = 3.141592653589793;
var number = Math.round(pi);
console.log("Pi is now " + number);

//Output Below

Pi is now 3

Fantastic! Always remember that values below 0.5 will be rounded down, and from 0.5 upwards will be rounded up.

Psst: don't ever say that to a mathematician!

Math

Math is an object that contains several constants like Math.PI and methods like Math.random() that help us solve mathematical problems.

var number = Math.PI;
var random = Math.random();
console.log(number);
console.log(random);

//Output Below

3.141592653589793
0.45374651692506784

Sweet! Math.PI is a constant, a variable that can't be changed, and Math.random() produces a random number between 0 and 1.

Date

Another object, Date, lets us work with dates and time. What's different between Date and Math is that we use the word new to create a so-called instance of it.

var date = new Date("1985-10-21");
document.write(date);

//Output Below

Mon Oct 21 1985 00:00:00 GMT

Sweet! A date consists of a year, a month, a day, an hour, a minute, a second and milliseconds.

Getting dates

As they're objects themselves, these dates have a bunch of methods that help us use them.

Let's build a date string ourselves, shall we?

var date = new Date("1985-10-21");
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
console.log(year + "/" + month + "/" + day);

//Output Below

1985/10/21

Nice! What's up with the + 1, though? Well, getMonth() returns the month as a number that starts with 0. So does getDay() with the weekday, by the way.

Using dates

We can use these dates in a number of ways. For example, we can change, compare and display them.

var d1 = new Date(1985, 10, 21);
var d2 = new Date(d1.getTime());
d2.setFullYear(2015);

if (d1 < d2) {
 console.log(d1.toDateString() + " is \"less\" than " + d2.toDateString());
} else {
 console.log(d1.toDateString() + " isn't \"greater\" than " + d2.toDateString());
}

//Output Below

Mon Oct 21 1985 is "less" than Wed Oct 21 2015

Sweet! Did you notice how we created d1 and d2? The getTime() method returns the time in milliseconds from January 1, 1970.



Why arrays?

An array is a special kind of variable that contains several values of a type or even different types.

var things = ["raindrops", "roses", "whiskers", "cats"];
console.log(things);

//Output Below

["raindrops", "roses", "whiskers", "cats"]

Sweet! Arrays are great way to store related values.

Creating

As we've seen, we create an array when we assign values in brackets to a variable. We can also use empty brackets to create an empty array, though.

var things = [];
console.log(things);

//Output Below

[]

Sweet! When we use [], the array literal, to create an array, we can use multiple values, a single value or no values at all.

Accessing

But how do we get to these values? Well, arrays have positions, or index positions, for that. In order to access a value, we put its index in brackets after the array name.

var things = ["raindrops", "roses", "whiskers", "kittens"];
console.log(things[0]);

//Output Below

raindrops

See that? Like strings, months and days of the week, these index positions start at 0.

Converting

Arrays are objects as well, which means they have a bunch of methods at their disposal as well.

Let's use a method to turn this array into a string, shall we?

var things = ["raindrops", "roses", "whiskers", "kittens"];
console.log(things.toString());

//Output Below

raindrops,roses,whiskers,kittens

Great job! The toString() method turns an array into a comma-separated string. The same applies to join() if we don't give it a string as a separator.

Length

As with strings, there's a property that tells us how long an array is.

var things = ["raindrops", "roses", "whiskers", "kittens"];
console.log(things.length);

//Output Below

4

Nice! The length property keeps track of the number of values in the array.

Manipulating

Not only can we access a value through its index, we can also change and even add values with index numbers.

var things = ["raindrops", "roses", "whiskers", "kittens"];
things[0] = "kettles";
console.log(things);

//Output Below

["kettles", "roses", "whiskers", "kittens"]

Wow! We can change an existing value with its index number but we can also use the length property to add a value to the end of the array.

Splitting strings

We've already created strings from arrays. Why shouldn't we be able to create arrays from strings, then?

var sentence = "raindrops and roses and whiskers and kittens";
var things = sentence.split(" and ");
console.log(things);

//Output Below

["raindrops", "roses", "whiskers", "kittens"]

See that? We can use a string's split() method with a separator to split the string into an array of so-called substrings.

Pushing the boundaries

In order to add values at the end of an array, we can also use the .push() method.

var things = ["raindrops", "roses", "whiskers", "kittens"];
things.push("kettles");
console.log(things);

//Output Below

["raindrops", "roses", "whiskers", "kittens", "kettles"]

Sweet! That's the same thing as assigning a value at the index of things.length.

Popping

Now that we've talked so much about adding values to arrays, how about we move on to removing some?

var things = ["raindrops", "roses", "whiskers", "kittens"];
var thing = things.pop();
console.log(things);
console.log(thing);

//Output Below

["raindrops", "roses", "whiskers"]
kittens

Fantastic! The pop() method removes the last value from the array. If we assign it to a variable, the variable receives the removed value.

Shifting

What if we want to remove a value from the beginning of an array, though? Again, there's a method for that.

var things = ["raindrops", "roses", "whiskers", "kittens"];
things.shift();
console.log(things[0]);

//Output Below

roses

Awesome! shift() removes a value from the beginning and moves, or shifts, all the other values to a lower index.

Unshifting

The unshift() method is kind of like the opposite of shift() in that it adds a value at the beginning of an array.

Do you have anything to add to this array of things?

var things = ["raindrops", "roses", "whiskers", "kittens"];
things.unshift("guitars");
console.log(things);

//Output Below

["guitars", "raindrops", "roses", "whiskers", "kittens"]

Good job! When we add a value with unshift(), all the other values get pushed to a higher index.

Psst: we can also use unshift() with multiple values.

Splicing

Let's talk about a method that can add, insert, replace and remove values: splice(), which takes two numbers and, after that, a variable number of values.

var things = ["raindrops", "roses", "whiskers", "kittens"];
things.splice(1, 1);
console.log(things);

//Output Below

["raindrops", "whiskers", "kittens"]

Wow! The numbers define an index and how many values we want to remove at that index. The optional values we provide will be added at the index.

Sorting things out

Finally, we can use the sort() method to, well, sort, an array in alphabetical order. If we want to reverse that order, we can use reverse() on the array.

var things = ["raindrops", "roses", "whiskers", "kittens"];
things.sort();
console.log(things);

//Output Below

["kittens", "raindrops", "roses", "whiskers"]

What a neat and tidy array we have there!

Psst: when we use a method after another on an object in the same statement, we're said to chain these methods.


Why loops

Something we want to avoid for readability and simplicity reasons are pieces of code that perform very similar actions.

var numbers = [3, 7, 14, 15, 22, 41];
numbers[0]++;
numbers[1]++;
numbers[2]++;
numbers[3]++;
numbers[4]++;
numbers[5]++;
console.log(numbers);

//Output Below

[4, 8, 15, 16, 23, 42]

What a waste of time! How can we get rid of this redundant code, though?

For loops

Yes, of course: we can use loops to repeat these pieces of code for as often as we want.

Let's start with the for loop, shall we?

var s = "";
for(var i = 0; i < 5; i++) { 
  s += i;
}
console.log(s);

//Output Below

01234

See that? In the parentheses after the word for, we put a control variable, a condition and a way to make the condition false at some point.

Arrays

Why don't we use such a loop to increment the values of the array from earlier on?

var numbers = [3, 7, 14, 15, 22, 41];
for(var i = 0; i < numbers.length; i++) { 
 numbers[i]++;
}
console.log(numbers);

//Output Below

[4, 8, 15, 16, 23, 42]

Fantastic! The loop will start with 0 and, well, loop until i isn't less than numbers.length anymore. That's exactly what we need for the indices of number.

For-in

There's another way to loop through arrays with for, using the in keyword.

var things = ["raindrops", "roses", "whiskers", "kittens"];
for (var thing in things) {
 console.log(things[thing]);
}

//Output Below

raindrops
roses
whiskers
kittens

See that? Every time the loop runs, thing holds a different index number from the things array.

While loops

The while loop, another kind of loop, loops through a piece of code as long as a specific condition is true.

var numbers = [3, 7, 14, 15, 22, 41];
var i = 0;
while (i < numbers.length) {
 numbers[i]++;
 i++;
}
console.log(numbers);

//Output Below

[4, 8, 15, 16, 23, 42]

Sweet! We use the while keyword to create a while loop. As these loops don't have control variables, we need to make sure that the condition becomes false.

Do-while

A slight variation of the while loop is the do-while loop, which, unsurprisingly, uses the keywords do and while.

var numbers = [3, 7, 14, 15, 22, 41];
var i = 0;
do {
 numbers[i]++;
 i++; 
}
while (i < numbers.length);

//Output Below

[4, 8, 15, 16, 23, 42]

See that? A do-while loop runs at least once, even if the condition is false. That's because the loop runs the piece of code before it checks the condition.

Taking breaks

At times, we might want to stop looping early, for which we can use the break keyword.

for (var i = 0; i < 5; i++) {
 if (i == 1) {
  break;
 }
 console.log("Counting to " + i);
}

//Output Below

Counting to 0

Great work! The loop checks the condition in the if statement every time it comes around. When the condition is met, it'll break out of the loop.

Continuing

Alternatively, if we want to skip a specific iteration but continue with the loop, we can use continue.

for(var i = 0; i < 5; i++) {
 if(i == 1) {
  continue;
 }
 console.log("Counting to " + i);
}

//Output Below

Counting to 0
Counting to 2
Counting to 3
Counting to 4

Nifty, huh? The continue keyword is useful if we need to skip a specific iteration of a loop.


Why functions

In a nutshell, functions are blocks of code that perform a specific task. But why are they useful?

var r1 = 12;
var area1 = r1 * r1 * Math.PI;
console.log(area1);

//Output Below

452.3893421169302

Does it really make sense to write these lines every time we want to calculate the area of a circle? Well, no. That's what functions are for.

Creating

In order to create a function, we use the function keyword, a unique name and a pair of parentheses. Once created, we can reuse it whenever we feel like it.

function sayHello() {
 console.log("Hello!");
}
sayHello();

//Output Below

Hello!

Simple as that! Everything we put in the braces becomes a part of the function. But why doesn't it display anything?

Invoking

Ah, yes! In order to get a function to run, we need to call, or invoke it.

function sayHello() {
 console.log("Hello!");
}
sayHello();

//Output Below

Hello!

There it is! We invoke a function by writing its name followed by parentheses.

Parameters

Do you remember when we passed values to methods like console.log()? As it turns out, we can do the same with functions if we include parameters.

function calculateArea(radius) {
 var result = radius * radius * Math.PI;
 console.log(result);
}
calculateArea(10);

//Output Below

314.1592653589793

See that? Parameters are temporary variables that we define in the parentheses after the function name and use to access values that we pass to the function.

Psst: these values are also known as arguments.

Multiple parameters

We can also create functions with multiple parameters. In the function definition, we simply separate them with commas.

function insert(array, value, index) {
 array.splice(index, 0, value);
}
var things = ["raindrops", "roses", "kittens"];
insert(things, "whiskers", 2);
console.log(things);

//Output Below

["raindrops", "roses", "whiskers", "kittens"]

Fantastic! We need to pass these arguments in the right order, of course.

Returning values

Just like many methods return values, we can have a function give back a value by putting a return keyword before the value we want to, well, return.

function calculateArea(radius) {
 var result = radius * radius * Math.PI;
 return result;
}
var area = calculateArea(10);
console.log(area);

//Output Below

314.1592653589793

Great job! The return keyword allows us to get results from functions.

Expressing functions

We can also define and store functions in variables. After we've assigned a function to a variable, we can use the variable just like a function.

var add = function(n1, n2) { return n1 + n2 };
var number = add(1, 1);
console.log(number);

//Output Below

2

Great! If we'd assign a function to a variable without parentheses, the variable would store the function itself, as opposed to the value it returns.

Psst: this statement is also known as a function expression.



Why objects

So far we've gotten along well with variables and arrays. Why would we need objects, another type of container? Let's find out!

Do you remember the name, age and height variables from earlier on?

var name = "Kwesi";
var age = 42;
var height = 1.72;
console.log(name);

//Output Below

Kwesi

Don't these variables kind of belong together? Besides, what if we want to have variables for the name, age and height of another person?

Creating

Objects are variables that contain several values, or properties. We create an object using a pair of braces, which we also call an object literal.

var person = {};
console.log(typeof person);

//Output Below

object

So far so good. But aren't arrays also variables that contain several values?

Properties

Compared to the values of arrays, the properties of objects have an important advantage: a name.

var person = {name: "Joe", age: 42, height: 1.72};
console.log(person);

//Output Below

{name: "Joe", age: 42, height: 1.72}

Nice! We create these properties with a name and a value that we separate with a colon. The properties, then, are separated by commas.

Accessing

We can use these names to access values. Let's try!

var person = {
 name: "Kwesi",
 age: 42,
 height: 1.72
};
console.log(person.name);

//Output Below

Kwesi

Good work! We can access the name property using a bracket or a dot notation.

Changing

We can change the values of these properties by, well, assigning different values to them.

var person = {
 name: "Kwesi",
 age: 42,
 height: 1.72
};
person.age = 58.0;
console.log(person);

//Output Below

{name: "Kwesi", age: 58.0, height: 1.72}

Sweet! But not only can we change properties that way, we can also create properties by assigning values to the names.

Deleting

What if we want to get rid of a property, though? We can use a handy little keyword to, well, delete it.

var person = {
 name: "Kwesi",
 age: 42,
 height: 1.72
};
delete person.height;
console.log(person);

//Output Below

{name: "Kwesi", age: 42}

Huzzah! The delete keyword deletes the whole name-value pair that makes up the property.

Methods

Methods are nothing but functions that belong to objects and perform actions on them.

var person = {
 name: "Kwesi",
 age: 42,
 height: 1.72,
 speak: function() {
  console.log("Hi, I'm " + this.name + "!";
 }
};
person.speak();

//Output Below

Hi, I'm Kwesi!

Great work! We define a method by assigning a function expression to a property and invoke it just like a regular function.

Psst: the word this points to the particular object that the speak() method belongs to. It helps us distinguish between properties and parameters.

Constructors

What if we want to create multiple objects with the same properties and methods but different values?

function Person(name, age, height) {
 this.name = name;
 this.age = age;
 this.height = height;
 this.speak = function() {
  console.log("Hi, I'm " + this.name + "!";
 }
}
var p1 = new Person("Kwesi", 42, 1.72);
console.log(p1.name); 

//Output Below

Kwesi

Boom! By creating a constructor function, we can use the new keyword to create as many instances of an object as we want.


Computer Programs

Computers are incredibly powerful machines, capable of performing amazing feats like playing competitive chess, serving thousands of web pages, or making millions of complex calculations in less than a few seconds. But deep down, computers are actually pretty dumb. Computers can only do exactly what we humans tell them to do. We tell computers how to behave using computer programs, which are just sets of instructions for the computers to follow. Without programs, computers can’t do anything at all!

Computers can't even understand English or any other spoken language but only programming languages like JavaScript.


What is JavaScript

JavaScript can control how a web page looks or make the page respond when a viewer clicks a button or moves the mouse.

Popular websites like google , facebook , twitter and ... use JavaScript to make it easier to send email, post comments, or browse websites.


Why Learn JavaScript?

JavaScript isn’t the only programming language out there — in fact, there are literally hundreds of programming languages. But there are many reasons to learn JavaScript. For one, it’s a lot easier (and more fun) to learn than many other programming languages. But perhaps best of all, in order to write and run JavaScript programs, all you need is a web browser like Mozilla Firefox, or Google Chrome. Every web browser comes with a JavaScript interpreter that understands how to read JavaScript programs.


Let's Write Some JavaScript

Install Chrome on your computer (if it’s not already installed), and then open it and type about:blank in the address bar.Now press ENTER and you’ll see a blank page.

We’ll begin by coding in Chrome’s JavaScript console, which is a secret way programmers can test out short JavaScript programs. On Microsoft Windows or Linux, hold down the CTRL and SHIFT keys and press J. On Mac OS, hold down the COMMAND and OPTION keys and press J.

If you’ve done everything correctly, you should see a blank web page and, beneath that, a blinking cursor ( ) next to a right angle bracket ( > ). That’s where you’ll write JavaScript!

When you enter code at the cursor and press ENTER , JavaScript should run, or execute, your code and display the result (if any) on the next line. For example, type this into the console:

3 + 4;

Now press ENTER . JavaScript should output the answer ( 7 ) to this simple bit of addition on the following line:

3 + 4;

7

Well, that’s easy enough. But isn’t JavaScript more than a glorified calculator?


Writing Longer Code in the Console

Unlike our addition program,other huge JavaScript program like the idea in your head right now, will take up multiple lines. To type those program into the console, you’ll have to add new lines by pressing SHIFT-ENTER at the end of each line. (If you just press ENTER , Chrome will try to execute what you’ve written, and the program won’t work as expected. I warned you that computers were dumb!)


Is the console that good?

The browser-based JavaScript console that used is great for trying out small snippets of code, but in order to create actual programs, we’ll need something a bit more flexible, like a web page with some JavaScript in it.


Embedding JavaScript in HTML

JavaScript code is usually added to our HTML web pages using the <script></script> tags.

Note: If the tag thing looks weird, I suggest you take our HTML course before you start here.