[JavaScript Beginner‘s Guide]Background and introduction

JavaScript Beginner’s Guide

1. Introduction

In this guide, we will not provide in-depth detail about any one feature. This is to avoid confusion and the feeling of being overwhelmed. We will only explain what it is and how to use it. We will provide short and simple examples to ensure understanding. This guide is not meant for looking up syntax. It is meant for reading in its entirety to solidify your understanding of the language. In other words, you can use this guide as a supplement to other JavaScript resources you may find. By using this approach, we are hoping that once you have used this guide to learn JavaScript, you will feel competent and comfortable in your ability to use the language.
We are taking an untraditional approach to learning JavaScript. In most programming guides, you will find a plethora of in-depth information on each language feature. They usually specify which are important and which can be disregarded. Often, in the end, you are overwhelmed with too much information. You feel like you need to memorize everything you have learned before learning anything else. This approach comes from teaching with the intent of making the reader feel satisfied at the completion of each chapter. We want to make you feel such satisfaction to urge you to continue learning more. With this in mind, we teach you the basics of JavaScript and slowly lead you to more complex features in order to include every type of learner. This way, the reader will retain the information and will be able to use what he/she has learned immediately.
Welcome to the JavaScript Beginner’s Guide! If you are reading this, chances are you are brand new to programming in general. If not, perfect! Either way, you are at the right place. The primary goal of the JavaScript Beginner’s Guide is to let you be able to teach yourself the language. After all, that is the most effective learning technique. Simply reading this guide from beginning to end will not make you a JavaScript expert. You must use the examples and try writing the code yourself.

1.1 About the Content

The primary goal of this content is to build solid foundations of JavaScript knowledge to readers who are totally new to programming or have little experience, as well as those who are already experienced with JavaScript, enabling them to understand the language in more depth. The content is designed in such a way that it’s easy to follow, simple and each example builds on top of the previous one. Each chapter should take the reader one step further in understanding JavaScript. Inline exercises and end of chapter questions are also provided to further enhance learning. The content covers specific JavaScript features as well as general programming techniques and concepts (control structures, recursion, data hiding, etc). This means that even if you don’t use JavaScript, this book can still be of value to you because the concepts are easily translated to other languages. This is IDC’s third JavaScript title. Learn JavaScript Now! covers the very basics, and JavaScript: A Beginner’s guide gives a broader understanding of JavaScript and more of an insight into the language for those already familiar with it. The content utilizes example code extensively because we believe that the most effective way to learn a programming language is by working through examples and understanding how they work. This content has been developed by instructors for a first-year university JavaScript course. Due to time and content constraints in courses, instructors often didn’t have time to write material for students or search for examples. This content saves them time and provides it for the student at a low cost.

1.2 Previewing and Buying this Book

To get the full experience of this book, it is necessary to have a computer with an internet connection. Though the book will teach the basics and principles of JavaScript which can be practiced on any computer running any operating system, its primary focus is on Dynamic HTML (DHTML) and the Document Object Model (DOM) and teaches these programming techniques and concepts within the context of modern browsers. The examples and the practice of JavaScript during reading this book will go more smoothly if a reader is able to try them out as he goes and most of this practice will be done best with a computer connected to the internet. This online connectivity will also be useful for reference information and transfers of example code from the book to working HTML files. The author recommends that if you are reading this at a library or bookstore you will get more out of it and a better understanding of the material if you are using a personal copy during a longer period of study and practice.

1.3 About the Author

The author is a software engineer and he has been creating content about JavaScript for a long time. He was always passionate about explaining to others what he learns, which is the reason why he decided to write this book. Over the past few years, he has noticed that there are no good resources for complete beginners to learn JavaScript. He wanted to fill that void for those who are looking to start out with programming or are coming from a background such as Ruby or Python. This book is also written in mind for those who may be coming from a programming background such as ActionScript or ProcessingJS. He has created many visual explanations to help clarify concepts which he felt can get lost in traditional web development-oriented explanations. Although the main goal is to help beginners, he feels much of the content may be useful to those coming from other scripting or dynamically typed languages such as PHP or Ruby. He has made an effort to keep it under 200 pages as to not be daunting to beginners to programming types and hopes that they do not get lost under a blow of terminology or language features. He is hoping this may turn into further content, such as an advanced JavaScript book, supplemental website resources, or even video tutorials on the material. This intention has often been a failure point for free online resources. If this does happen, it is quite probable that it will be free bonuses for those who have bought the book. All of the errata and fixes to the book will be found at books.MDC.io, so be sure to check there after purchase.

1.4 Acknowledgements

The most difficult part for any book to start writing on any project is to thank everybody who contributed to that project indirectly, and in this case, a book. I too have a big list of people whom I would like to thank for this project. Although at this time, I believe it’s more of my hard work and dedication to this project which has made it a success, and not to forget anything can be achieved without support of our family and friends. And I too had support of many people, my parents and my brother who gave me free space and time to do this project and I’m part from it. My friends who helped me with some of the project topics and references to learn the scripting in a much better way. This is just one small part of the project, of course. I certainly want to thank the team at “Beginner Guides” list. James, your support to me as a writer is very well appreciated. And the people who are reading and willing to buy my book, I would thank them for showing faith in the “Beginner Guide” series of programming books and would assure them to provide more interactive and innovative books in the future.
I believe I would have missed many names to mention over here, but as said, it’s just an “acknowledgement”. This project is dedicated to all the people who have supported me on the day it was initiated back in September 2009, and it certainly a start to my career as a programmer and a writer. Thank you all! And hope you have a good time learning this book and get a good hold on JavaScript.
Last but not least, I would thank God for giving me the strength and patience for completing this book.
Thank you all.

2. Getting Started with JavaScript

JavaScript can be run on the desktop! Every modern operating system has a built-in JavaScript runtime and there’s nothing to install. Windows users who’ve installed JScript.NET or are still stuck on an old version of Internet Explorer might want to download a more recent runtime such as Rhino or Node. I personally recommend writing JavaScript in either Node or Mozilla SpiderMonkey, but if you’re just testing out the language as a newbie, any console will do. One convenient way to get started is to use the Scratchpad feature built into the Firefox web browser. The advantage of using Mozilla software is that the same engine is running behind both the JavaScript console and the web browser, so behavior is consistent. With consistent behavior between running JavaScript in and out of web pages, there’s less to confuse the beginner.
Setting up the environment and running your first code are still the biggest stumbling blocks to learning a new programming language. Much of the available documentation immediately asks you to do too much too soon, or skips over the crucial details. Unfortunately, JavaScript is now being taught in the large without letting the students play with it in a local environment. Over-reliance on the presence of a browser has led to a plethora of instructional material that simply doesn’t work. For example, the early lessons at Codecademy ask the student to start typing JavaScript into a browser console before the student has even learned how to access said console, or the peculiarities of whatever pre-packaged environment the site provides are inconsistent with the code in question.

2.1 Installing JavaScript

There are technically two ways of running JavaScript programs on your own computer: 1. web browser and 2. Standalone. This tutorial focuses on setting up JavaScript for web development. Although it’s possible to install the SpiderMonkey distribution of JavaScript on Windows, this is a little complicated, and it’s much easier to try using WAMP or EasyPHP for Windows, both of which provide complete environments with Apache, PHP, and MySQL. There are many others that include JavaScript support out of the box. For other platforms, you can install Apache, PHP, and MySQL individually and then configure it for JavaScript. This involves setting up a virtual host to serve files from your chosen directory (it can be as simple as adding two lines to httpd.conf), and possibly tweaking .htaccess or httpd.conf files to make sure that .js files are run through the JavaScript interpreter.
The easiest way to start with JavaScript is to put the scripts directly into your HTML files. This generally provides much quicker development and easier debugging than using an external .js file, and is perfect for getting a feel for the language. However, for more complex programs, especially those that should be accessible from multiple pages, using an external file is far more convenient. To begin with, it’s recommended to find or create a simple HTML file and add JavaScript to it. After setting things up, you’ll want to try the examples in your chosen reference and experiment by modifying them and creating your own trivial scripts. The Mozilla JavaScript reference is probably the most thorough, but if you’re just starting out, you might want to find a simple JavaScript tutorial. Although almost certainly it will teach bad practice and outdated methods, so be sure to verify everything with a second source.

2.2 Writing Your First JavaScript Code

<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate a simple alert box.</p>
<button onclick="myFunction()">Click me</button>
</body>
</html>
You will note we saved our file with a .html extension. This is because JavaScript is incorporated into an HTML document. When we want to run JavaScript code at this beginner level, we will be doing it through HTML. This is the easy way to test simple programs without worrying about creating custom dialog boxes.
A little input box will come up and ask you for your name. When you type your name, an alert will pop up, saying hello to you. This could be the start to a JavaScript redirecting page to welcome you, but for now we will just start with the basics. Open up notepad, or any other text editor you have on your computer. Type the following code, then save your file as "simpleinput.html".
Our main aim in this part is to get you comfortable with the core syntax of JavaScript. The best way to do that is by example, so we're going to walk through building a very simple program. The program we will build is a very common one in any programming language.
2.3 Understanding Variables
At the heart of programming is the ability to process data. A variable is a way of storing information, such as a number, a string of text, or an array. Once a variable has been assigned, it can be recalled and used in functions or conditional statements. Variables are also placeholders, which means that you can change the value of a variable at any time to affect the outcome of a program. In JavaScript, there are three ways to declare a variable: the keyword var, the keyword let, and the keyword const. The keyword var declares a variable globally, or locally to an entire function, regardless of block scope. Because it is not logical to use a global variable when it is only required in a certain part of code, var is not a great method for declaring variables and therefore is beyond the scope of this guide. let and const have similar functionality, yet vary in that a variable declared with const must be assigned, and once assigned, its value can never change. The ability to reassign the value of a variable in JavaScript has its downsides, in that it might not always behave as expected due to an error in code. In some cases, a variable will not be declared properly in a single block of code, but will be declared in multiple blocks of code. When this happens, JavaScript may experience a conflict due to the same name of variables in the same scope, causing it to overwrite variable values in situations where that was not the intended outcome. This is where working with variables in JavaScript can become complex.
### 2.4 Working with Functions
So far we have used several functions like plot, freq and sin but we have not discussed how to go about using them on your own functions to solve problems. This is the aim of the next few examples. We will see how functions can save us time and effort spent on repetitive tasks, help us solve problems more effectively, and enable us to better understand how to build more complex algorithms. Take the example of the 1-D random walk. This involves a sequence of steps where at each time t the position x(t) is changed by an amount r chosen at random from for example a uniform distribution in the interval (-1,1). This is such a simple process, and yet we know from basic mechanics that the mean squared displacement at time t given by <Δx^2> is equal to 2t. Now this system can be modelled as a sequence of n random number picks from (-1,1) which change the position between each pick. Now this is a wonderful opportunity to make a function! A random walk in any dimension can be modelled by giving the number of steps and the dimension as arguments to a function which returns the position vector at the end of the walk. For each type of walk (e.g. 3-D, Brownian, lattice) we can define different probabilities for the changes in the position so that the function can be used to represent the walk in any of these scenarios. Now to illustrate an event driven approach and aid future visualisations, we will create a function which makes one step of the walk, and uses an argument plot which if true will plot the new position of the system. In future examples the aim is to put these various functions into objects with the functions being the methods of the object.
Step 1: Make a function randvec which takes an integer n as argument and returns a vector of n random numbers from 1 to input from a uniform distribution.
Step 2: With a fixed dimension and number of steps, use the above function with arguments (putting the output in a matrix) to return a vector which is the position of the walk at the end. Now we can use vector to store the output can be used an argument (defaulting to false) which will prompt the function to plot the walk by calling the event functions a set of times and plotting after each call.
2.5 Using Conditional Statements
Finally, you can have a general else statement which will execute if none of the previous conditions are true.
If the first condition is false, it tests another condition. If the second condition is true, another block of code will execute.
For multiple condition decisions, you can use the else if statement. It works like this:
Code:
if q < 20 is true, execute x = x * q;
var x = 40, q = 2;
if ( q < 20 ) {
  x = x * q;
  document.write ( x );
}
If a particular condition is true, then a block of code will execute. Here's an example:
When you write a program, you need to decide the output under certain conditions. For example, if a certain input is given, then what will be the output. In order to carry out certain operations based on whether a certain condition is true or false, we use the if and else statements.
## 3. JavaScript Data Types
JavaScript is a loosely typed language, which means you do not have to define the data type of a variable when you declare it. The data type of a variable can change during the execution of a program, and you can store all types of data in the same variable. This is different from languages like Java or C, which are statically typed. For example, in Java, if you declare a variable to be an integer, it can only ever hold an integer. If you try to store any other type of data in that variable, the program will fail to compile.
Data types are used to represent data. When you are writing a program, you need to store data in variables. You may then manipulate that data and perform various actions based on it.
We will also introduce arrays, which are list structures, and objects, which can be used to store collections of data and more complex entities.
In this short chapter, we will explore some of the simple data types that are used in JavaScript. Our focus will be:
- Strings: Textual data
- Numbers: Numeric data
- Booleans: True or false values
### 3.1 Understanding Strings
JavaScript includes only one data type that holds text values. String data types hold a sequence of characters such as 'hello world' or 'How are you?'. String can have letters, numeric, special characters and white spaces. And the string of characters can be any length, 0 or more.
You can declare string data types in a number of ways. The easiest way is to use quotes around the value you will assign to the variable. This can be either single or double quotes, although usually a programmer will choose one style and stick to it. For instance:
var myString = "the quick brown fox"; myString = 'jumped over the lazy dog';
If you want to include quotes inside the string you can use the other type to set off the whole string. For instance:
var myString = "He said 'Do you fancy a pint?' to me."; myString = 'The file was called "appendix1.txt".';
If you attempt to write a string across more than one line you may find that an error occurs due to JavaScript's automatic insertion of semicolons in your code. If it thinks you've finished a statement, it will not expect another one to start on the next line. This problem can be solved by using the + operator to concatenate broken strings together, or by using the \ character at the end of each broken line to escape the newline character.
### 3.2 Working with Numbers
The multiplication and division operators, * and /, both work in the same way as the subtraction operator, converting any data types in the expression into numbers and producing a number as the result.
The subtraction operator is represented by the dash/hyphen (-). It can be used with any combination of data types and always converts them into numbers:
typeof (5 - 5) // number
typeof ("6" - 5) // number
typeof ("hello" - 7) // number
The addition operator is represented by the plus sign (+). When using addition, the following will happen to the data types:
If a number is added to a string, the number will become part of the string:
typeof(5 + " hello") // string
If a string is added to a number, the number will be treated as a string:
typeof("5" + 3) // string
If two numbers are added, the result will be a number:
typeof(5 + 6) // number
JavaScript Data Types
3.1 Understanding Strings
3.2 Working with Numbers
3.3 Exploring Booleans
3.4 Using Arrays
3.5 Working with Objects Writing Mathematical Expressions
3.3 Exploring Booleans
Boolean is a data type that is either there or isn't. In JavaScript, truth values are represented with a simple true or false. You may recognize these from flow control statements in other languages. There are a few unexpected ways that the boolean data type can appear. The first is as a result of a comparison. Each comparison results in the boolean value true or false. This is fairly straightforward, however the actual value compared is often not a boolean. For example, comparing two numbers: 2 == 3. This expression results in the boolean value false. If you are unsure what type a comparison will result in, try using === instead of ==. This is a strict comparison and will not carry out any implicit type conversions. Another common source of boolean values is from conditions. A condition is anything that can be evaluated as true or false. Most common uses are in loop and branching statements. An if statement is a good example: if (x != 9) { ... }. The boolean value here will be the result of comparing the current value of x to 9. With some practice, you will see that boolean data is used extensively to control the flow of a program.
### 3.4 Using Arrays
var Country = new Object();
Country["India"] = "New Delhi";
Country["China"] = "Beijing";
Country["France"] = "Paris";
If someone is too much inclined to use array simulating named indexes, it's better to use an object instead. For example:
Here country array is also an associative array. But it's not the efficient way. Array is also an object in JavaScript and object is a collection of key-value pair.
var Country = new Array();
Country["India"] = "New Delhi";
Country["China"] = "Beijing";
Country["France"] = "Paris";
Array as an object with assigning elements as properties to it. For example:
JavaScript doesn't support arrays with named indexes. JavaScript all arrays can have all elements as strings. Normally it's not efficient to use array as associative arrays (array with named indexes), but still if someone wants it can be simulated as follows:
JavaScript arrays are dynamic, so they can keep adding elements.
var array = [1, "two", [3]]; // an array with a number, a string, and an array.
Arrays can store different types of elements at the same time. For example:
var list = new Array("Delhi", "UP", "Punjab"),
or
var list = new Array(3); // create an empty array with length 3
or
var list = ["Delhi", "UP", "Punjab"]; // same as first example
In JavaScript, creating an array is as simple as making a list. For example:
3.5 Working with Objects
We can access the data in an object using the property name in conjunction with the dot operator. For example, to get the product_name property from our book object, we can type book.product_name. The dot operator is used to reference the property contained within our object. Remember that "object" here refers to the object instance or the "blueprint" itself. Accessing properties of an object is also possible by placing the property name inside square brackets and passing the result to a variable. This is much less common than using the dot operator but can be useful in certain situations.
There are no restrictions to the value types a property can hold. Properties can be any data type, including another object. A property can even be a function, in which case it is known as a method. A method is a function that belongs to an object and can be used to manipulate the data contained within the object.
By declaring a variable with the keyword var and setting its value to an object, we have created an object instance. You can think of an object instance as a variable containing a "copy" of the object's "blueprint". After creating the object instance, we set its properties by referring to the property name and assigning it a value. This is the basic syntax for setting properties of an object. Object properties can also be set when declaring a new object instance, like this:
An object is a custom data type that contains a sequence of variables. Variables are like "slots" within the object that contain data. The data within an object is often referred to as an object's properties. JavaScript objects can have properties that are other objects, allowing you to create complex nested data structures. Here's an example of a simple object and its properties.
## 4. JavaScript Operators
In this case, y will be equal to 10, as x++ increments x after y is defined. So before, x++ is equivalent to x = x + 1.
Example:
x = 5;
y = 5 + x++;
Increment and decrement are used to add or subtract 1 from the variable. This is very useful because JavaScript, like many languages, supports the ++ and – within another statement.
In this case, z will be equal to 1, because 10 divided by 3 has a remainder of 1.
Example:
x = 10;
y = 3;
z = x % y;
The multiplication operator speaks for itself, and so does the division one. The modulus operator is used to find the remainder between two variables.
In this case, z will be equal to 5.
Example:
x = 10;
y = 5;
z = x - y;
The subtraction operator is used to subtract one value from another.
In this case, z will be equal to 11.
Example:
x = 5;
y = 6;
z = x + y;

### 4.1 Arithmetic Operators
Addition (+)
This operator is used to add two operands. If both operands are numeric, then it will perform an addition. If any one of the operands is a string, then it concatenates two operands.
```javascript
var x = 10;
var y = "20";
var result = x + 20; // Result will be 30
result = x + y; // Result will be "1020"

Following are a few arithmetic operators:
Arithmetic operations provide a way to add, subtract, multiply, and divide, as well as find the remainder when you divide two numbers. We can perform arithmetic operations on numbers as well as on strings. If we perform arithmetic operations on strings, then it will consider the strings as numbers.
Here x and y are two operands and we applied some arithmetic operators on them. In the snippet, result holds the value of the expression on the right-hand side comment of each statement.
// Decrement
result = --x; // x is now 10, result holds 10

// Increment
result = ++x; // x is now 11, result holds 11
// Modulus
result = x % y; // Result holds 1
// Division
result = x / y; // Result holds 3.(3) i.e. 3.33
// Multiplication
result = x * y; // Result holds 30
// Subtraction
result = x - y; // Result holds 7
// Addition
var result = x + y; // Result holds 13
Consider the following code snippet:
```javascript
var x = 10; // The value of x is 10
var y = 3; // The value of y is 3
### 4.2 Comparison Operators
JavaScript has several sets of built-in operators, which can be used on numbers, strings, and logical values. They are a part of the JavaScript language and they are placed in the JavaScript "syntax". Comparison operators are used in logical statements. The result of applying a comparison operator to a pair of operands is a Boolean value often referred to as a "logical value". The comparison operators that can be used in a "standard" environment are listed in the table below. 
The equivalence comparison operator can be used to compare strings or numbers to see if they are equivalent. This operator utilizes two equal signs and if the operands are equal it returns true, whereas if they are not equal it returns false. This is also referred to as the equality operator. The weakest point of this operator is that it does not work in cases where you want to compare to a boolean value, as it treats it as a number. Let me show you what I mean: 
(6) == "6" <-------- This will return true even though we have compared a string to a number.
This is because JavaScript has a convenience feature that lets you alter a string into a number if a string has numerical content and it thinks you are going to use it in a numerical operation! But be aware that this feature can cause problems, so it's often best to avoid it by using an explicit conversion. See An explicit conversion using the Number() function.
The best method to compare numbers or strings without involving type coercion is the strict equals operator ===. This operator returns true if the operands are equal and of the same type. The reason this does not involve type coercion is because if the operands are not of the same type, this operator will return false without attempting to convert the operands. Finally, we have the not equals operator.
This is essentially the same as the equality operator, but it returns the result of the equality operator negated. i.e. execute the equality operator and then swap the result for the not equals. These can be very useful in decision making if you choose to use them in conjunction with the equivalence and equivalence conversion operators.
### 4.3 Logical Operators
This will return the string "Both the x statement and the y statement are true". The reason for this is that if the first operand of the logical AND is false, there is no need to test the second one; so in the case where x is not less than 10, nothing will be displayed because the second operand is not tested.
Logical AND
This operator, represented by two ampersands, is used to return a value of true only if both the operands are true. If the first operand is false, the second operand is not tested, and false is returned. For that reason, the logical AND can be used to encapsulate an if statement. The following example illustrates a simple if statement encapsulated in a logical AND:
x = 7;
y = 9;
if (x < 10 && y > 5) {
    document.write("Both the x statement and the y statement are true");
}
In this case, the comparison x is not greater than y, so the document will display a value of false because the logical NOT is reversing the answer to the original comparison.
Logical NOT
This operator is represented by an exclamation point. It is used to return a value of true when it precedes an expression that is false. Conversely, it will return a value of false when it precedes an expression that is true. Consider the following example:
x = 5;
y = 2;
document.write(!(x > y)); //Output: false
There are three logical operators in JavaScript: ! (logical NOT), && (logical AND), and || (logical OR).
Logical operators are typically used to encapsulate conditional expressions; more information on conditional statements can be found in our JavaScript Comparisons chapter.
### 4.4 Assignment Operators
Division assignment
The division assignment operator (/=) divides the value of the left operand by the value of the right operand and assigns the result to the left operand. For example, if we assume that i has the value 10, i/=5 is the same as i=i/5 and will change the value of i to 2.
Multiplication assignment
The multiplication assignment operator (*=) multiplies the value of the right operand by the value of the left operand and assigns the result to the left operand. For example, if we assume that i has the value 5, i*=3 is the same as i=i*3 and will change the value of i to 15.
Subtraction assignment
The subtraction assignment operator (-=) subtracts the value of the left operand from the value of the right operand and assigns the result to the left operand. For example, if we assume that i has the value 5, i-=3 is the same as i=i-3 and will change the value of i to 2.
Addition assignment
The addition assignment operator (+=) adds the value of the right operand to the value of the left operand and assigns the result to the left operand. For example, if we assume that i has the value 5, i+=3 is the same as i=i+3 and will change the value of i to 8.
Simple assignment operator
The simple assignment operator (=) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. For example, x=y=z=5 will assign 5 to all three variables.
## 5. Control Flow in JavaScript
If there are several conditions you want to test, you can use multiple if-else statements. However, for multiple conditions that you want to test, the most efficient way is often a switch statement, which will be explained later.

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

An else statement can be used in conjunction with an if statement to provide an alternative route for the code to take if the if statement results in a false value for the condition. It looks like this:
Only one statement is valid following the if statement; however, you can enclose a block of code within {} to include several statements. The condition can be anything at all and is a piece of data that can be evaluated in terms of true or false. If the condition is a variable and you intend to test it against known values, it is worth using type coercion to check the value as well as the type of the variable.

if (condition) {
// code to be executed if condition is true
}

An if statement looks like this:
Depending on data, you may want to make a decision at a certain point in your script to do something different. You can specify a block of code to take one path if the condition results in true or another if it results in false. For this, you would use an if statement and optionally, to follow the false path, you would use an else statement.
Through control flow, we dictate what happens when in our code. This is often dependent on the processing of data through filtering or the comparison of different values. JavaScript has typical structures in controlling the flow in a program. These are generally the same as other languages and involve: if/else statements, looping, and switch statements. This article explains how to use these and the effects they have on your scripts.
### 5.1 Conditional Statements
```javascript
if (x > 5 && y > 10) {
  // code to be executed if x is greater than 5 and y is greater than 10
}

An alternative to nested if statements is a compound statement using the AND (&&) or OR (||) operators. This can be done with Boolean Logical Operations. For example:

if (x > 5) {
  if (y > 10) {
    // code to be executed if x is greater than 5 and y is greater than 10
  }
}

Nested if statements are a method referred to when the action from a conditional statement requires another action from a conditional statement. For example:
Please note that data from a prompt is always a string, so it may require conversion for more specific operations.
Data Type and Content Comparison:

if (x === 5) {
  // code to be executed if x is strictly equal to 5
}

You may want to remember that in JavaScript, both equal to () and strict equal to (=) are used for comparison. The former just checks the value, and the latter checks the value and data type. The same goes for not equal to (!=) and strict not equal to (!==). An example of a strict equal to in use is:

  • if statement: Use this statement if you want to execute a set of instructions when a specified condition is true.
  • if…else statement: Use this statement if you want to execute a set of instructions when a condition is true and a different set if the condition is false.
  • if…else if…else statement: Use this statement if you want to select one of many blocks of code to execute.
    Conditional statements are used to perform different actions based on different conditions. In JavaScript, we have the following conditional statements:

5.2 Loops

5.2.1 For-In

This is a unique loop designed to iterate through the properties of an object. This loop will be covered in further detail in the object-related tutorial.
5.2.2 For
This is similar to the while loop, but its syntax can be more convenient. The for loop contains three parts, each separated by a semicolon. This is the initialization of the loop index, the condition, and an expression to affect the loop index. Again, once the condition is false the loop ends. Run this code, and you’ll find that it is exactly the same as the while statement.
for (x = 0; x < 5; x++) {
document.write(“x is less than 5
”);
}

5.2.3 Do-While

This is similar to the while statement. The key difference here is that the condition is checked after the statement is completed. This means that the statement will be carried out at least once. Usually, the do-while loop is appreciated for menu designs. The loop looks as follows:
x = 0;
do {
document.write(“x is less than 5
”);
x++;
} while (x < 5);

5.2.4 While

The while statement is the simplest loop to construct in JavaScript. It follows the given condition. If the condition is true a certain statement is repeated. Once the condition becomes false, the loop ends. The while loop will look as follows:
x = 0;
while (x < 5) {
document.write(“x is less than 5
”);
x++;
}
There are several different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times. There are four kinds of loops in JavaScript: “while”, “do-while”, “for”, and “for-in”. During an iteration through a list, and the current item is removed, the next item will be moved up to the current spot. This will cause you to skip an item, since the index is incremented, but the item left is another higher index is what you’ll be moving to. If you don’t wish to examine the item at the increased index, you’ll want to examine the same index during the next iteration through the list, you can increase the index at the bottom of the loop to have it increased a second time. If you are using a for a loop, you can simply put an additional statement to increase the loop index by 1.

5.3 Switch Statements

The break statements are very important. If you forget to add a certain break statement, for instance case value1, and the intended result is the code under case value2, then both sets of code will be executed. This is called “falling through” and is useful when intentional, but in the usual case is a logic error. It is important to debug fall through errors as they are often hard to spot.

switch (expression) {
  case value1:
    //Statements executed when the result of expression matches value1
    break;
  case value2:
    //Statements executed when the result of expression matches value2
    break;
  ...
  case valueN:
    //Statements executed when the result of expression matches valueN
    break;
  default:
    //Statements executed when none of the values match the value of the expression
    break;
}

Instead of writing multiple if statements, we can write one switch statement to compare values. The switch statement is described as a “cleaner” way to perform the same action as an if…else if statement. The syntax of a switch statement is:

6. JavaScript Functions

The language provides a function keyword that can be used to define functions. In the simplest case, a function can take no arguments, and simply execute some code, then return. A function definition can specify input parameters, which act as variables in the function definition. The value of the parameters is given by the invocation of the function, using the () operator. An input parameter is defined as a variable name as part of the function definition. A function may have an unlimited number of input parameters, separated by commas.
An input argument is the value that is passed to the function when it is invoked. The input arguments are specified inside the () operator, separated by commas. In the example above, the function invocation times(2,3) causes the values 2 and 3 to be input arguments for the function, with x = 2 and y = 3. The + operator is the code that is executed inside the function, and the result of the + operation is returned as the output value of the function.

6.1 Defining Functions

Functions are declared using the keyword function followed by the name of the function and then a list of parameters in parentheses. The parameters act as placeholders for values to be passed to the function when it is called. A parameter is only a reference to the argument, not the argument itself. When the function is invoked, and actual values (arguments) are passed to the function, the parameters will act as local variables within the function. That is, when the function has been executed, the parameters will no longer be defined. I won’t go too much into this, but it is important to remember the difference between a reference to an object and the object itself. This is particularly relevant when dealing with arrays and objects. Any changes made to an object or array that is passed to a function, is done so using a reference, and thus the original object or array will be affected. Make sure you understand this, as it can cause difficult to trace bugs in code if changes are made accidentally.
One of the clearest examples of this is in the definition of JavaScript functions. Functions are declared in code, which gives them a name by which they can be called. The name is followed by parentheses. In the parentheses are any arguments the function is to take. If the function is not required to take any arguments, then the parentheses are left empty. This is then usually followed by a block of code which is the function’s body. An example is shown below.

6.2 Function Parameters and Arguments

When we looked at defining functions, we saw that some functions used parameters (variables) to get the information they needed to perform their task, whereas other functions didn’t need explicit information to do their job. In the function information(x), the name of the parameter is specified in the parentheses. A function can have two types of parameters: those that are variable and those that are specified. In fact, the function may not even need to use all the parameters that are specified. In the following case, the add function has two specified parameters a and b, and a third variable parameter c. The function uses the first two parameters to perform an addition and assign the result to the variable x. The third parameter is required to demonstrate specified and variable parameters. If we call the function add(3,4,5), the alert will display 12. Any parameters that are not specified default to the value undefined. The function in the later case will assign the value undefined to the variable c. This type of behavior is important if we want to maintain backwards compatibility with older code.

6.3 Returning Values from Functions

When I was younger, in my early teens, I had done lots of aggressive rollerblading. It came to a time when I became so good and was always entering competitions that I wanted to get a sponsor. I asked my parents for advice and they told me I had to write a resume, but I really didn’t understand it. After thinking, I came to the conclusion that I should write about everything I have learned from aggressive rollerblading and what I have accomplished throughout the years. This wasn’t exactly the correct approach, but the act of me wanting to put down on paper keywords of what I have learned and achieved is basically writing a resume. And it is the same approach you have to take when writing a return statement for a function. A return statement is used to stop the execution of the function and to define what value is to be returned to the calling function. This value is considered the function’s return value. Now, here is the best example of what a resume really is. When an employer reads a resume, it tells them what skills and experience you possess. The employer doesn’t care about what you did yesterday, they want to know what you know right now and what you have learned throughout your experiences. So, when you write a return statement for a function, you are basically giving it a resume on a specific experience you have encountered.

6.4 Function Expressions vs. Function Declarations

In this case, the call to animalSound1 works because the function declaration is hoisted to the top of the scope before the code is run. The variable declaration of animalSound2 is hoisted, but the initialization is not, so it is undefined when it is called. The function expression myCatSound is hoisted and is equal to undefined because the initialization has not been run yet.

// Outputs: "Yes!" and "Undefined"
console.log(animalSound1()); // Logs: "Yes!"
console.log(animalSound2);
// Error: animalSound1 is not a function
myCatSound = function() {
  return "Meow";
};
function animalSound1() {
  return "Woof!";
}
var animalSound2 = function() {
  return "Tweet";
};

To make an anonymous function, we can simply omit the name of the function. Function declarations actually hoist the function definition to the top of the current scope, which means the function can be used before it is defined. This is because of how variable and function declarations are ‘hoisted’ to the top of the scope by the interpreter. Variable declarations are hoisted, but not their initialization. Initializations of variables and functions are hoisted. E.g.

7. JavaScript Objects

The simplest way to create a new object is using the Object constructor. Var obj = new Object(). There is a more concise way to create an object. Let obj = {}. This is equivalent to using new Object() and serves as the basis for object creation using the expected object literal notation. This notation is also the current recommended practice and is much cleaner than using the Object constructor. The first step is creating a new constructor function. Constructors in JavaScript are the object’s factory. The most common way to create an object prototype is to use a combination of a constructor function and the new keyword. This could be something such as: function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } This gives you the outline for a person object by creating properties for the person’s name, age and sex. You can now create a new person object as many times as you want by using the new keyword to instantiate a new person. E.g. Var person1 = new person(“Paul”, 29, “male”); Var person2 = new person(“Joanna”, 32, “female”); This is the most common way to create new objects and objects created in this way will have a single common prototype and are given a more traditional look and feel for an object.
An object may be instanced using a constructor in the following manner: let obj = new Object(). This creates a new object instance and assigns it to the variable obj. All the properties and methods for a given object instance are defined inside the constructor function. This is done using the this keyword to identify the object instance. A method is created with the same idea. E.g. let obj = new Object(); obj.displayInfo = function() { return this.name + " is " + this.age + " and is " + this.sex; }; This creates a method displayInfo for the obj instance. The method references the obj instance using this and returns a string built from concatenating the values of the object’s properties.

7.1 Creating Objects

We already have briefly examined the differences between object and primitive datatypes in JavaScript. Here we instantiate an a new Object using the new operator, and then assign some properties to it. And the properties could have been assigned to it during the instantiation step. Step by Step:
Create a new instance of an object using the new Object() statement. If you do not specify any properties when creating the object, the Object() constructor creates it with no methods and no properties.
Define some properties for your object. This is done using assignment statements using the = operator. It is important to note that stating element newData = “foo”; actually adds a property to the object newData is a member of, and if said object does not exist, will enteail the creation of a new Object.
Any valid datatype can be used as a value for a property, or for a method. We can create a method by using function as the datatype. An object method is nothing more than a property that is a function, and it can be added in the exact same way as a data method. See the example below for adding a method to the car object.
Creating an object is about as straightforward as it gets in JavaScript. Consider this example:
var myCar = new Object();
myCar.make = ‘Ford’;
myCar.model = ‘Mustang’;
myCar.year = 1969.

7.2 Accessing Object Properties

  • It is using a variable name that could be mistyped. If there is no name variable declared in the current scope at the time of the access, this would result in an error and a value of the global object property called name being returned. This could be a very hard to find bug, if name is a property on multiple objects or a widely used global var.
  • myCar may be an object of a recently written API or a third party vendor library. It is hard to ensure that all properties are documented in your object. You may not even be sure that name is a property of myCar.
  • It is not possible to default values if properties are deep or not all guarantee to be defined. For example, let’s say you have an array of car objects and you want to do something to all cars made by Ford. This will result in an error if any car does not have a make property and be very hard to code defensively against.
    Is this the best way to access the name property of myCar? It is the easiest and shortest way. However, there are some problems with using this syntax:
var name = myCar.name;

When you start writing content to record JavaScript object properties, you will get various opinions on how to access and use the properties. For example, you have seen this mentioned elsewhere:

7.3 Modifying Object Properties

This shows that the method has changed the value of the property speed.

The results will be:
var myCar = new Car("VW", "Golf", 2005, "Me", 5);
document.write(myCar.speed + "<br />");
myCar.setSpeed(20);
document.write(myCar.speed + "<br />");

function setSpeed(speed) {
    this.speed = speed;
}
function Car(make, model, year, owner, speed) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.owner = owner;
    this.speed = speed;
    this.setSpeed = setSpeed;
}
You can also use this method to change the value of a property inside a method of the object. In the following example, the method setSpeed is defined to change the value of speed:
The property of the object has been changed.

myCar.speed = 60;

Sometimes you'll want to change the value of an object's property after you've created it. You can do this the same way you'd change the value of any variable you've already created, by assigning a new value to it:
### 7.4 Object Methods
Overall, this is a good practice as it is often far better to manipulate object data using methods included with the object type. A list of built-in JavaScript methods for standard objects can be found here: Built-in JavaScript Methods.
objectName.methodName() 
objectName.methodName(argument)
In the same way that we can access and modify the properties of an object, properties can also be used to access and run methods:
The original string would have been modified to "THIS IS A STRING".
var myString = "This is a string"; 
myString = myString.toUpperCase();
This script creates a new String object and stores it in the variable myString. It then calls the toUpperCase method of the myString object. This method does not change the original string in any way. Instead, it returns a new string that was created by converting the characters in the original string to uppercase. This is why we need to store the result in a new variable or the same variable if we want to change the original string. If we did this:
var myString = "This is a string"; 
myString.toUpperCase();
Sometimes, functions are created to work with an object. These are called methods. A method is a function that is stored as a property of an object. Consider the following example:
## 8. JavaScript Arrays
Hence, as there are long statements for each day, we just use a 'for loop' for the extn array to access each day. This will give an alert box with Mon, Tue, Wed, Thu, Fri, Sat, Sun with a 'long live' prefixed to each day.
Accessing array elements is the same as assigning or changing their values. Just use the variable name followed by the index in square brackets. Here is an example to add an extension to the days array:
var extn = new Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
for (i = 0; i < extn.length; i++) {
  extn[i] = "Long live " + extn[i];
}
alert(extn.join());
Each element in the array can be accessed by its index (position in the array), which starts from 0. Using the days array defined above, days[0] would be Mon and days[3] would be Thu.
So you've just created the array days and you get an alert box which shows Mon, Tue, Wed, Thu, Fri, Sat, Sun.
Both the above lines have the same effect. Now, if you want to verify the contents of the array, it's better to use the inbuilt method .join();
alert(days.join());
For example, to create an array to store the names of days in a week, the code is:
var days = new Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
or
var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
Creating an array in JavaScript is simple. Just type var arrayname = new Array(); or var arrayname = [ ];
Arrays in JavaScript are variable pointers. They are used to store multiple values in a single variable. This can cut down a lot of coding.
### 8.1 Creating Arrays
This would replace the array values with Bill, Joe, and Dave. Array values can be accessed and replaced using its variable name followed by square brackets and the array's position number, starting at 0. Array values can also be any kind of data type such as strings, integers, objects, and more. Array values can also be updated the same as any other variable using the = sign. E.g.
arrayName = ['Bill', 'Joe', 'Dave'];
This assigns the previously created array with the values of John for the first value, Fred for the second value, and Mac for the third value. Array values can be any kind of data type such as strings, integers, objects, and more. Array values can also be updated the same as any other variable using the = sign. E.g.
var arrayName = ['John', 'Fred', 'Mac'];
This creates an array that can be accessed using the variable name arrayName. Arrays within JavaScript start counting at zero for the first value, 1 for the second value, and so on. To add values into the array, you would declare the array using a similar method with a value for the variable. E.g.
var arrayName = [];
Much like other languages, JavaScript allows you to create arrays. Arrays can be used to store any kind of data, including numbers and strings, e.g. '24', 'John'. They can also be used to store objects. In JavaScript, you can create an array by simply declaring a variable and giving it a value in brackets. E.g.
### 8.2 Accessing Array Elements
*(arr + 5) = 1000 + (5 * 4) = 1020
arr[5] = 1000 + (5 * 4) = 1020
Access to an element in an array can be explicitly stated by deriving the address from the location of the array name in memory. Pointer arithmetic implementation and subscript notation can be interchanged for accessing the value of the 6th element in an array called arr. Suppose the array starts at memory location 1000 and each element is 4 bytes, *(arr + 5) and arr[5] would refer to the 6th element in an array.
Accessing Array Elements
Using subscript notation.
There are two ways to access an element for its value in an array. You can refer to the address of the element within the array relative to the beginning of the array. Equivalently, you can refer to the address of the element using a calculated value that is relative to the beginning of the array. Array access by element address is implemented using pointer arithmetic and always use the subscript notation arr_ind. However, in an expression, an array name is converted to a pointer to the beginning of the array so you can use pointer arithmetic.
### 8.3 Modifying Array Elements
Arrays also have many methods that can be used to change their contents. All these methods would be expected to return the new array length. If n is the number of items in the array, these methods run from O(log n) to O(n), so one would do best to try them out and see whether they are fast enough for the specific application. Remember that these methods have generic versions in Array.prototype that operate on arrays and array-like objects. If you are using this code often, you may want to use those instead.
It may be that you are happy with the contents of your array and you simply want to shuffle things around a bit. This can be done as long as you are only changing the order or moving some elements to a different place, you are not adding or deleting any. This can be done by referencing an element from one part of the array and copying it to another.
A characteristic of arrays that may be surprising is that the size of an array can be changed at any time. Not every number from 0 to the length of the array is a valid index. The length property is the gatekeeper to adding and removing elements. Whenever the length property is changed, the actual array is changed so that it has exactly that many elements; extra elements are deleted and insufficiently many elements are set to undefined. It is an easy way to trim an array. On the other hand, an easy way to increase the length is to use length directly.
### 8.4 Array Methods
```javascript
var arr = ['apple', 'pear', 'banana'];
arr.map(function(item) {
  return item.charAt(0).toUpperCase() + item.slice(1);
}); // ["Apple", "Pear", "Banana"]

The previous sections covered several ways of accessing and modifying the elements of an array. 8.4 Array Methods There are many other built-in methods on the Array prototype. These methods are convenient and powerful, providing a lot of functionality in a succinct syntax. Because the native array methods (map, reduce, filter, etc) all take callback functions, they are very flexible in general. These make array manipulation far more natural and easy. Consider the task of taking an array of strings and capitalizing them. Using a for loop, this would require creating an empty array, iterating through the input array, pushing the capitalized elements onto the new array, and returning the new array. With a map, capitalizing the array of strings is far more direct.

9. JavaScript Events

Event Attribute is similar to the event listener, but it is an attribute in an HTML tag that contains the type of event and the function. Event attribute can only contain one event, and if we want to add another event, we have to reassign the attribute. However, one of the advantages is that micro elements can be attached to an event with less coding.
Event Listener is a method that is attached to the element that has been selected and waits until an event happens. There are two methods: addEventListener and removeEventListener. These methods work by adding the type of event and the function of what to do when the event occurs.
In HTML DOM, events are the representation of the state of the HTML document and can trigger the script that can respond with some output. DOM objects are the representation of the HTML documents and they can be changed or modified by a script. With the script, you can create some logic that not only manipulates a single element but also multiple elements. We might want a different style of manipulation, and we can achieve it through event handling. Event handling can be done by an event listener or an event attribute.
Using events, you can create an event handler for an element. An event handler is a function that runs when the event is triggered.
JavaScript code can be executed when an event occurs, like when a user clicks on an HTML element. Writing JavaScript code into HTML.

9.1 Understanding Event Handlers

An event is an action that occurs in a program. An event handler is a block of code that is triggered deliberately by a certain event. With JavaScript, an event is an action that can be detected by the program, such as the user clicking on a button. Events can be detected by any type of element, but it’s most useful with forms and interactive page elements. Actions such as buttons are implemented by the use of a JavaScript method, but it’s possible instead or as well to make the action occur as a result of a user event on that element. This essentially is what interactive scripting is all about. At a later date, there are also ways to handle events in Document Object Model Level 2 and XML events. Event handling is, however, most commonly performed using HTML because it is far easier to understand and cross-browser implementation is more effective. Working with HTML events basically involves assigning an event handler to any desirable element, the scope of this will be apparent to you in later examples.
In order to determine how JavaScript and events are useful, consider this scenario: Suppose you have a form on your web page, and someone is filling it out. When the user moves to the text area of input, a message telling them how many characters they have left is displayed. This could be very useful to the user, but annoying all the same. Here is an example of an event that is useful to the user, but not to you. That’s what event handlers are all about. You to make things happen, and you want to have more control over the actions that occur. There are many types of events triggered by many different types of elements. Whether there is a use for event handling on all the various event types is questionable, but it’s most beneficial with user interaction based events. Things like clicking, hovering, selecting, inputting, changing focus etc. are all ways users interact with your page and event handling can make each of these actions do exactly what you wish.

9.2 Handling Mouse Events

Mouse events occur when a pointing device is used to interact with a web page. There are 5 events associated with the mouse: click, dblclick, mousedown, mouseup, and mouseover. These events are very useful for those who want to make a web page more interactive. For example, you can change the background color of a

when the mouse is over it. When the mouse cursor comes over a link, the status bar changes, and when it goes off, the status should be restored back to the old one. You can handle this easily using these events, and on a large scale, the mouse events play a very crucial role in developing web games or web applications. A beginner has to keep in mind that mouse events do not execute on keyboard navigation unless any specific event is involved in the process, such as changing the text by focusing on an element. This is a very important point as it affects the accessibility features of a web page, and you should always keep in mind that your applications or games using mouse events are accessible to a large audience. A point to mention here is that mouse events are available for almost all HTML elements, but they may have a different behavior for different elements. For example, an onClick event on a link or a span will have a different behavior than the same event on a radio button or a list item. This is because all HTML elements have not been created in the same way, and a large difference can exist between their implementations. Always refer to the HTML element reference to get a better understanding of the behavior of the event handled.
All the events that occur in JavaScript happen on the different HTML tags or elements. This string of events in JavaScript leads to the generation of different interactions called event handling. An event of any kind is recognized and identified in JavaScript by its event handler. An event handler is a statement of code that sets up the response to the occurrence of a specific event. When an event has occurred, the event handler’s code is executed. This action of recognizing and execution is also known as the raising of an event. For example, if you want to execute a function when a user clicks on a hyperlink, then you must write an onclick event handler for that hyperlink.

9.3 Handling Keyboard Events

The onkeypress event occurs when a user is pressing a key (regardless of whether it produces a character such as “e”) while the focus is on an element. This term is widely used, but it is something of a misnomer, since it includes pressing keys that do not produce anything (e.g. left arrow, ALT, function keys). The more accurately named onkeydown event also occurs when a user is pressing a key, but is specifically for keys that produce a character. In the following example of handling a key event, pressing the ‘x’ or ‘m’ key will pop up an alert dialogue. Try typing in the textarea. Remember that since onkeypress produces different effects in different browsers, it is sometimes necessary to test both onkeypress and onkeydown for the same key.
In JavaScript, it is sometimes necessary for a script to react to the user’s keyboard actions. For example, in a game, the left and right arrow keys might move a game character. In an animation, pressing a key might cause a sequence to stop. Web browsers and web pages also often define keyboard actions. For example, in Internet Explorer CTRL-n opens a new browser window, and in a framed page, the key might reload one of the frames. To script any of these keyboard actions, an author needs to know how to detect that a key on the keyboard has been pressed and how to take an action in response. Handling keyboard events is more complex than handling mouse events because it requires capturing or tracking system state that exists independently of event, but it is still quite easy with JavaScript event handlers.

9.4 Handling Form Events

“Javascript Events” is a way to make web pages more interactive, especially in the form part. A form is used to collect data from user input. We can enhance the user experience by using its power. The form has many kinds of events, such as onblur, onchange, onfocus, onselect, and onsubmit. We are about to discuss them step by step. An event occurs when the user inputs data in the form. You can use the onblur and onchange events. These two events will fire a script function when the user is finished inputting data in an input form and then the user tries to change the data. Differences from those events are onfocus and onselect events, which occur when an input form gets focus from the user and when the user selects an input form. And the last is the onsubmit event, which occurs when the user presses the enter button or clicks the submit button to submit the form.

10. JavaScript DOM Manipulation

Then Dave learned more, and he found out about DOM (Document Object Model). “This is it!” Dave said. DOM is an API provided from a programming language that can be used to access, change, or manipulate a document’s content, whether it’s XML or HTML.
The main goal from scripting with changing the internet content is to get the better internet page looks because the visitors can interact with the page.
Then Dave learned from it and he found JavaScript and the internet scripting language are not the same as the local computer programming language, although they are a little bit similar. The output from the internet scripting language is not just a value, but also can access, change, or manipulate the internet page content. Whether it’s text, a form, a picture, or even building the entire new web page.
So what’s wrong with Dave’s JavaScript program? It seems correct, doesn’t it? His friends said that he needs to learn about scripting and programming on the internet. Dave said, “Scripting? Programming on the internet? What’s that? I just want to get an output from my title.”
Dave is a beginner JavaScript programmer. He was trying to make his first JavaScript program from the book he had. He wrote some JavaScript statements and tried to run it from his browser. He wanted to get the output from his HTML page title. He wrote this statement in his HTML file. But the result is not as he expected, he got an “undefined” value.

10.1 Introduction to the Document Object Model (DOM)

Understanding the DOM and this world of HTML elements is key when it comes to JavaScript and web page manipulation. Today we focus on understanding the basics of how we can use JavaScript to interact with the DOM to achieve such element manipulation. With our newly acquired understanding of the DOM combined with our native JavaScript abilities, the possibilities are endless to create a more dynamic and interactive web page.
An HTML document and its DOM can be thought of as two separate worlds. Initially our HTML page and its structure exists in the form of text in a file. When this file is opened with a web browser the browser reads this text and creates a new world of dynamic HTML elements represented by a tree structure. This new world of HTML elements can be affected with JavaScript to dynamically create, delete or modify these HTML elements within the web browser. When you use JavaScript to create an HTML element within a web page, you are adding an element to this tree structure world in which it can be directly visualized in the web browser.
So, what is the DOM? Think of the DOM as a tree structure representation of an HTML document. An easy visualization would be to think of the HTML document as a parent element with child and elements, the and elements have their children and so on. This tree structure with parent and child relationships between HTML elements is what the DOM essentially is. When we use JavaScript to affect an HTML document, we are essentially using JavaScript to manipulate this tree structure.
Alright, let us begin the mastering of our very versatile JavaScript skills. The environment in which our JavaScript runs is typically with a web browser. Although it is technically possible to run JavaScript within a text-based browser, for the purposes of this tutorial we will focus on JavaScript within a browser to dynamically affect an HTML page. When it comes to browser-based JavaScript, the Document Object Model or DOM is the bridge between our JavaScript and the web page we wish to affect. By understanding the DOM and how to manipulate it with JavaScript, you can truly take your web development skills to the next level.

10.2 Modifying HTML Elements

function remove() {
  var d = document.getElementById('div1');
  var parentDiv = d.parentNode;
  var removed = parentDiv.removeChild(d); // Save a reference to the removed div
  parentDiv.appendChild(removed); // Then append it to the parent at the end
}

There are a couple of built-in methods for removing an element from the DOM. The removeChild method in the Element interface removes the calling element from the document. A copy of the removed node is returned. The following code fragment demonstrates the usage of removeChild and appends the removed child back to the document.
With the HTML markup for a document loaded into the DOM, it is then possible to manipulate the structure and content of the document. A basic understanding of how the DOM represents a document allows programmers to create, delete, and modify document content.

10.3 Creating and Deleting Elements

Now that we have talked about modifying the content of HTML elements, it would be natural to talk about how to create and delete elements. But before we do that, you need to be aware that creating and deleting elements have a big impact on the loading time of your webpage. If you continually create and delete elements instead of just creating them once then modifying their attributes or contents, your page will become slow and unresponsive. This is because every time you create an element, you are using memory. Depending on how the element is created, it may also use a lot of processor cycles. Creating an element is a complex process that usually involves several other elements and is not as basic as writing tag.innerHTML = ‘text’. This outlines what is known as the Document Object Model, which JavaScript utilizes. We will look at this concept in another tutorial. Remember that the more memory used and the more processor cycles used, the slower the page will be. Now let’s look at how to create an element.
The syntax to create an element has two steps. The first step is to create the element and the second step is to assign the element to another element on the page. For example, creating a new paragraph and then assigning it to be a child of the document’s body.

10.4 Traversing the DOM

The second most important thing is that we can move between nodes (and change the tree) using the new properties such as parentElement, nextElementSibling, and previousElementSibling. Each of these properties either returns the relevant ancestor or child nodes, or it returns null if there are no such nodes. An important detail is that these properties only return element nodes, so a next or previous sibling that is a text or comment node is ignored. This is nice because it allows us to write loops that will only move between actual elements, ignoring the text and comments. So we could now write a script that adds or removes a class from sibling elements of a given node using a loop. Given the simplicity of this example, it may not seem all that important, but as you get used to the new functionality, you will see the power it.
The two most important things for traversing are first to be able to access the child nodes of an Element node. Up till now, the only way to do it has been to convert the NodeList of child nodes into an array and work with the array. This is fine, but it would be nice to be able to just call the child nodes directly. This is achieved by adding properties named firstElementChild and lastElementChild to all element nodes. If an element has no element children (for example, a

with only text and comment nodes), then these properties will return null. So we can now access the first and last child nodes with ease. There is also a property named children which returns a live HTMLCollection of all the child elements.
Imagine you are viewing this page in a web page with a modern browser. The page is represented by a tree. The root of the tree is the Document node, and there is only one root in the tree. This document node has one child, an element node for the html element. The html element has two children, one element node for the head element and one for the body element. We can move to and from these nodes using the document’s various node properties, very few as yet. The DOM Traversal specs add quite a few more.
Traversing the DOM means moving up, down, and sideways between nodes of the DOM. It’s an essential skill to get the most out of the DOM and is a prerequisite for using a lot of other APIs.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

俺叫西西弗斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值