JavaScript Console for Beginners

These exercises will familiarize you with writing JavaScript, using the console. Open it now. Google open javascript console if you don’t know how. Use the console to test and practice JavaScript statements, methods, etc.

console.log('Hello, world!');

console.log(5);

console.log(3 + 6);

console.log('foobar');

console.log(foobar); // error

JavaScript Variables

A variable can be described as a kind of container. We assign a value to a variable. We can change the value later. A variable is a word. It cannot include spaces. Variable name on the left. Variable value on the right.

let fruit = 'apple';

console.log(fruit);

let fruit = 'pear'; // error

fruit = 'pear';

console.log(fruit);

let pears = 5;

let apples = 2;

console.log( apples + pears );

JavaScript Strings

A string is simply text. It must be enclosed in quotation marks or backticks. Strings can contain any kind of characters, including numbers and punctuation.

let firstName = 'Harry';

let lastName = 'Potter';

console.log(firstName + lastName); // fix this?

let address = "4 Privet Dr., Little Whinging, Surrey RH10";

console.log(address);

We can do things to strings:

JavaScript Strings (2)

Q: What is a backtick and when do we use it?
A: Mainly for template literals, which work like this:

let name = 'Chris';

let faveBook = "The Wind-Up Bird Chronicle";

let faveMovie = 'Wings of Desire';

let result = `${name}'s favorite movie is ${faveMovie} and favorite book is ${faveBook}.`;

console.log(result);

Without template literals, you'd need to make that string with plus signs:

result = name + "'s favorite movie is " + faveMovie + " and favorite book is " + faveBook + ".";

Find the backtick key to the left of the number "1" key on your computer.

JavaScript Numbers

Numbers are not strings, and you can do math with numbers. As we've seen before, we can also put numbers into variables. The order of operations (PEMDAS) matters.

2 + 9

20 - 7

12 * 9

100 / 7

Exponent: 2**8

Modulus (remainder): 27 % 4

PEMDAS: 20 + 2 * 10

PEMDAS: (20 + 2) * 10

JavaScript Strings Plus Numbers

We can add strings together (concatenate them). Can we add a string to itself? Can we multiply strings? Can we add strings and numbers?

let word = "umbrella";

word + word

console.log(word);

word = word + word;

console.log(word);

word + word

5 + "foo"

5 + "5" // no coercion

5 * "5" // coercion

5 * "foo" // NaN

JavaScript Random Numbers

We often want a random number for use in games, or even for offering new content. You can always look this up when you need it.

In the console, use the up-arrow to repeat a line you previously entered.

Math.random() // several times

Math.random() * 100 // several times

Math.floor(Math.random() * 100) // several times

Math.floor(Math.random() * 6) // 0 through 5

Math.floor(Math.random() * 6) + 1 // 1 through 6

JavaScript and Booleans

Boolean values are true or false, nothing else. Here we can test Boolean values with comparison operators.

100 < 10

100 > 10

10 <= 100

10 >= 100

10 == "10" // true

10 === "10" // false

This is all pretty standard until we get to that triple equals sign (===), which tests for strict equivalence in JavaScript.

We can test "not equal" with !== or != (note that !== is the strict one).

Note that the true and false values are all lowercase in JavaScript, and they are NOT strings.

JavaScript Logical Operators

The logical operators are and, or, not. In JavaScript these are represented by && (and), || (or), ! (not). When we use a logical operator between two statements, the result is a Boolean value (true or false).

and

true true true
true false false
false true false
false false false

or

true true true
true false true
false true true
false false false

// false AND true: returns false
(100 < 10) && (1 > 0)

// false OR true: returns true
(100 < 10) || (1 > 0)

JavaScript and “Not”

One of the three logical operators is not (represented by !). Let's see how not works with a variable. We will change the value several times.

let foobar; // a new variable with no assigned value

!foobar; // true

foobar = 0;

!foobar; // true

foobar = "something";

!foobar; // false

foobar = null;

!foobar; // true

foobar = undefined;

!foobar; // true

JavaScript Data Types

In the previous example, you saw two new data types: Null and Undefined. (The others are String, Number, and Boolean.*) Unlike the other JavaScript data types, each of these has only one possible value: null for Null and undefined for Undefined.

let savings; // a new variable with no assigned value

console.log(savings);

savings === undefined; // true

savings = null;

console.log(savings);

savings === undefined; // false

typeof savings;

* Actually these are called primitive data types, and there is one more: Symbol.

JavaScript if–else if–else

if-statements allow us to create branching paths in code. If the first thing is true, the first code block executes. If the second thing is true, the first code block is ignored, and the second code block executes. And so on. if-statements are referred to as conditionals or control flow. We can have one, many, or no else if statements between if and else.

if (someCondition) {
   // instructions;
} else if (anotherCondition) {
   // different instructions;
} else {
   // other instructions;
}

We will use Repl.it (https://repl.it/) to work on if-statements.

JavaScript and Truthiness

A statement in JavaScript is considered true unless its value is one of these six:

Test it like this:

let test = null;
if (test) {
  console.log("It is true.");
} else {
  console.log("It is NOT true.");
}

Live example: Truthiness

JavaScript’s Switch Statement

This is useful when you need to test a large number of possible conditions — instead of writing "else if" many, many times.

A switch statement requires a variable. The value of the variable will have been assigned outside the switch statement.

switch (someVariable) { }

For each possible value the variable might have, provide the value, then write all the instructions, and end with break; (required).

case "wizard":
   console.log("Only a Wizard can cast spells.");
   // as many statements as needed
   break;

Finally, provide a default condition at the end of the switch statement, in case the value given was not valid:

default:
   console.log("You must choose a type.");
   break;

Live example: Switch statement - basic

JavaScript Arrays

An array is essentially a list of values, or variables, or both together.

let shopping = ['bread', 'cheese', 'apples'];

The items in an array are ordered, which means we can reliably use them by referring to their position in the array. Note that the first position has an index of 0.

console.log(shopping[0]);

console.log(shopping[1]);

This position number is called an index. We can change the value of an item at a particular index:

shopping[2] = 'oranges';

console.log(shopping);

JavaScript Arrays (2)

An array has a length property. Arrays also have a lot of useful methods, which you can look up as you need them. Two of the most comonly used are shown below.

let shopping = ['milk', 'eggs', 'bread'];

let total = shopping.length;

console.log(`Please buy ${total} items.`);

shopping.push('peanut butter');

console.log(shopping);

let removed = shopping.pop();

console.log(shopping);

console.log(removed);

Live example: Array basics

JavaScript Loops

A loop allows us to easily repeat the same code again and again. In some cases we know exactly how many times we want to repeat the code. Then we use a for-loop. If we don't know how many times it will be necessary to repeat the code, we use a while-loop.

Here is a basic for-loop:

for (let i = 0; i < someValue; i++) {
   // instructions;
}

The three parts in parentheses are the KEY to how the loop runs:

Live example: 4 for-loops

Increment and Decrement

If you need to add 1 to a variable, or subtract 1 from a variable, JavaScript has a nifty shorthand for you to use:

If you need to increase the variable's value by more than 1, or decrease it by more than 1, there is a slightly longer shorthand:

Note: This does not work with a variable that was initialized with const — you must use let to allow the value to be changed.

JavaScript Loops (2)

If we don't know how many times it will be necessary to repeat the code, we use a while-loop. When we use a while-loop, we must be sure the loop will be forced to stop at some point, or else the loop will run forever (an infinite loop) and crash the browser.

A while-loop starts with a condition to be tested. If the condition is false at the start, the loop will never run at all.*

To prevent an infinite loop, eventually the tested condition must become false.

while (someCondition) { // doThings; }

Live example: while-loop

* If you need the loop to run once no matter what (even with a false condition), see the do...while statement. If there's no chance the starting condition would be false, then don't use a do...while-loop.

JavaScript’s .forEach() Method

It's perfecty fine to use a regular for-loop to loop over an array. There's also another way to do it, and it does not include (let i = 0; i < someValue; i++). Here it is:

arrayName.forEach(function(item) {
    // doThings;
});

The code you write between the curly braces will be run on every item in the array. You use item (or whatever variable name you put in the function) to stand for each array item. For example:

console.log(item);

There's no way to halt the loop in this case (you can halt a regular for-loop).

Live example: .forEach()

We haven't covered functions yet — they are next! What we have here is an anonymous function (it has no name) fully enclosed in the parentheses of forEach().

JavaScript Functions

A function is a bundle of code instructions. Usually a function has a name. If it doesn't, it is called an anonymous function.

By bundling code into short(ish) functions, we make it modular, easier to debug, easier for others to understand and maintain, and easier to reuse and repurpose in future projects.

JavaScript provides several ways to write a function. Here are three:

function someName(a, b) { //instructions; }

const someName = function (a, b) { //instructions; };

const someName = (a, b) => { //instructions; };

In all cases, the instructions (code) would be exactly the same. We cause a function to run by calling it, like this:

someName(value1, value2);

Live example: Function Examples 1

JavaScript Functions (2)

function someName(a, b) { //instructions; }

const someName = function (a, b) { //instructions; };

The a and b in parentheses are parameters.

You can think of them as variables that exist only inside the function. A function may have no parameters, or one, or many. Whatever names you give to the parameters when you define the function will be used inside the curly braces — the code block — the instructions.

Note that if no parameters are given, empty parentheses are required — with no space between them.

JavaScript Functions (3)

The returned value from a function can be used elsewhere in the script — outside the function.

Some functions do not return anything. A function that rewrites the contents of an HTML file, for example, doesn't need to return anything. In Eloquent JavaScript, author Marijn Haverbeke says, "Showing a dialog box or writing text to the screen is a side effect. A lot of functions are useful because of the side effects they produce."

When we want a function to return a value, we write a return statement inside the function:

return someValue;

The value that is returned may come from an evaluated statement:

return someValue + 10;

We can "catch" the returned value in a variable:

let answer = someFunFunction(x, y);

JavaScript Functions (4)

Let's review basic facts about functions.

When you are writing a function, think about its purpose and name it accordingly. For example, if I want to calculate the gas mileage of a car, I might call the function getGasMileage.

JavaScript Function Exercise

The best way to learn to code is to practice. To really understand functions, you should write a lot of short functions to solve short problems.

This is a typical, basic function exercise:

  1. Write a function that searches in a string for a shorter string. (You can Google string method includes.)
  2. The function takes two arguments: a string and a shorter string.
  3. The function returns true or false.

Building on the first function exercise, try this one next:

  1. Write a function that searches every item in a list for a given string.
  2. The function takes two arguments: an array and a string to search for.
  3. Return a new array of all items that contain that string.

Live example: JavaScript Function Exercise

More function exercises: Exercises, Practice, Solution

This is the final section.