Javascript (HTML DOG)
Javascript (HTML DOG)
Javascript (HTML DOG)
There’s a few ways to try out JavaScript, and when learning it’s
best to try them out to see what works for you. But first, how
does JavaScript relate to HTML and CSS?
HTML, CSS and JavaScript
Mostly, JavaScript runs in your web browser alongside HTML and CSS, and can be added to any
web page using a script tag. The script element can either contain JavaScript directly (internal) or
link to an external resource via a src attribute (external).
A browser then runs JavaScript line-by-line, starting at the top of the file or script element and
finishing at the bottom (unless you tell it to go elsewhere).
Internal
You can just put the JavaScript inside a script element:
<script>
alert("Hello, world.");
</script>
Link To Us!If you've found HTML Dog useful, please consider linking to us.
External
An external JavaScript resource is a text file with a .js extension, just like an external CSS
resource with a .css extension.
To add a JavaScript file to your page, you just need to use a script tag with a src attribute
pointing to the file. So, if your file was called script.js and sat in the same directory as your
HTML file, your script element would look like this:
<script src="script.js"></script>
You might also come across another way on your view-source travels: inline. This involves
event attributes inside HTML tags that look something like <a href="somewhere.html"
me</a> . Just move along and pretend you haven’t witnessed this
aberration. We really, really, really want to separate our technologies so it’s preferable to avoid
this approach.
Console
The last way is great for getting instant feedback, and it’s recommend if you just want to try a
line out quickly.
In a modern browser you’ll find some developer tools - often you can right click on a page, then
click “inspect element” to bring them up. Find the console and you’ll be able to type JavaScript,
hit enter and have it run immediately.
Search the net if you can’t find your dev tools or console - they’re changing in browsers all the
time.
Let’s go!
To get started, the best way is the internal method. You can modify the contents of
the script element and refresh the page just like you’re used to - quick and easy.
Now it’s time to learn some JavaScript. Good luck!
Variables
Think, if you will, of a variable as a shelf with a name so it’s easy to get back to. You’ve named
a shelf surname.
You can name a variable anything you like, but it’s best to name it in a way that tells what
you’ve stored there. For example, surname is better than mything or s.
When you type a variable name into the console you are asking the browser, which looks after
the shelves, to go find the shelf and give what’s on it to you. This is also known as the
variable’s value. The value can be almost anything - in surname, you’ve stored some letters,
known as a string. You can also store numbers and a myriad other kinds of data.
So, a variable has a name and a value.
They are the way we store data, and you’ll be using them a lot.
There are two parts to creating a variable; declaration and initialization. Once it’s created, you
can assign (or set) its value.
Declaration
Declaration is declaring a variable to exist. To return to the shelf metaphor, it’s like picking an
empty shelf in a massive warehouse and putting a name on it.
As above, to declare a variable, use the var keyword followed by the variable name, like this:
var surname;
var age;
Notice those semicolons (“;”)? Almost every line in JavaScript ends in a semicolon - you’ll be
using them a lot.
Initialization
Initialization is giving a variable its value for the first time. The value can change later, but it is
only initialized once.
You initialize a variable using the equals sign (=). You can read it as “the value of the variable
on the left should be the data on the right”:
Assignment
As mentioned, you can set a variable’s value as many times as you like. It’s
called assignment and it looks very similar to initialization. You again use the equals sign, but
there’s no need for the var keyword because we’ve already declared the variable.
It’s like this, yo:
name = "Andy";
age = 43;
Only do this if you’ve declared the variable using the var keyword!
Doing Math
Variables can be used to store strings and numbers (amongst
other things), but here the focus is on numbers.
How much fruit?
In your console, let’s create two variables. One will be the number of apples we have, the second
will be the number of pears.
(10 + 2) / 2 + 4 * 2
The part in brackets is worked out first. So this becomes…
12 / 2 + 4 * 2
…which works out to…
6+4*2
Then things are done in operator precedence order. If multiple sums are of the same precedence
then they are evaluated left to right.
The multiplication is higher precedence so is done first, which works out to…
6+8
This is used to work out the final value:
14
Whew!
Logic
A really important part of programming is being able to compare
values in order to make decisions in code. When a comparison is
made the outcome is either true or false; a special kind a of data
called a boolean. This is logic.
Like when doing math, there’s a set of operators that work on booleans. They are used to
compare two values, on the left and right of the operator, to produce a boolean value.
The following comparisons are made in the console. The result we get from each line (shown
underneath) will be true or false; these are booleans.
Equality
To find out when two values are equal, use the triple equals operator (“===”).
true
We can also determine if two values are not equal using the triple not equal operator (“!==”).
true
It’s important to know that strings containing a number and an actual number are not equal.
'10' === 10
false
10 > 5
true
Next we use the less than operator (“<”) to determine if the left value is smaller.
false
That example gives back (or returns) false, because 20.4 is not a smaller number than 20.2.
Combined comparisons
Combining a comparison of equality and size can be done with the greater than or equal
to and less than or equal to operators (“>=” and “<=” respectively).
10 >= 10
true
10 <= 5
false
Conditional
Logic is used to make decisions in code; choosing to run one
piece of code or another depending on the comparisons made.
This requires use of something called a conditional. There are a
few different conditionals that you might want to use, but we’ll
just focus the one used most commonly: if.
If
It’s very simple: if some logic (the condition) is true, run a block of code. You can also supply
more code to be run if the condition is not true, and supply additional conditions and blocks of
code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:
if (10 > 5) {
// Run the code in here
}
The code between the braces - “{” and “}” - is called a block, and this one is linked to
the if statement. It’s only run if the conditional (between the parentheses) is true.
10 is indeed greater than 5, so the code in the block would run.
Oh, and the line starting “//”? The double slashes indicate comment, which means that
everything after the slashes until the end of the line is ignored by the browser.
If-else
The if-else form of an if statement is used to run an alternative piece of code if the conditional is
not true. The code in the if block below will be ignored, for example - only the code in
the else block will be run.
if (43 < 2) {
// Run the code in here
} else {
// Run a different bit of code
}
Looping
Loops are a way of repeating the same block of code over and
over. They’re incredibly useful, and are used, for example, to
carry out an action on every item in an array (we will come to
arrays later) or in searching.
Two of the most common loops are while loops and for loops. They combine a conditional and a
block, running the block over and over until the logic of the conditional is no longer true, or until
you force them to stop.
While
A while loop repeats a block of code while a condition is true. Like an if statement, the condition
is found in parentheses.
var i = 1;
while (i < 10) {
alert(i);
i = i + 1;
}
// i is now 10
After looping has finished the code carries on running from just after the closing brace (“}”) of
the loop’s block.
For
A for loop is similar to an if statement, but it combines three semicolon-separated pieces
information between the parentheses: initialization, condition and a final expression.
The initialization part is for creating a variable to let you track how far through the loop you are
- like i in the while example; the condition is where the looping logic goes - the same as
the condition in the while example; and the final expression is run at the end of every loop.
Functions
Functions are reusable blocks of code that carry out a specific
task. To execute the code in a function you call it. A function
can be passed arguments to use, and a function may return a
value to whatever called it.
You can save functions as the value of a variable, and you call a function using this variable and
a pair of parentheses. This is also called invoking the function.
doSomething();
findAnInterestingThing();
To create a function, use the function keyword. You then list the arguments in parentheses, and
then supply a block that contains the function’s code. Here’s a function that adds two numbers:
var jedi = {
name: "Yoda",
age: 899,
talk: function () { alert("another... Sky... walk..."); }
};
The Jedi’s name and age are properties - they are essentially variables within the object and can
store anything a variable can. talk is a property that holds a function - a method.
You can get data back out of an object using the dot syntax:
jedi.name;
Yoda
jedi.age;
899
jedi.talk();
jedi.lightsaber = "purple";
Properties can be any kind of data including objects and arrays. Adding an object as a property of
another object creates a nested object:
var person = {
age: 122
};
person.name = {
first: "Jeanne",
last: "Calment"
};
Creating an empty object and adding properties and methods to it is possible too:
Arrays
Arrays are lists of any kind of data, including other arrays. Each
item in the array has an index — a number — which can be
used to retrieve an element from the array.
The indices start at 0; that is, the first element in the array has the index 0, and subsequent
elements have incrementally increasing indices, so the last element in the array has an index one
less than the length of the array.
In JavaScript, you create an array using the array-literal syntax:
Milk
It’s also possible to set the value at a particular index, again using the square bracket syntax:
shoppingList[1] = 'Cookies';
You can find the number of elements in the array using its length property:
shoppingList.length;
You can use push and pop methods to add and remove elements from the end of the array:
shoppingList.pop();
Here’s an example that creates, pushes, pops and iterates over an array, passing each name to a
function called helloFrom. helloFrom returns a string with a greeting: “Hello from ” and then the
person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron”
and “Bob”.
people.push('Bob');
people.push('Dr Evil');
people.pop();
Getting an Element
The first thing to know is how to get an element. There are a number of ways of doing it, and
browsers support different ones. Starting with the best supported we’ll move through to the
latest, and most useful, versions.
By ID
document.getElementById is a method for getting hold of an element - unsurprisingly - by its ID.
By Tag Name
document.getElementsByTagName works in much the same way as getElementById, except that it takes
a tag name (a, ul, li, etc) instead of an ID and returns a NodeList, which is essentially an array of
the DOM Elements.
By Class Name
document.getElementsByClassName returnsthe same kind of NodeList as getElementsByTagName,
except that you pass a class name to be matched, not a tag name.
By CSS Selector
A couple of new methods are available in modern browsers that make selecting elements easier
by allowing the use of CSS selectors. They are document.querySelector and document.querySelectorAll.
button.attachEvent('onclick', handleClick);
Notice that it requires onclick, not just click. You’ll find this is the same for most events. It’s
things like this that caused the creation of libraries like jQuery (which we’ll come to) - they help
you so that you don’t have to care that the way of listening for events is different across
browsers.
Data about a particular event is passed to the event callback. Take a look at handleClick, declared
above. You can see its argument: event - it’s an object whose properties describe what occurred.
Here’s an example event you might see into a click event callback like handleClick. There are lots
of properties giving you an idea of where the event occurred on the page (like pageX and offsetY) -
these are slightly different because they depend on the reference point used to measure from.
You can also see the target which is a reference to the node that was clicked.
{
offsetX: 74,
offsetY: 10,
pageX: 154,
pageY: 576,
screenX: 154,
screenY: 489,
target: h2,
timeStamp: 1363131952985,
type: "click",
x: 154,
y: 395
}
AJAX
In the early years of the web things were simple — a page was
text, perhaps with styling, and it contained links to other pages.
To get new content you moved from one page to the next. But as
developers got more ambitious with the web, attempting to build
interactive (“native-like” applications), it was obvious that there
needed to be a way to load new content into a page without a
full reload.
To retrieve new content for a page, like new articles on an
infinite-scroll site or to notify you of new emails, a tool called
an XML HTTP Request (XHR) is used. Web apps that do this
are also called AJAX apps, AJAX standing for Asynchronous
JavaScript and XML.
Almost all sites that pull in new content without a page reload (like Facebook, Gmail, Google
Maps etc) use this same technique. In fact, it was Microsoft developing Outlook Web Access
who originally created the XMLHttpRequest.
JSON
JSON — JavaScript Object Notation — is a set of text
formatting rules for storing and transferring data in a machine
and human readable way. It looks a lot like the object literal
syntax of JavaScript, and it is from there JSON originates.
But JSON is not JavaScript. Officially it’s a totally different language with its own spec but it
plays such a big part in JavaScript development that it’s important to cover.
Here’s some JSON:
Using JSON
Data is either converted to or from JSON, using methods called stringify and parse respectively.
JSON is an object available in pretty much all modern browsers but there are ways of adding to a
browser that doesn’t have it.
car.model = "P1";
Scope
Scope is the term used to mean variable visibility — a
variable’s scope is the part of your code that can access and
modify that variable. JavaScript has function scope — but what
does that mean and how is it different to other languages?
Scope is, in many programming languages, dictated by the block in which the variable was
declared. A block, in C-like languages, is anything between two curly braces, or indentation in a
language like Python. For example, the b variable below is not available outside the curly braces
in which it was declared:
var a = 10;
if (a > 5) {
var b = 5;
}
Function scope
JavaScript does things a little differently. It uses function scope. This means that variables are
not visible outside of the function in which they were declared. If they are not declared inside a
function then they are available globally.
The example below demonstrates that a variable is only visible inside the function in which it
was declared. The doSomething function is the variable a’s scope.
doSomething();
console.log(a); // a is undefined
Comparing this to the block scope example above, you can see that, in JavaScript, b is available:
var a = 10;
if (a > 5) {
var b = 5;
}
var c = a + b; // c is 15
Child scopes
Variables are available in child scopes of their own scope. For example, doSomethingElse is a
child of doSomething, so a is visible inside doSomethingElse.
doSomething();
Functional scope is a very powerful tool for creating elegant code, as we’ll see, but it can take
some time to get your head around.
jQuery
The set of tools used to allow modification and control of the
DOM are a bit of mess because they differ across browsers,
generally for historical reasons. To make your job easier, a
number of libraries have been created that hide these
differences, providing a more uniform way of interacting with
the DOM. Often they also provide AJAX functionality, taking
the burden of that complexity away from you.
jQuery is far and away the most popular DOM library and it is
used on a huge number of websites.
By the way, the way you interact with the DOM (or any service that you use via code) is called
an Application Programming Interface or API.
jQuery has a very distinctive syntax, all based around the dollar symbol. Here’s some:
$('.btn').click(function () {
// do something
});
This code attaches a click handler to all elements with a class of btn. This selector syntax is core
to jQuery.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
jQuery is added to a page by simply including it as a file using a script element. Download it from
jquery.com, or include it from a Content Delivery Network (CDN) such as CDNJS:
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
In the following pages we’ll be taking a look at jQuery for selecting and manipulating
elements, AJAX and at some of its other useful tricks.
It’s not always the best idea to use a library, and it’s best to choose whether to use a framework
based on the specific project. For example, jQuery is a large file to introduce to a page and slow
the downloading of that page, particularly on mobile browsers with potentially weak
connections.
$('.note').css('background', 'red').height(100);
jQuery uses a really neat chainable syntax that allows code like the above. This works because,
for any kind of “setting” method, jQuery returns the same thing as the selector function (“$”)
does: $ is a function that returns a jQuery wrapper around an element. .css is a method of that
jQuery wrapper and it too returns the same wrapper. .height sets the height (duh) of the element
selected, and of course there’s an equivalent for width.
Advertise Here!On a long-established, well-read, well-respected web development resource.
Context
It’s sometimes useful to limit the area of the DOM from which an element can be selected. The
area of the DOM used is also known as a different context.
To tell jQuery which area you want to select from you pass a second argument that can be
a DOM element, a string selector (selecting an element that jQuery will find and use) or
a jQuery object. jQuery will only search within this context for your selector.
Here’s an example. Notice that the variables that are used to store jQuery objects begin with
a dollar. This a convention to help you and readers of your code understand that it’s a jQuery
object being saved.
jQuery: AJAX
jQuery has some AJAX helper methods that save time and are
much easier to read. They are all properties of
the $ variable: $.get, $.post, and $.ajax.
$.ajax is
the main method, allowing you to manually construct your AJAX request - the others are
shortcuts to common configurations, like getting data or posting it.
Here’s an example that gets some data from a server:
$.ajax({
url: '/data.json',
method: 'GET',
success: function (data) {
console.log(data);
}
});
You can see that a configuration object is used to tell jQuery how to get the data. The basics are
supplied: a URL, the method (which actually defaults to get) and a function to be called when the
data is retrieved, named the success callback.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
$.get
This example is just getting some data and, because this is a very common activity, jQuery
provides a helper: $.get.
$.post
Sending data to a server is just as easy, using the $.post method. The second argument is the data
to be sent - it can be almost anything except a function: jQuery will figure out how to send it for
you. How convenient!
$.ajax
Of course, if you want more control over how data is sent, use $.ajax to set the request up
manually.
$.ajax({
url: '/save',
method: 'POST',
data: { username: 'tom' },
success: function (data) {
console.log(data);
}),
error: function () {
// Uh oh, something went wrong
}
});
window.addEventListener('DOMContentLoaded', doSomething);
But we can do it more easily with jQuery, and it will work cross-browser:
$(window).ready(doSomething);
This can be shortened further to:
$(doSomething);
In all the above examples, doSomething is a JavaScript function.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
Load
In other situations it’s better to wait for the page to fully load - that is, when all stylesheets and
images have been downloaded.
To do this without jQuery, listen for the load event on the window:
window.addEventListener('load', doSomething);
But it’s even easier with jQuery:
$(window).load(doSomething);
Type checking
Finding out what kind of data is stored in a variable in JavaScript is awkward at best so jQuery
provides some tools to help you out:
$.isArray([1, 2, 3]);
true
$.isFunction(function () { });
true
$.isNumeric(10);
true
true
Object-Oriented Code
Humans are good a categorizing. Objects are a way to
categorize behavior and data, making large amounts of code
easier to design and think about. In fact, object-
oriented programming can be found in many languages used to
build all kinds of software and is considered a very good way to
write code.
We’ve already looked at objects in JavaScript - they’re collections of named properties and
methods, and they can be created on the fly using the object literal syntax:
var user = {
name: "tom",
say: function (words) { alert(words); }
};
One reason using objects to hold data is useful is that, as mentioned, human brains are very good
at categorizing things: a boat; a chair; a moose. Creating objects in code helps you to think about
how the different parts of your code fit and (hopefully) work together.
In a large application you may have a great number of objects interacting with each other.
Remember that objects are a grouping together of properties (like name) and methods (like say)?
This grouping of data and behavior into one entity is called encapsulation.
A powerful tool available to you when building applications using objects is called inheritance.
This is where an object inherits properties and methods from another object. An object can alter
the properties and methods it inherits and add additional properties and methods too.
So, for example, you could create a moose object that inherits behavior from a mammal object.
The moose could alter the mammal’s furriness, for example. You could then create
a pangolin object that also inherits from a mammal. But, of course, pangolins aren’t furry, and
they might have a different scaliness property.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
In practice
There are many ways to achieve inheritance in JavaScript. The most commonly used is
the constructor pattern. In this pattern, a function called a constructor is used to create new
objects. Constructors are used in combination with the new keyword to create objects.
Here’s an example constructor. Note the capital letter on Person - this is an important
convention. Generally, in JavaScript, if it’s got a capital first letter, it’s a constructor and should
be used with the new keyword.
{
name: "Tom"
}
In the constructor pattern you manually create the object from which the new objects will inherit
by adding properties and methods to the prototype property of the constructor function. Like this:
Creating Elements
Creating elements using HTML tags isn’t the only way to do it
— in fact it’s possible to create, modify and insert elements
from JavaScript.
Here’s an example that creates a div, adds some text to it and appends it as the last element in the
body:
Removing an element
Removing elements is just as fun. Each DOM element has a property that’s actually the DOM
element’s parent. To remove an element, you call the removeChild method of the parent, passing
the child element you want to remove. Something like this:
div.parentNode.removeChild(div);
Simple, eh?
Canvas
The HTML 5 specification has introduced a slew of new and
exciting technologies to the web. Here we’ll expand on just one:
the Canvas API. It’s for drawing pretty, whizzy things.
Canvas is a new DOM API for drawing on a 2- or 3-dimensional (you guessed it) canvas. What
follows just looks at the 2D version, but the 3D technology is called WebGL and there are some
incredible things being done with it.
The first thing to know is that canvas is a new element in the HTML 5 specification. To begin
drawing on the canvas, you grab hold of it and retrieve a particular context - either 2d or webgl:
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 10, 10);
</script>
Try this out on a page to see a little black square!
The getContext function retrieved the correct context, which is an object whose methods are used
to draw, fill and generally modify the canvas. Above we’re using fillRect, which takes
the x and y position of the top left corner of the rectangle as the first two arguments, and
the width and height dimensions as the latter two.
New Examples Section!See all of this code stuff in action, and play around
with it.
Animation
canvas works a bit like a real canvas - pixels are drawn and layered on top of each other until you
erase - clear - them. This means that if you want to animate something moving across a canvas
you have to repeatedly clear the canvas (or a section of it) and redraw the scene.
In the next example we’ve animating the square bouncing around the canvas, which automatically
resizes to fill the screen. loop is the business part of the code. The clearRect function is used to
clear the entire canvas before each frame.
window.addEventListener('resize', resize);
window.addEventListener('load', function () {
resize();
Local Storage
When building more complex JavaScript applications that run in
a user’s browser it’s very useful to be able to store information
in the browser, so that the information can be shared across
different pages and browsing sessions.
In the recent past this would have only been possible
with cookies - text files saved to a user’s computer - but the way
of managing these with JavaScript was not good. Now there’s a
new technology called local storage that does a similar thing,
but with an easier-to-use interface.
Unlike cookies, local storage can only be read client-side — that is, by the browser and your
JavaScript. If you want to share some data with a server, cookies may be a better option.
To save some data, use localStorage.setItem.
localStorage.setItem('name', 'tom');
The first argument is the identifier you’ll later use to get the data out again. The second is the
data you want to store.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
Getting back out again is simple — just pass the identifier to localStorage.getItem.
// Object example
localStorage.setItem('user', JSON.stringify({
username: 'htmldog',
api_key: 'abc123xyz789'
}));
JSON.parse("a");
// Produces a SyntaxError
You can account for exceptions being thrown using a construct called a try-catch. It looks like
this:
try {
JSON.parse("a"); // Produces a SyntaxError
} catch (error) {
// Handle the error
alert(error.message);
}
If an error is thrown in the try block it doesn’t prevent continued code execution - the error is
passed into the catch block for you to deal with. Here, for example, you could tell the user that the
JSON that was passed in was invalid.
The error passed to the catch block (like a function) is an object with a message property you can
use to see what went wrong.
In almost all cases you’ll want to ensure your code handles errors gracefully. It’s worth learning
when errors are likely to occur so that you can defend your code against them.
Advertise Here!On a long-established, well-read, well-respected web development resource.
Creating errors
It’s possible to generate your own errors for someone else to deal with. This is done using
the throw keyword:
Defensive code
Errors are most common at the front line where data from outside your code is brought in, and so
those are the areas you need to be most careful.
Try-catch blocks are one way of handling errors, but you can also check the type of some data
and provide sensible defaults if you do receive ill-formatted data. Being defensive in your code is
a good way of avoiding errors.
Regular Expressions
Regular expressions are another type of data in JavaScript,
used to search and match strings to identify if a string is a
valid domain name or to replace all instances of a word within a
string, for example.
Regular expressions have their own syntax and often you’ll need to consult a regular expression
reference if you’re doing something complex. Just search the Internet for what you need!
The following is a very high-level overview of a complex area, going through some simple
examples to show how to do it in JavaScript.
if (lowerCaseString.match(regex)) {
alert('Yes, all lowercase');
}
match produces a truthy value if the regular expression matches the string
(lowerCaseString) match is called on. The string matches, so execution drops into the if statement to
show an alert.
Regular expressions can also be used to replace text:
This expression matches the word “everything” and the word “nothing” and replaces all
occurrences of them with the word “something”. Notice the “g” after the closing forward slash
(“/”) of the regular expression - this is the global flag that means the expression should
match all occurrences, rather than just the first, which is what it does by default.
Flags always go after the closing slash. The other flag you might need to use is the case-
insensitive flag. By default, regular expressions care about the difference between uppercase and
lowercase letters, but this can be changed using the “i” flag.
Closures
A closure is a function that returns a function. The function that
is returned (the inner function) is created inside the called
function (the outer) so - due to the scoping rules we’ve seen -
the inner has access to the variables and arguments of the outer.
Closures are a powerful tool but can be tricky to understand. Mastering them, however, will
allow you to write some very elegant code.
Here’s an example:
alert(retriever());
10
The saver function returns a function that, when called, retrieves the value that was passed into
saver. The inner can do so because it was created in the scope of the outer and functions created
in a particular scope retain access to variables in the scope even if they are called outside of it.
Advertise Here!On a long-established, well-read, well-respected web development resource.
One way to use closures is for creating functions that act differently depending on what was
passed to the outer function. For example, here’s an add function. The value passed to the outer
function is used to add to values passed to the inner.
alert(addFive(10));
15
The inner, here saved as addFive, has access to a when it is called because it was created in the
same scope as a. The inner adds a and b and returns the result.
In the above example, the inner is saved as addFive because it adds 5 to anything passed to it. A
different adding function, using strings, could be created in the same way:
alert(hello('tom'));
Hello tom
Node.js
Much of the code we’ve seen so far has been with a web
browser in mind, using DOM APIs that are only available in that
environment. But JavaScript has found its way to the other side
of the client/sever divide in the form of Node.js (also known as
just Node).
Node is a platform for building servers in JavaScript, built on Google’s V8 JavaScript engine.
V8 is also found in the Chromium browser project and derivatives like Google Chrome.
If you have used preprocessors like PHP then Node may take some getting used to, but the main
thing to remember is that it works like JavaScript in the browser: idling until an event occurs,
responding to that event and returning to idle.
Install
You can grab Node from nodejs.org. You’ll get npm in there too, which is the Node Package
Manager, used to install others’ modules to make developing things easier.
Advertise Here!On a long-established, well-read, well-respected web development resource.
Example
Node comes with a core set of modules, one of which is “http”, used to set up a web server.
Here’s a simple HTTP server example that serves one page to all requests:
server.listen(1337, '127.0.0.1');
JS Apps
These days JavaScript is being used to build large-scale web
applications and the web is maturing as a platform for doing so.
These apps have the advantage of being able to be highly
interactive and responsive, requiring fewer page loads and
HTTP requests.
Ideas are being taken from the software engineering world on how to build such applications, so
here’s a few ideas on how to do it before a look at some JavaScript frameworks designed to
assist building larger apps.
Modularity
A key concept in software engineering is the idea of modularity in code. Separating out the key
functionality of your app improves its maintainability and has a number of development
advantages.
For example, in a modular system a component can be swapped out at little cost, so long as the
interface between the components remains the same. Similarly, different components can be
worked on in isolation from each other, which is beneficial for development time and human
resource management.
Modules can be connected in a number of different ways - one way is with modules
communicating only with a central event and resource management module, sometimes referred
to as a sandbox, and not communicating directly with each other. A module can publish a
notification about an event occurring without caring who or what else will act on it. This means
that if one component ceases to function the others may continue, and that a new module can be
easily added without affecting the others.
If you want to begin building modular apps, a library called RequireJS is a good place to start.
Link To Us!If you've found HTML Dog useful, please consider linking to us.
MVC Architecture
Model-View-Controller (MVC) architecture is a way of structuring code within an application.
A model is concerned with the data in your app; the view with displaying or outputting data and
the controller with the business logic and coordinating the models and views. An app might
have many of all three.
For example, you might have a User model that is responsible for retrieving information about a
user. Then you’d have a Login controller that managed when to show a log-in screen to a visitor.
The LoginView would be responsible for showing the screen and handling form submission, the
data from which would be passed to the Login controller through to the User model.
As with any system there are a number of variations on this, and a number of client-side
frameworks have addressed this idea in JavaScript. We’ll take a quick look at
two: Backbone and Angular.
Backbone
Backbone.js (aka Backbone) is designed to add structure to
client-side applications, to avoid a spaghetti-code mess.
In the words of Backbone.js:
Backbone.js gives structure to web applications by providing models with key-value binding and
custom events, collections with a rich API of enumerable functions, views with declarative event
handling, and connects it all to your existing API over a RESTful JSON interface.
Models are where you keep your data, and in Backbone they are special JavaScript objects
created from a Backbone’s built-in Model, optionally extended by you to add functionality.
Making a Model looks something like this:
jediView.$el.appendTo('body');
jediView.render();
A template, often kept in a script element with a type of “template”, contains the HTML that the
view should use. For the above example, it might look something like this:
Link To Us!If you've found HTML Dog useful, please consider linking to us.
Backbone is a very large, well-used and mature project, and covering it in any depth is way
beyond the scope of this tutorial. If you’d like to learn more, Addy Osmani’s freely available
book Developing Backbone.js Applications is a great resource.
One thing to consider about Backbone is that it’s dependent on two other JavaScript
libraries: jQuery and Underscore. This makes it quite a heavy dependency to have in your
project, and that’s something worth taking into account when deciding whether to use it. Mobile
browsers may struggle to download all that code, making your site unusable.
Angular
AngularJS is an open-source client-side JavaScript framework
that uses HTML as its templating language. It’s notable for it’s
philosophy that declarative programming is better than
imperative programming for wiring up user interfaces and
creating modular components.
Angular is MVC but it works quite differently from Backbone.
Templates and views in Angular are analogous, and are just regular HTML with some added
sugar. In fact, you can put together a (very) simple Angular app without a single line of
JavaScript:
<input ng-model="name">
Link To Us!If you've found HTML Dog useful, please consider linking to us.
A controller has a scope, which is an area of DOM it has access to. Giving a controller a scope
looks like this:
<div ng-controller="AppCtrl">
<input ng-model="name">
<h1>Hello {{ name }}</h1>
</div>
A model exists within a controller’s scope, so in the above example the “name” model would be
set to “Yoda” by default, but the input would update the model and the h1 as you typed.
You’ll notice the $scope variable that the controller takes as an argument, but that seems to come
from nowhere. This is injected into the controller using a system called dependency injection.
It’s a complex area, but is a useful tool for building modular apps.
Angular doesn’t depend on anything in the page, and so the file-size footprint tends to be smaller
than Backbone. If you’re worried about your HTML validating then Angular supports using data
attributes instead of the ng attributes used above. For example, data-ng-controller.