1995 LiveScript released for NetScape Navigator. It was a language designed to by easy for non-programmers and to add cool dynamic functionality to websites. It ran in the web browser. These days all web browsers have JavaScript engines built in because it is the de facto scripting language of the web. Its name was quickly changed to JavaScript as a marketing ploy because Java was a very hot language at the time. But it has nothing to do with Java. The only thing it has in common is syntax because both languages have syntax based on C.
1996 JavaScript standardized by ECMA. The standard is called ECMAScript
JavaScript used to be famous for being really slow, but because of how important it is to dynamic web pages, companies like Google and Mozilla have sunk a tonne of money into making it faster. These days it's pretty fast and isn't only used in web browsers (see Node.js).
To get access the JS console in your web browser, Ctrl+Shift+J or Cmd+Opt+J.
2 + 4
// > 6
3*3
// > 9JS is a dynamically typed language so when declaring a variable, you don't have to say it's an int or a String or an Array. JS will figure that out itself. All you need to do is use the var keyword. (var sets up a variable in the current scope, not using var will set up a variable in the global scope. So it's best to always use var because you don't want to pollute the global scope.)
// Array of numbers
var myVariable = [4, 8, 15, 16, 23, 42];
// String
myVariable = 'Ted'; // This variable dynamically changed its type!var year = 2014;
if (year < 2014) {
console.log('It\'s the past!');
} else if (year === 2014) { // Note the strict equals
console.log('It\'s now!');
} else {
console.log('It\'s the future!');
}var age = 0;
while(age < 18) {
console.log('at age ' + age + ' you can\'t buy beer.');
}var lottery = [4, 8, 15, 16, 23, 42];
for(var i = 0; i < lottery.length; i++) {
console.log(lottery[i]);
}There are several ways to declare a function:
// Declaring a function
function square(x) {
return x*x;
}
// Assigning a 'lambda' or 'anonymous function' to a variable
var square = function(x) {
return x*x;
};
// Assigning a function with a name to a variable (Used for debugging, squareFunction does not get defined)
var square = function squareFunction(x) {
return x*x;
};Functions are first-class citizens in JavaScript. That means you can input and output functions to and from other functions. So you can use functional programming with JS. Here's an example of using a closure to curry a function:
var add = function(a) {
return function(b) {
return a + b;
};
};
var add1 = add(1);
var add2 = add(2);
console.log(add1(3)); // 4
console.log(add2(3)); // 5Here's an example of passing a function as an argument:
var doSomethingToDave = function(f) {
f('Dave');
};
doSomethingToDave(alert);
doSomethingToDave(console.log);Objects are useful for encapsulating data and methods about a certain type of thing. An object is essentially a list of key/value pairs. And the object can contain anything: Arrays, numbers, strings, functions, or other objects. The way objects are made in JS is called JSON, or JavaScript Object Notation. JSON is a really popular way to transfer information on the web. Say somebody logs into your site using Facbook and you want to get info on that person like a list of their friends or their favourite sports, Facebook will send that to you in JSON. If you want to get info from Google Maps, they'll send that to you in JSON. Most APIs these days will send you data in JSON.
Let's create an object to represent a person.
var person = { name: 'Tim', age: 20, legs: 2 };
person.name // Tim
person.age // 20Let's say Tim has a horrible accident and loses one of his legs. How do we change the object?
person.legs = 1;
// Object is now { name: 'Tim', age: 20, legs: 1 }
person.legs // 1
// You can even add properties:
person.arms = 2;
// Object is now { name: 'Tim', age: 20, legs: 1, arms: 2 }Let's add some things to our object:
var person = {
name: 'Tim',
age: 20,
legs: 2,
saySomething: function() { // In this case there's no need to wrap console.log with and anonymous function. I'm just doing it to show that you can do this.
console.log('Hello');
},
sayName: function() {
console.log(this.name);
},
lotteryNumbers: [4, 8, 15, 16, 23, 42],
favouriteShow: {
name: 'Breaking Bad',
seasons: 5,
characters: ['Walt', 'Jesse', 'Gus', 'Hank', 'Gomez']
}
}
person.name // Tim
person.saySomething() // Hello
person.sayName() // Tim
person.lotteryNumbers[2] // 15
person.favouriteShow.name // Breaking Bad
var show = person.favouriteShow;
show.characters[0] // Walt All objects inherit from a prototype which has several methods such as toString().
There are other ways to make objects. You can instantiate an object then add in all the properties:
var person = {};
person.name = 'Tim';
person.age = 20;
person.legs = 2; // It grew back
// Object is now { name: 'Tim', age: 20, legs: 2 }Or you can use a contructor.
function Person(name) {
this.name = name;
}
var tim = new Person('Tim');
tim.name // TimLet's look at some real life JSON! https://developers.facebook.com/
When you navigate to a URL, the web server will usually send you back some HTML. The HTML tells the browser the general structure of the web page. It will say "This is the title", "Here's a list of links", "Here's an image", "Here's a paragraph". The browser will go through the html and find other things it needs, like CSS files, images, or JavaScript files and it will ask the server for those and the server will send them all back.
- HTML does the structure and text.
- CSS does the style and layout.
- JavaScript does the interactivity.
the web browser turns the html into something called the Document Object Model or DOM. Essentially this is a heirarchy of all your html elements.
Take this HTML for example:
<!doctype html>
<html>
<head>
<title>Alchemy for beginners</title>
<script src="script.js"></script>
</head>
<body>
<h1>Chapter 1: Equipment</h1>
<p>
This is what an <em>alchemists' bottle</em> looks like:
</p>
<img src="bottle.jpg">
</body>
</html>This is converted into this DOM:
You can see that the body element is a parent of the h1, p, and img elements. And the h1, p, and img elements are children of the body element. The h1, p, and img elements are called siblings.
Note that the tree contains two types of elements: Nodes, which are shown as blue boxes, and pieces of simple text. The pieces of text work somewhat different than the other elements. For one thing, they never have children.
The browser exposes the DOM to JavaScript so that we can write code to add or remove DOM elements, or change the elements' attributes.
First thing we want to do is get a simple web page set up. One of the easiest ways to do this is using (Yeoman)[http://yeoman.io/].
First off, let's grab the element with the id todolist:
var todoList = document.getElementById('todolist');Now we create a p tag and some text to go in the p tag:
var todoElement = document.createElement('p');
var todoText = document.createTextNode('Do the dishes');Now we append the text to the p tag and the p tag to the todo list:
todoElement.appendChild(todoText);
todoList.appendChild(todoElement);Done! We've added an item to our to do list. There is another way to do this using the innerHTML property:
todoList.innerHTML += "<p>Go shopping</p>"; We could put this all in a function and call the function whenever we want to add something to the list:
addItem = function(text) {
var todoList = document.getElementById('todolist');
var todoElement = document.createElement('p');
var todoText = document.createTextNode(text);
todoElement.appendChild(todoText);
todoList.appendChild(todoElement);
};
addItem('Return video tapes');Either way, this is a lot of work to do something basic. In practice, we'd never need to do it this way becasue we'd be using a library called JQuery which makes it all 1000x easier. I'm just showing you this so you know what it's like in raw JavaScript and you get a sense of how to manipulate the DOM.
To remove the last item in the list, we could do this:
todoList.removeChild(todoList.lastChild);And we could put that in a function too:
removeLastItem = function() {
todoList.removeChild(todoList.lastChild);
};
removeLastItem();todoList.style.color = 'red';
todoList.style.background = '#ccc';
todoList.lastChild.innerHTML = '<b>Important task</b>';
var footer = document.getElementById('footer');
footer.className = footer.className + " green";JavaScript has an event loop. It is constantly listening for events such as 'there was a mouse click', 'the cursor hovered over this element', 'the page was scrolled', 'a key was pressed', etc. In your code, you can attach a function called an event handler to an event. So when JS detects an event, it will call the event handler function.
Let's start off by modifying our addItem() function to add text from an input.
var addItem = function() {
var text = document.getElementById('textInput').value;
var todoList = document.getElementById('todolist');
var todoElement = document.createElement('p');
var todoText = document.createTextNode(text);
todoElement.appendChild(todoText);
todoList.appendChild(todoElement);
};Now we add an event listener for the click on a button:
document.getElementById('addItem').addEventListener("click", addItem, false);For clicks, there is a shorthand:
document.getElementById('addItem').onclick(addItem);XHR stands for XMLHttpRequest. It's the way JavaScript sends HTTP requests to servers behind the scenes without reloading the web page. You can do lots of cool stuff with this like the infinite scrolling on Facebook or Reddit. Using this is usually called AJAX (Asynchronous JavaScript And XML). AJAX is asynchronous because it sends http requests behind the scenes without reloading the web page. It's always done by JavaScript. and it has literally nothing to do with XML. The XML is only there because AJAX sounds cool. Really it's usually AJAJ - Asynchronous JavaScript and JSON - becuase most of the time you'll be getting JSON back from the server. But AJAJ doesn't sound as nice as AJAX.
This is how you do XHR in pure JavaScript:
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();Screw this. Let's learn JQuery.
$(document).ready(function() {
$('#addItem').click(function(){
var newElem = '<p>' + $('#textInput').val() + '</p>';
$('#todolist').append(newElem);
$('#textInput').val('');
$('#todolist p').hover(function(){
$(this).addClass('hovering');
}, function() {
$(this).removeClass('hovering')
});
});
});- Angular/Backbone/Ember
- Require
- Underscore
- Bower, Grunt, Yeoman
