Ready for JavaScript?

Now that you've gotten yourself familiarized with HTML and CSS, let's start modifying some of that stuff with JavaScript! Ok, so get an html template file ready. If you don't have one already, here is one you can use. Just save it as an html file, or change the extension. Once you get that ready, place "script" opening and closing tags after the closing body tag and before the closing html tag. Give the opening script tag a "type" of "text/javascript". Now you're ready to start coding... but first, let's get a little familiar with the basics of the language.

Pick a Topic



Free Code Camp


JavaScript1
JavaScript Example MDN Web Docs JavaScript for Dummies JavaScript DOM Manipulation

ThoughtMap

Current Progress

w3schools - What can JavaScript Do?

add ECMA 2015 to WebDev > JavaScript

add D3.js to WebDev > JavaScript

D3 tutorial site > https://www.dashingd3js.com/introductory-d3-course

JavaScript tutorials > https://sabe.io/classes/javascript

List of things to know for advanced JavaScript > https://youtu.be/OIioG0cx0Wo
9. Specification: http://www.ecma-international.org/ecma-262/6.0/
8. Object Constructors
7. Babel vs TypeScript
6. Closures
5. Global Namespace
4. IIFE & Modules
3. Prototypes
2. Functions
1. This Keyword

What is JavaScript?

JavaScript is a scripting language, which is a type of programming language. A script is an automated series of instructions that are carried out to complete one or more tasks. Although scripts are programmed, they are not considered programs themselves. They are often used to carry out repetitive or complex tasks within a program. The program runs on your computer, and the script runs in the program. JavaScript runs in browsers to add functionality to websites or web apps.

JavaScript Terminology

Unfortunately, there are many terms associated with programming, so for those who are unfamiliar with these terms, ironically it takes decoding the language to be able to explain how to code with it. I feel this is the best approach for beginners since even if I just showed you the code, it would be unclear how the code is being used, and without the terminology it would be hard to explain. With this out of the way, we'll be in a good position to develop from. Let's go ahead and get started.

JavaScript Syntax

Syntax is like the language's grammer. You have to put the symbols and words in the correct order to get the script to work properly. JavaScript syntax includes symbols such as: (parentheses) {curly brackets} [brackets] comma (,) period (.) semicolon (;) single (' ') and double quotes (" "), also keywords, variables, etc. Syntax is used to define and interpret the different aspects of the language.

JavaScript Curly Brackets { ... }

Curly brackets (also called curly braces) are probably the most common symbols used for JavaScript syntax. The main idea of these brackets is to either separate a chunk of code from the main body of code for some special function. These are typically called functions, but there are other forms such as loops and if statements. Another purpose for the curly brackets is to group chunks of data together into units called "objects".

function thisIsAFunction() {
  1rst line of code for this function;
  2nd line of code for this function;
  3rd line of code for this function;
}

var object = {
  data1: 1,
  data2: 2,
  data3: 3
}

if (something is true) {
  then this line of code happens;
} else {
  if not true then this line of code happens;
}

Don't worry if you don't understand the above code yet, we'll go into more detail as we go along. This is just an example of how curly brackets are used.

JavaScript Statements and the Semicolon ";"

Notice how each piece, or section, of JavaScript code ends with a semicolon? Each piece of code in JavaScript is called a statement. The reason for the semicolon is so you can break the code up over multiple lines to make it easier to read. The JavaScript interpreter in the web browser condenses the white spaces the same way it does for html. The semicolons ensure that the interpreter knows where a statement ends. Forgetting a semicolon can cause a bug and sometimes takes time to troubleshoot, so make sure you're placing them correctly.

Each JavaScript code command ends with a semicolon ";". It's kinda like using a period at the end of a sentence, but instead of being called a "sentence" these are called "statements". Leaving one of these semicolons off of a code statement can invoke an error in your script, so these are very important.

JavaScript Comments and the Double Slash "//"

...

Most of the other symbols are associated with values, and before we can explain that we'll have to focus on a different aspect of syntax, keywords and variables.

JavaScript Keywords

Programming languages consist of keywords and variables. A keyword is a built-in specified term that has special meaning within the language. For example, "console" and "log" are both JavaScript keywords. The keyword "console" is representing the browser's console, and the keyword "log" represents the action of writing to the console to log information from the script. Keywords have set meanings, variables do not. Some JavaScript keywords include: "window, document, console, var, let, const, for, if, else, while, switch, function, class, constructor, new, extends, return," and others.

JavaScript Variables

A variable is a term, it's name defined by the programmer, created as a placeholder for different aspects of the script. Things such as an html element, a sentence of text, or some type of data. The information that the variable represents is called the variable's "value".

JavaScript Values

A value is the content of a variable. The variable's value is data or information represented by that variable. When computers temporarily store information in memory, it's stored in what is called a "memory address". The contents of the memory address is a binary number (collection of 1's and 0's) and is considered the memory address's value. Variables link to memory in the computer, and store their information in a memory address. This is likely (I assume) the reason the information stored in variables are called values.

JavaScript Value Type: Number

A number value is when a variable is simply assigned to a number:

var x = 3;

"var" is an older JavaScript keyword that is used to declare a variable. The more commonly used variable keywords now are "let" and "const", which you can basically use the same way as "var", but there are slight differences which we'll get into later.

JavaScript Value Type: Strings and Quotation Marks ("...")

In JavaScript, any number of characters inside quotation marks is called a string, as in a "string of text". String characters are just text. For example, "3" + "2" = "32", not "5", because they are not number values, they are just simple text, and the plus sign is just joining the two string values together into one string value. The action of fusing string values together with a plus sign is called concatenation.

let someString = "This is a string!";
let otherString = "This is another!";

let concatinatedString = someString + otherString;

// output of concatinatedString would be:
// "This is a string!This is another!"

// if you wanted to put a space after the first string, you could do:

let concatinatedString = someString + " " + otherString;

JavaScript Value Type: Array

Instead of quotation marks, if a value has brackets around it, that makes it an array value.

var x = [3];

Arrays are a way of storing muliple values of same or different types of values within a single variable. For example, an array could hold a number, a string, and even another array.

let someArray = [1, 2, 3, "A", "B", "C"];

let arrayWithinAnArray =
[1, 2, 3, "A", "B", "C", ["some", "other", "array"]];

array variables hold muliple values in a certain numerical order, objects are slightly more complex and hold named properties and values, but also functions called methods. Arrays can hold variables, strings, and numbers.

JavaScript Variable Value Type: Object

If a value has curly brackets (also known as curly braces) around it, that makes it an object.

var x = {3};

Objects hold lists of variables and their values. An object's variables are called properties. Object properties are variables that are grouped under and relate to the object variable. Object properites don't need a variable keyword in front, and are assigned to their values using a colon instead of the equal sign. This differentiates them, when looking at the code, from regular variables that aren't attached to an object variable. They can be written in one line like this...

let someObject = {property1: value1, property2: value2, property3: value3};

...but most often look like this...

let someObject = {
  property1: value1,
  property2: value2,
  property3: value3
};

JavaScript is known as an "object-oriented" language. Objects are used for grouping information with categories that they belong to. The information is called a "value" and the category is called a "property". So objects are groups of properties and values. For example you could create an object that represents a car, and list within that object the make, model, year, type, color, etc (properties) along with the associated information (values).

Properties and Dot-Notation

JavaScript's language term "document" is an object that represents the html page currently in the window. To access a property of an object, you can use a period, called a "dot" (as in "dot com"). So if you were to type " document.all " in the browser console, and hit enter, the console would list all the properties of the object "document". This means of accessing properties of objects is called "dot notation".

Bracket Notation

There is another way of accessing properties of objects. This is by using brackets, or "bracket notation". The name of the property goes in brackets surrounded by quotation marks and immediately follows the object without spaces. Either double quotes or single quotes will work. Such as " document['all'] " or " document["all"] " (without the additional quotes of course).

The Browser's Web Console

Let's a break for a minute to get familiar with the console. At this point you can start testing things while you learn. In fact, the console is an excellent tool for testing the code and learning on your own, so it's worth while to learn how to use it. With the browser window active, hit F12 on the keyboard, or go to the developer tools menu and open the console from there. The console, along with the JavaScript "console.log()" command, is very useful for learning how JavaScript works.

console.log("Hi!");

Put this code between your html script tags, save the file, and open the file. Then look in your browser's console. It should be saying "Hi!". If it is then you now know how to use the console. If not, you may need to use the Internet to do research or ask questions to figure out why it isn't working. Now that we've been over that, let's pick back up where we left off.

Now that you know what the console does, let's create an object! Type the code above for the car object and hit enter, then type "car" and hit enter again. You should see the object displayed in the console. Click on it to see the list of properties and values.

New JavaScript Variables

What if you wanted to get the console to display an object without typing it in and hitting enter, by just using JavaScript code?

You'll need an HTML file.

If you include " console.log() " in your script, any part of the code between the parentheses will be sent to the console for inspection. Such as: " console.log('Hello there!'); " (notice the semicolon?) You'll need either double or single quotes in the parentheses to get the direct text. Text with quotation marks around them in JavaScript code are called "strings". If you leave the quotation marks off you'll get an error because it's reading the words " Hello there! " as JavaScript code. So if you type " console.log("document"); " or " console.log('document'); " you'll just see the word "document" in the console. But if you want to send the document object to the console, you would put " console.log(document); " into your code. You'll find it helpful to use this method temporarily in your code to help you troubleshoot errors.

JavaScript Value Type: undefined

Variables don't have to be created with values assigned right away. If the variable is used in the code before assigning it a value, the value will automatically be assigned a value of "undefined". It simply means that a variable hasn't been assigned to anything. "Undefined" is both a type of value, and a keyword that represents the condition where a variable has a missing value.

let someVariable;
console.log(someVariable);

JavaScript Keyword: typeof

There are other types of values. One way of finding out what type of value a variable has is by using the keyword "typeof".

let someVariable = 3;
console.log(typeof someVariable);

Using Variables

As previously stated, variables are created as placeholders for different aspects of the script, and hold different types of values. Things such as an html element, a sentence of text, or some type of data. Variables are used for making code writing quicker and easier. Instead of writing, "This is a really long sentence, and I'd hate to have to write it out every single time I need to use it!", you can create a variable...

let longSentence = "This is a really long sentence, and I'd hate to have to write it out every single time I need to use it!";

... to represent that text, and the script will get that value from memory whenever it sees longSentence in the code.

let longSentence = "This is a really long sentence, and I'd hate to have to write it out every single time I need to use it!";

console.log(longSentence);
console.log(longSentence);

Variables can be used like the "x" in algebra. Let's do some algebra using JavaScript. We're going to declare a variable name "x", and assign it to a number value.

var x = 3;

console.log(x + 2);

console.log(x + x);

The "x" isn't special, it could be any variable name. The code above is the same as the code below.

var numberThree = 3;

console.log(numberThree + 2);

console.log(numberThree + numberThree);

Parentheses and JavaScript Parameters

Parenthesis in JavaScript typically indicate a function of some sort. The "log()" part of "console.log();" is a type of function called a "method", which means it's a function that belongs to an object. We'll talk about that later. The parentheses in JavaScript functions are mostly used to pass information into the function through the use of variables or values called "parameters". For example, the "Hi!" in the code "console.log("Hi!");" is a value that could be represented by a variable.

let hello = "hello!";
console.log(hello);

Either as a value or variable, it's considered to be the first parameter. Parameters are separated by commas. If we had two variables called "like" and "this" they would be input as parameters into someFunction(like, this). The values are then sent to be used by the function.

let hello = "hello!";
console.log(hello);

Let's review. In the code above, the first hello is the variable, and the second hello is the value. The use of a variable sets up a place in memory to store a value. Typing "let" or "const" in JavaScript means you're about to create a variable. The single "=" (equal sign) is used to assign values to variables. The value "hello!" is assigned to the variable hello. The variable is then placed as a parameter into the "log" function, which is a method of the object "console". The value of "hello!" gets logged to and shows up in the web browswer's console.

The code below is a declaration of a variable called "someThing". This variable was not assigned a value. A variable without an assigned value is considered "undefined".

var someThing;
console.log(someThing);

You can assign a value to a variable by using the equal sign.

var someThing = 32;

Once you use a variable keyword (like "var" or "let") to create a variable, you can then use the variable without the keyword. In otherwords, you don't have to keep declaring the variable by using "var" if you've already done it, you can just use the variable name. For example, you can first declare the variable without assigning it, and then assign it later:

var someThing;
someThing = 32;
console.log(someThing);

Or, you can assign the variable and then later re-assign it:

var someThing;
someThing = 32;
console.log(someThing);
someThing = 64;
console.log(someThing);

If you want to create and assign a variable, but don't want it to get reassigned later, that's what the variable keyword "const" is for.

If you console log a lot of variables, you might get confused on which one is coming from where. Fortunately, you can type what you want to show directly in quotes and combine that with variables by using a "+" (plus, or addition sign). Doing this allows you to print a description of the result to the console. A series of characters inside quotation marks is called a "string", as in a string of text. Remember to leave a space after to colon to print that space to the console.

var someThing;
someThing = 32;
console.log("First someThing: " + someThing);
someThing = 64;
console.log("Second someThing: " + someThing);

Talk about scope for variable purposes.

In addition to "var", there is also "let" and "const", which are newer types of variables. You declare them the same way you do with "var", by typing it in front of your variable. [describe differences]

JavaScript Variable Value Type: Functions

Where variables are used as placeholders for values, functions can be used as placeholders for multiple statements of code. Instead of writing the same lines of code over and over, a function name can be used as a placeholder for that code. Using a function name in code like a variable, so that the code is read by the interpreter at that position is called "calling" the function. To call a function, we simply use the function's name, followed by open and closing parentheses. Just like strings have quotes, arrays have brackets, and objects have curly brackets, when writing and reading code, functions are indentified by having parentheses "()" after the function name. It doesn't matter how much space is in between, as long as it is only space, but since it's used for identification when inspecting the code, it's often placed immediately after the function name.

someFunction();

This is the correct way to call a function.

Just like regular variables, we need to declare them, or they will be "undefined" and we'll get an error that says it's not defined. The code contained within the function will be written where it is declared. To declare a function, instead of using "var", "let", or "const", functions use the keyword "function". However, there are differences to defining functions vs regular variables. There's no use of an equal sign or colon to declare a function's name since they aren't directly assigned to values, instead they contain statements (lines of code) and return values.

If you put the below into your script, you would get a syntax error. It expects the parentheses.

function someFunction;

This next one will also produce a syntax error, and not a full definition, since a function definition needs to include a place for lines of code to be included.

function someFunction();

Curly brackets (or braces) "{}" are used for objects, but they are also used for situations in which it is desired to group multiple lines of code into one thing. For an object, you're grouping properties and values, but with functions you're grouping statements.

So,just to be clear, a function definition will need to include both parenthesis and curly brackets. Either of the below will produce a syntax error. The functions are not declared correctly.

function someFunction();
function someFunction{};

However, the code below is correct.

function someFunction(){};

When this function is defined, we get back a value of "undefined", because we did not give the function any information to process. There are no syntax errors though. The function has been declared, so the browser can load it into memory and be prepared to run it. It's name is "someFunction" and it has no values passed in or statements to process.

As explained previously, to call the function, instead of declaring it, we simply take away the "function" keyword and the curly brackets. We'll use the function's variable name (the function name), then we add "()", which tells the interpreter that this is a function variable, and that's it. The below will run the function called "someFunction".

someFunction();

At the point that the interpreter gets to this line, whatever statements are in the curly brackets of the "someFunction" declaration will be ran.

If you just have a small script that doesn't do a whole lot of different things, you don't have to use functions in your code, you can just list the commands in the script. However, the purpose of functions is to help with organizing the script into groups of commands that serve specific functions, which also makes it easier to troubleshoot.

Now, when we add commands we could do it all on one line, like this...

function functionName(){var hello="hello";console.log(hello);hello="goodbye";console.log(hello);};function functionGoodbye(){var goodbye="hello";};

The above code actually works, however, notice how everything blends all together and it's very hard to read. That's why it's written over multiple lines, for the sake of clarity, like this...

function functionName() {

var hello = "hello";
console.log(hello);

hello = "goodbye";
console.log(hello);

}

function functionGoodbye() {

var goodbye = "hello";

}

Now we can tell we were looking at two separate functions and only the first function is using "console.log()" (which sends information to the browser's console. The curly brackets act as frames for the function's commands. They function a lot like html opening and closing tags. The commands are inset so it's easier to tell they belong to that function. We still have one small problem to deal with. If we place this code in the script, it's error free, but nothing will happen.

functionName();

The above command will run the functionName function's commands.

Let's take a closer look at this function to see what's happening with it.

function functionName() {

var hello = "hello";
console.log(hello);
hello = "goodbye";
console.log(hello);

}

functionName();

You can put this code into your script, save the file, and reload the file in your browser. Either open the file, or if you have it loaded already, with the file's tab active refresh the page by hitting F5 on your keyboard. Now look at the console to see what happend. It should say "hello" and then "goodbye". However, if you look at the code, "console.log()" is used twice with the same variable, hello. The first command declared the variable, the second sent the information to the console, the third reassigned the variable to represent "goodbye", and the fourth sent that information to the console.

JavaScript Scope

JavaScript Function Arguments

One is a place in the code for passing values into the function, and the other is place to put multiple statements. Values can be placed within the parentheses, but it isn't always necessary and we'll get to that later.

The Document Object Model (DOM)

By now you might be thinking, "ok, ok, but when do I get to actually make something?!" Don't worry, we're about to soon! This is the section you were looking for! The DOM is the key to creating things, and interacting with the page in JavaScript.

However, you might be wondering, "so, what is the DOM anyway?"

A "document" is like a file of information for the page. One of the main functions of JavaScript is to manipulate components of an HTML page in the browser. Since JavaScript is an object programming language, it represents the html file as an object that is linked to the JavaScript keyword "document". That's essentially the JavaScript equivalent to the html tags <html></html> and everything it holds.

When an HTML page is loaded into the browser window, it sets up a location in memory for the document object. The document object is linked to other objects in memory as properties. The memory profile of objects that make up the page is the Document Object Model.

A web browser has a built in JavaScript engine which allows you to access the DOM. You can interact directly with the DOM in the browser's console. The console will interpret JavaScript code when you enter it at the console's input field. You can access and view the document properities by entering the word "document" into the console. The console then returns to you the document object. As an object, the document has properties, such as "head," "title", and "body", for example. If you click on it, the console will show you the list of properties it has. HTML elements are represented as objects in groups called "HTML collections". If you wanted to, you could use JavaScript in the console to manipulate the DOM and alter what is shown in the browser window.

Finally! We can start writing JavaScript! Let's take our template and create the body structure of our html file and h1 within the body, like in the example below, but do it in a JavaScript script instead of using HTML.

<body>
<h1>HELLO WORLD!</h1>
</body>

So, how do we do this? To attach JavaScript code to your HTML file, you use <script> </script> tags, or use the tags to link to a JavaScript file with extension ".js". Let's start by writing directly in the html file within the script tags. We'll talk about linking to a JavaScript file later.

You could, technically, place the script tags anywhere in the html file... however, when positioning the script tags, keep in mind that if the JavaScript code references anything below the script tags, you'll have issues, because the browser reads the file top to bottom, and the html being referenced isn't loaded into memory at the time the JavaScript code is interpreted. The html information has to be loaded into memory before the JavaScript code tries to retrieve the information. There are work arounds for this, but what I like to do is place the script tags below the closing <body> tag.

<html>
 <head>
 </head>
 <body>
 </body>
 <script>
   // JavaScript Here!
 </script>
</html>

So, now that you know where to put your code, let's start coding! In order to recreate our former html example (including the body element), we'll have to create the HTML objects and then place them into the proper locations. So, for this example, go ahead and delete the html tags that indicate the body of the document <body></body> from your template. Let's start out by creating the objects (body, h1, and the string 'It Works!'). Creating them means that JavaScript will set up memory locations for them, they'll be added to the DOM, but won't be located where we want them. In order to access them after creation, we'll need a reference to the memory location, so we'll need to use variables. Let's start with the body and h1. We'll use "bodyElementObject" and "h1ElementObject".

<script>
  let bodyElementObject = document.createElement('body');
  let h1ElementObject = document.createElement('h1');
</script>

Ok, so what did we do here? We've got two statements. Each statement creates an HTML element within the DOM. Each element name is a string argument within the parameters of a function which is a property of the document object (called "methods," see below). The result is then assigned to a declared variable. See how quickly all that information came together?

When the browser reads an html file, it takes all the information on that file and files linked to it, creates a technical model of the page in memory, and displays the details of the page from that model. This model is called the document, or the Document Object Model, or DOM. The JavaScript keyword for accessing the DOM is "document". document.createElement('h1'); This creates a document element, or a memory space in the DOM for the equivalent of an HTML h1 tag. var hello = document.createElement('h1'); This command creates the element, and then sets the variable "hello" to represent that element. hello.innerHTML="YES! IT WORKS!"; This command takes a string, "YES! IT WORKS!", and places that value inside the "hello" h1 element as if the value were in between opening and closing h1 tags. Whatever "innerHTML" is set to, becomes the HTML that would go in between the opening and closing HTML tags of the variable's element. So, you could actually write some html in between the quotes and it will function the same way it would as an html file. (give an example, hard to explain) document.body.appendChild(hello); This command takes that element created in memory, and places it in the body of the document. explain parent-child using html language... The body becomes the parent, and the "hello" element, with the value of an h1 element that contains innerHTML, becomes the child of the body.

Before I continue to explain "hello = document.createElement('h1');" I think we should discuss objects and the DOM.

Methods

Methods are functions which are attached to an object as a property.

Now that we've created variables for our elements, we can attach them to objects within the DOM by a method of those objects called "appendChild". We're going to want to place the body object within the document object, and the h1 object within the body object. The order in which we do this does not matter.

bodyElementObject.appendChild(h1ElementObject);
document.appendChild(bodyElementObject);

Or...

document.appendChild(bodyElementObject);
bodyElementObject.appendChild(h1ElementObject);

Notice how the quotes aren't necessary for these arguments? That's because we're not passing in strings, we're passing in variables. Just to be clear, this would go beneath the previous code within the script... so, this is what we've done so far.

<html>
 <head>
 </head>
 <script>

  let bodyElementObject = document.createElement('body');
  let h1ElementObject = document.createElement('h1');

  document.appendChild(bodyElementObject);
  bodyElementObject.appendChild(h1ElementObject);

 </script>
</html>

Now, we still won't be able to see anything yet, because we haven't added our text object. There's a few ways of doing this, I'll show you two ways. One way is to create a text node object, then append that to the h1 element.

let textObject = document.createTextNode('IT WORKS!');
h1ElementObject.appendChild(textObject);

The other way is to edit the contents of the h1 object directly with the object's built in "innerText" property.

h1ElementObject.innerText = "IT WORKS!";

Now, save your html file and open it. Tada! Did it work? If not, check and make sure everything was typed correctly. If it did, congratulations! You just edited an html page with JavaScript!

Assigning Id and Class

We're going to be mostly working with modifying the HTML elements. First, let's add an id and class to the element we created above that holds the text node. First the id.

<!-- in HTML -->

<h1 id='h1-object-id'></h1>

Is the same as...

// in javaScript

let h1ElementObject = document.createElement('h1');
h1ElementObject.id = 'h1-object-id';

Now, the class.

<!-- in HTML -->

<h1 class='blue-text'></h1>

Is the same as...

// in javaScript

let h1ElementObject = document.createElement('h1');
h1ELementObject.classList.add('blue-text');

Attaching Property Directly to Element

Skip the CSS... what if I want to modify the element's CSS property directly? This is like using inline styles.

h1ElementObject.style.color = "#00FF00"; // in javaScript

This is for adding a class name to an element, so that it can be affected when the class name is listed in the CSS file. This technique is going to become very useful later.

Selecting ID's

When tagging HTML elements for reference, you can sometimes place an ID on the element, depending on the element type. Such as " id="elementID " You can then access this element with JavaScript using " document.getElementById() " by placing the name of the ID in single or double quotes inside the parentheses. Such as " document.getElementById('elementID') " Now you can do something with the element, such as send it to the console: " console.log('document.getElementById("elementID")'); "

Linking to External Script Files

To link to the file, you add a source location to the first script tag without anything between the tags, like this, if they're in the same folder: " <script src="JavaScriptFileName.js"></script> ". If not in the same folder, type the path to the source file the same way you would for the "src" of an image file.

https://youtu.be/hA-fYOlLXPQ

Current Category:

[Home] ===> [Knowledge and Profession] ===> [Web Development]

--Related Subcategories--

[Technology] [Information] [Systems] [Software Development]