Definition of Javascript

JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. The language has since been adopted by all other major graphical web browsers. It has made modern web applications possible— applications with which you can interact directly without doing a page reload for every action. JavaScript is also used in more traditional websites to provide various forms of interactivity and cleverness.

It is important to note that JavaScript has almost nothing to do with the programming language named Java.

Variables

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules:

  1. A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($)
  2. subsequent characters can also be digits (0-9)
  3. Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Declaring variables

You can declare a variable in three ways:

  1. With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables.
  2. By simply assigning it a value. For example, x = 42.This always declares a global variable. It generates a strict JavaScript warning
  3. And let y = 13.This syntax can be used to declare a block scope local variable. See Variable scope below.

Variable scope

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

if (true) { var x = 5; } console.log(x); // 5

The words var and const can also be used to create bindings, in a way similar to let.

var name = "Ayda"; const greeting = "Hello "; console.log(greeting + name); // → Hello Ayda

The first, var (short for “variable”), is the way bindings were declared in pre-2015 JavaScript. I’ll get back to the precise way it differs from let in the next chapter. For now, remember that it mostly does the same thing, but we’ll rarely use it in this book because it has some confusing properties. The word const stands for constant. It defines a constant binding, which points at the same value for as long as it lives. This is useful for bindings that give a name to a value so that you can easily refer to it later.

Types of variables

Numbers

Values of the number type are numeric values. In a JavaScript program, they are written as follows:

13

Fractional numbers are written by using a dot. Like example:

9.81

For very big or very small numbers, you may also use scientific notation by adding an e (for exponent), followed by the exponent of the number.

2.998e8 That is 2.998 × 108 = 299,800,000.

Strings

The next basic data type is the string. Strings are used to represent text. They are written by enclosing their content in quotes.

`Down on the sea` "Lie on the ocean" 'Float on the ocean'

You can use single quotes, double quotes, or backticks to mark strings, as long as the quotes at the start and the end of the string match.

Strings cannot be divided, multiplied, or subtracted, but the + operator can be used on them. It does not add, but it concatenates—it glues two strings together. The following line will produce the string "concatenate":

"con" + "cat" + "e" + "nate"

Boolean values

It is often useful to have a value that distinguishes between only two possibilities, like “yes” and “no” or “on” and “off”. For this purpose, JavaScript has a Boolean type, which has just two values, true and false, which are written as those words.

Comparison

Here is one way to produce Boolean values:

console.log(3 > 2) // → true

Logical operators

There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: and, or, and not. These can be used to “reason” about Booleans.

The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true.

console.log(true && false) // → false console.log(true && true) // → true

The || operator denotes logical or. It produces true if either of the values given to it is true.

console.log(true || false) // → true console.log(false || false) // → false

Not is written as an exclamation mark (!). It is a unary operator that flips the value given to it—!true produces false, and !false gives true.

The last logical operator I will discuss is not unary, not binary, but ternary, operating on three values. It is written with a question mark and a colon, like this:

console.log(true ? 1 : 2); // → 1 console.log(false ? 1 : 2); // → 2

The value on the left of the question mark “picks” which of the other two values will come out. When it is true, it chooses the middle value, and when it is false, it chooses the value on the right.

Empty values

There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

Function

Functions are the bread and butter of JavaScript programming. The concept of wrapping a piece of program in a value has many uses. It gives us a way to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.

The most obvious application of functions is defining new vocabulary. Creating new words in prose is usually bad style. But in programming, it is indispensable.

Defining a function

A function definition is a regular binding where the value of the binding is a function. For example, this code defines square to refer to a function that produces the square of a given number:

const square = function(x) { return x * x; }; console.log(square(12)); // → 144

A function is created with an expression that starts with the keyword function . Functions have a set of parameters (in this case, only x) and a body, which contains the statements that are to be executed when the function is called. The function body of a function created this way must always be wrapped in braces, even when it consists of only a single statement.

A function can have multiple parameters or no parameters at all. In the following example, makeNoise does not list any parameter names, whereas power lists two:

const makeNoise = function() { console.log("Pling!"); }; makeNoise(); // → Pling! const power = function(base, exponent) { let result = 1; for (let count = 0; count < exponent; count++) { result *= base; } return result; }; console.log(power(2, 10)); // → 1024

Declaration notation

function square(x) { return x * x; }

This is a function declaration. The statement defines the binding square and points it at the given function. It is slightly easier to write and doesn’t require a semicolon after the function

Arrow Function

const power = (base, exponent) => { let result = 1; for (let count = 0; count < exponent; count++) { result *= base; } return result; };

Instead of the function keyword, it uses an arrow (=>) made up of an equal sign and a greater-than character (not to be confused with the greaterthan- or-equal operator, which is written >=).

Optional Arguments

If you write an = operator after a parameter, followed by an expression, the value of that expression will replace the argument when it is not given. For example, this version of power makes its second argument optional. If you don’t provide it or pass the value undefined, it will default to two, and the function will behave like square.

function power(base, exponent = 2) { let result = 1; for (let count = 0; count < exponent; count++) { result *= base; } return result; } console.log(power(4)); // → 16 console.log(power(2, 6)); // → 64

Closure

function wrapValue(n) { let local = n; return () => local; } let wrap1 = wrapValue(1); let wrap2 = wrapValue(2); console.log(wrap1()); // → 1 console.log(wrap2()); // → 2

This example defines a function, wrapValue, that creates a local binding. It then returns a function that accesses and returns this local binding.

This feature—being able to reference a specific instance of a local binding in an enclosing scope—is called closure. A function that references bindings from local scopes around it is called a closure.

Arrays

JavaScript lets you create and group together data in more interesting ways with arrays. An array is just a list of other JavaScript data values.

Example of array

var dinosaurs = [ "T-Rex", "Velociraptor", "Stegosaurus", "Triceratops", "Brachiosaurus", "Pteranodon", "Apatosaurus", "Diplodocus", "Compsognathus" ];

Accessing an Array’s Elements

When it’s time to access elements in an array, you use square brackets with the index of the element you want, as you can see in the following example:

dinosaurs[0]; "T-Rex" dinosaurs[3]; "Triceratops"

An index is the number that corresponds to (or matches) the spot in the array where a value is stored. Just as with strings, the first element in an array is at index 0, the second is at index 1, the third at index 2, and so on. That’s why asking for index 0 from the dinosaurs array returns "T-Rex" (which is first in the list), and index 3 returns "Triceratops" (which is fourth in the list).

Setting or Changing Elements in an Array

You can use indexes in square brackets to set, change, or even add elements to an array. For example, to replace the first element in the dinosaurs array ("T-Rex") with "Tyrannosaurus Rex", you could do this:

dinosaurs[0] = "Tyrannosaurus Rex"; After you’ve done that, the dinosaurs array would look like this: ["Tyrannosaurus Rex", "Velociraptor", "Stegosaurus", "Triceratops", "Brachiosaurus", "Pteranodon", "Apatosaurus", "Diplodocus", "Compsognathus"]

Adding Elements to an Array

.push()

To add an element to the end of an array, you can use the push method. Add .push to the array name, followed by the element you want to add inside parentheses, like this:

var animals = []; animals.push("Cat"); 1 animals.push("Dog"); 2 animals.push("Llama"); 3 animals; ["Cat", "Dog", "Llama"] animals.length; 3

.unshift()

To add an element to the beginning of an array, you can use .unshift(element), like this:

animals; ["Cat", "Dog", "Llama"] animals[0]; "Cat" animals.unshift("Monkey"); 4 animals; ["Monkey", "Cat", "Dog", "Llama"] animals.unshift("Polar Bear"); 5 animals; ["Polar Bear", "Monkey", "Cat", "Dog", "Llama"] animals[0]; "Polar Bear" animals[2]; "Cat"

Removing Elements from an Array

.pop()

To remove the last element from an array, you can pop it off by adding .pop() to the end of the array name. The pop method can be particularly handy because it does two things: it removes the last element, and it returns that last element as a value. For example, let’s start with our animals array, ["Polar Bear", "Monkey", "Cat", "Dog", "Llama"]. Then we’ll create a new variable called lastAnimal and save the last animal into it by calling animals.pop().

animals; ["Polar Bear", "Monkey", "Cat", "Dog", "Llama"] var lastAnimal = animals.pop(); lastAnimal; "Llama" animals; ["Polar Bear", "Monkey", "Cat", "Dog"] animals.pop(); "Dog" animals; ["Polar Bear", "Monkey", "Cat"] w animals.unshift(lastAnimal); 4 animals; ["Llama", "Polar Bear", "Monkey", "Cat"]

.shift()

To remove and return the first element of an array, use .shift():

animals; ["Llama", "Polar Bear", "Monkey", "Cat"] var firstAnimal = animals.shift(); firstAnimal; "Llama" animals; ["Polar Bear", "Monkey", "Cat"]

You can use unshift and shift to add and remove items from the beginning of an array just as you’d use push and pop to add and remove items from the end of an array.

Adding Arrays

To add two arrays together to make a new, single array, you can use firstArray.concat(otherArray). The term concat is short for concatenate, a fancy computer science word for joining two values together. The concat method will combine both arrays into a new array, with the values from firstArray added in front of those from otherArray.

You can use concat to join more than two arrays together. Just put the extra arrays inside the parentheses, separated by commas:

var furryAnimals = ["Alpaca", "Ring-tailed Lemur", "Yeti"]; var scalyAnimals = ["Boa Constrictor", "Godzilla"]; var featheredAnimals = ["Macaw", "Dodo"]; var allAnimals = furryAnimals.concat(scalyAnimals, featheredAnimals); allAnimals; ["Alpaca", "Ring-tailed Lemur", "Yeti", "Boa Constrictor", "Godzilla", "Macaw", "Dodo"]

Finding the Index of an Element in an Array

To find the index of an element in an array, use .indexOf(element). Here we define the array colors and then ask for the index positions of "blue" and "green" with colors.indexOf("blue") and colors.indexOf("green"). Because the index of "blue" in the array is 2, colors.indexOf("blue") returns 2. The index of "green" in the array is 1, so colors.indexOf("green") returns 1.

var colors = ["red", "green", "blue"]; colors.indexOf("blue"); 2 colors.indexOf("green"); 1

If the element whose position you ask for is not in the array, JavaScript returns -1.

If the element appears more than once in the array, the indexOf method will return the first index of that element in the array.

var insects = ["Bee", "Ant", "Bee", "Bee", "Ant"]; insects.indexOf("Bee"); 0

Turning an Array into a String

You can use .join() to join all the elements in an array together into one big string.

var boringAnimals = ["Monkey", "Cat", "Fish", "Lizard"]; boringAnimals.join(); "Monkey,Cat,Fish,Lizard"

You can use .join(separator) to do the same thing, but with your own chosen separator between each value. The separator is whatever string you put inside the parentheses

var boringAnimals = ["Monkey", "Cat", "Fish", "Lizard"]; boringAnimals.join(" - "); "Monkey - Cat - Fish - Lizard" boringAnimals.join("*") "Monkey*Cat*Fish*Lizard" boringAnimals.join(" sees ") "Monkey sees Cat sees Fish sees Lizard"
Objects

Objects in JavaScript are very similar to arrays, but objects use strings instead of numbers to access the different elements. The strings are called keys or properties, and the elements they point to are called values. Together these pieces of information are called key-value pairs. While arrays are mostly used to represent lists of multiple things, objects are often used to represent single things with multiple characteristics, or attributes.

Basic syntax for creating an object:

var cat = { "legs": 3, "name": "Harmony", "color": "Tortoiseshell" };

When you create an object, the key goes before the colon (:), and the value goes after. The colon acts a bit like an equal sign—the values on the right get assigned to the names on the left, just like when you create variables. In between each key-value pair, you have to put a comma. In our example, the commas are at the ends of the lines—but notice that you don’t need a comma after the last keyvalue pair (color: "Tortoiseshell"). Because it’s the last key-value pair, the closing curly bracket comes next, instead of a comma.

Keys Without Quotes

var cat = { legs: 3, name: "Harmony", color: "Tortoiseshell" };

JavaScript knows that the keys will always be strings, which is why you can leave out the quotes. If you don’t put quotes around the keys, the unquoted keys have to follow the same rules as variable names: spaces aren’t allowed in an unquoted key, for example. If you put the key in quotes, then spaces are allowed:

var cat = { legs: 3, "full name": "Harmony Philomena Snuggly-Pants Morgan", color: "Tortoiseshell" };

Accessing Values in Objects

Square brackets

You can access values in objects using square brackets, just like with arrays. The only difference is that instead of the index (a number), you use the key (a string).

cat["name"]; "Harmony"

Dot notation

Instead of typing the key name in quotes inside square brackets after the object name, we just use a period, followed by the key, without any quotes. As with unquoted keys in object literals, this will work only if the key doesn’t contain any special characters, such as spaces.

cat.name; "Harmony"

Objects keys

Instead of looking up a value by typing its key, say you wanted to get a list of all the keys in an object. JavaScript gives you an easy way to do that, using Object.keys():

var dog = { name: "Pancake", age: 6, color: "white", bark: "Yip yap  yip!" }; var cat = { name: "Harmony", age: 8, color: "tortoiseshell" }; Object.keys(dog); ["name", "age", "color", "bark"] Object.keys(cat); ["name", "age", "color"]

Adding Values to Objects

An empty object is just like an empty array, but it uses curly brackets, { }, instead of square brackets:

var object = {};

You can add items to an object just as you’d add items to an array, but you use strings instead of numbers:

var cat = {}; cat["legs"] = 3; cat["name"] = "Harmony"; cat["color"] = "Tortoiseshell"; cat; { color: "Tortoiseshell", legs: 3, name: "Harmony" }

Combining Arrays and Objects

var dinosaurs = [ { name: "Tyrannosaurus Rex", period: "Late Cretaceous" }, { name: "Stegosaurus", period: "Late Jurassic" }, { name: "Plateosaurus", period: "Triassic" } ];

To get all the information about the first dinosaur, you can use the same technique we used before, entering the index in square brackets:

dinosaurs[0]; { name: "Tyrannosaurus Rex", period: "Late Cretaceous" }

If you want to get only the name of the first dinosaur, you can just add the object key in square brackets after the array index:

dinosaurs[0]["name"]; "Tyrannosaurus Rex"

Or, you can use dot notation, like this:

dinosaurs[1].period; "Late Jurassic"

***You can use dot notation only with objects, not with arrays.

The delete operator

The delete operator cuts off a tentacle from such an octopus. It is a unary operator that, when applied to an object property, will remove the named property from the object. This is not a common thing to do, but it is possible.

let anObject = {left: 1, right: 2}; console.log(anObject.left); // → 1 delete anObject.left; console.log(anObject.left); // → undefined console.log("left" in anObject); // → false console.log("right" in anObject); // → true

Object.assign

let objectA = {a: 1, b: 2}; Object.assign(objectA, {b: 3, c: 4}); console.log(objectA); // → {a: 1, b: 3, c: 4}

The Math object

Math is a grab bag of number-related utility functions, such as Math.max (maximum), Math.min (minimum), and Math.sqrt (square root).

Math.random

This is a function that returns a new pseudorandom number between zero (inclusive) and one (exclusive) every time you call it.

// → 0.36993729369714856 75 console.log(Math.random()); // → 0.727367032552138 console.log(Math.random()); // → 0.40180766698904335

If we want a whole random number instead of a fractional one, we can use Math.floor (which rounds down to the nearest whole number) on the result of Math.random.

console.log(Math.floor(Math.random() * 10)); // → 2

Multiplying the random number by 10 gives us a number greater than or equal to 0 and below 10. Since Math.floor rounds down, this expression will produce, with equal chance, any number from 0 through 9. There are also the functions Math.ceil (for “ceiling”, which rounds up to a whole number), Math.round (to the nearest whole number), and Math.abs, which takes the absolute value of a number, meaning it negates negative values but leaves positive ones as they are.

Embedding JavaScript in HTML
<! DOCTYPE html > <html > <head > <title >My first proper HTML page< /title > </head> <body> <h1>Hello world!</ h1> <p>My first web page.</ p> <script> var message = "Hello world!"; console.log(message); </script> </body> </html>

Writing the code in your HTML

Here we’ve added a new element, called script. This is a special element in HTML. With most HTML elements, the content between the opening and closing tags is displayed on the page. With script, on the other hand, everything between the tags is treated as JavaScript and run by the JavaScript interpreter. Now let’s look at the code inside the script element:

Using the script tag to include an external JavaScript file

To include an external JavaScript file, we can use the script tag with the attribute src. You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

This script tag should be included between the tags in your HTML document.

Conditional and loops

If statement

The if statement is the simplest of JavaScript’s control structures. It’s used to run code only if a condition is true.

var name = "Nicholas"; console.log("Hello " + name); if (name.length > 7) { console.log("Wow, you have a REALLY long name!");

An if statement has two main parts: the condition and the body. The condition should be a Boolean value. The body is one or more lines of JavaScript code, which are executed if the condition is true.

if…else Statements

If you want something else to happen when the condition is false, you need to use an if...else statement. Let’s extend the example from earlier:

var name = "Nicholas"; console.log("Hello " + name); if (name.length > 7) { console.log("Wow, you have a REALLY long name!"); } else { console.log("Your name isn't very long."); }

This does the same thing as before, except that if the name isn’t longer than seven characters, it prints out an alternative message. If...else statements look like if statements, but with two bodies. The keyword else is placed between the two bodies. In an if...else statement, the first body is run if the condition is true; otherwise, the second body is run.

Chaining if…else Statements

var lemonChicken = false; var beefWithBlackBean = true; var sweetAndSourPork = true; if (lemonChicken) { console.log("Great! I'm having lemon chicken!"); } else if (beefWithBlackBean) { console.log("I'm having the beef."); } else if (sweetAndSourPork) { console.log("OK, I'll have the pork."); } else { console.log("Well, I guess I'll have rice then."); }

To create a chain of if...else statements, start with a normal if statement and, after the closing brace of its body, enter the keywords else if, followed by another condition and another body. You can keep doing this until you run out of conditions; there’s no Conditionals and Loops 95 limit to the number of conditions. The final else section will run if none of the conditions is true.

Loops

while Loops

A while loop repeatedly executes its body until a particular condition stops being true. By writing a while loop, you are saying, “Keep doing this while this condition is true. Stop when the condition becomes false.”

var sheepCounted = 0; while (sheepCounted < 10) { console.log("I have counted " + sheepCounted + " sheep!"); sheepCounted++; } console.log("Zzzzzzzzzzz"); /* I have counted 0 sheep! I have counted 1 sheep! I have counted 2 sheep! I have counted 3 sheep! I have counted 4 sheep! I have counted 5 sheep! I have counted 6 sheep! I have counted 7 sheep! I have counted 8 sheep! I have counted 9 sheep! Zzzzzzzzzzz*/

Preventing Infinite Loops: when you’re using loops: if the condition you set never becomes false, your loop will loop forever (or at least until you quit your browser).

For Loops

When setting up a for loop, you create a variable, specify the condition, and say how the variable should change after each cycle—all before you reach the body of the loop.

var timesToSayHello = 3; for (var i = 0; i < timesToSayHello; i++) { console.log("Hello!"); } Here is the output: Hello! Hello! Hello!

If we were the JavaScript interpreter running this code, we would first create a variable called timesToSayHello and set it to 3. When we reach the for loop, we run the setup, which creates a variable i and sets it to 0. Next, we check the condition. Because i is equal to 0 and timesToSayHello is 3, the condition is true, so we enter the loop body, which simply outputs the string "Hello!". We then run the increment, which increases i to 1. Now we check the condition again. It’s still true, so we run the body and increment again. This happens repeatedly until i is equal to 3. At this point, the condition is false (3 is not less than 3), so we exit the loop.

Using for Loops with Arrays and Strings

One very common use of for loops is to do something with every element in an array or every character in a string. For example, here is a for loop that prints out the animals in a zoo:

var animals = ["Lion", "Flamingo", "Polar Bear", "Boa Constrictor"]; for (var i = 0; i < animals.length; i++) { console.log("This zoo contains a " + animals[i] + "."); } /*Running this would output: This zoo contains a Lion. This zoo contains a Flamingo. This zoo contains a Polar Bear. This zoo contains a Boa Constrictor.*/

Another example:

var name = "Nick"; for (var i = 0; i < name.length; i++) { console.log("My name contains the letter " + name[i] + "."); } This would output: My name contains the letter N. My name contains the letter i. My name contains the letter c. My name contains the letter k.

Other Ways to Use for Loops

As you might imagine, you don’t always have to start the looping variable at 0 and increment it by 1. For example, here’s a way to print all the powers of 2 below the number 10,000:

for (var x = 2; x < 10000; x = x * 2) { console.log(x); }
Bibliography