Jun 29, 2013
Jun 29, 2013
1
---
Jun 29, 2013
Jun 29, 2013
7
---
8
9
JavaScript was created by Netscape's Brendan Eich in 1995. It was originally
10
intended as a simpler scripting language for websites, complementing the use of
11
Java for more complex web applications, but its tight integration with Web pages
12
and built-in support in browsers has caused it to become far more common than
13
Java in web frontends.
Jun 29, 2013
Jun 29, 2013
14
15
JavaScript isn't just limited to web browsers, though: Node.js, a project that
16
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
17
becoming more and more popular.
18
19
JavaScript has a C-like syntax, so if you've used languages like C or Java,
20
a lot of the basic syntax will already be familiar. Despite this, and despite
21
the similarity in name, JavaScript's object model is significantly different to
22
Java's.
23
25
// Single-line comments start with two slashes.
26
/* Multiline comments start with slash-star,
Jun 29, 2013
Jun 29, 2013
27
and end with star-slash */
28
29
// Statements can be terminated by ;
30
doStuff();
31
32
// ... but they don't have to be, as semicolons are automatically inserted
33
// wherever there's a newline, except in certain cases.
34
doStuff()
35
36
// Because those cases can cause unexpected results, we'll keep on using
37
// semicolons in this guide.
Jun 29, 2013
Jun 29, 2013
38
Jun 29, 2013
Jun 29, 2013
41
Jun 29, 2013
Jun 29, 2013
47
Jun 29, 2013
Jun 29, 2013
54
Jun 29, 2013
Jun 29, 2013
57
58
// And modulo division.
59
10 % 2; // = 0
60
30 % 4; // = 2
61
18.5 % 7; // = 4.5
62
63
// Bitwise operations also work; when you perform a bitwise operation your float
64
// is converted to a signed int *up to* 32 bits.
Jun 29, 2013
Jun 29, 2013
69
Jun 29, 2013
Jun 29, 2013
75
// There's also a boolean type.
Jun 29, 2013
Jun 29, 2013
78
79
// Strings are created with ' or ".
Jun 29, 2013
Jun 29, 2013
82
83
// Negation uses the ! symbol
Jun 29, 2013
Jun 29, 2013
86
Jun 29, 2013
Jun 29, 2013
90
Jun 29, 2013
Jun 29, 2013
94
95
// More comparisons
96
1 < 10; // = true
97
1 > 10; // = false
98
2 <= 2; // = true
99
2 >= 2; // = true
Jun 29, 2013
Jun 29, 2013
100
101
// Strings are concatenated with +
Jun 29, 2013
Jun 29, 2013
103
104
// ... which works with more than just strings
105
"1, 2, " + 3; // = "1, 2, 3"
108
// ...which can result in some weird behaviour...
109
13 + !0; // 14
110
"13" + !0; // '13true'
111
Jun 29, 2013
Jun 29, 2013
112
// and are compared with < and >
Jun 29, 2013
Jun 29, 2013
114
Jun 29, 2013
Jun 29, 2013
118
Jun 29, 2013
Jun 29, 2013
122
Jun 29, 2013
Jun 29, 2013
131
132
// There's also `null` and `undefined`.
133
null; // used to indicate a deliberate non-value
134
undefined; // used to indicate a value is not currently present (although
137
// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.
Jun 29, 2013
Jun 29, 2013
139
Jun 29, 2013
Jun 29, 2013
142
143
// Variables are declared with the `var` keyword. JavaScript is dynamically
144
// typed, so you don't need to specify type. Assignment uses a single `=`
145
// character.
Jun 29, 2013
Jun 29, 2013
147
Jun 29, 2013
Jun 29, 2013
150
151
// ...but your variable will be created in the global scope, not in the scope
152
// you defined it in.
153
154
// Variables declared without being assigned to are set to undefined.
Jun 29, 2013
Jun 29, 2013
156
157
// If you want to declare a couple of variables, then you could use a comma
162
someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
163
someVar *= 10; // now someVar is 100
171
172
// Their members can be accessed using the square-brackets subscript syntax.
173
// Array indices start at zero.
176
// Arrays are mutable and of variable length.
177
myArray.push("World");
178
myArray.length; // = 4
179
183
// Add and remove element from front or back end of an array
184
myArray.unshift(3); // Add as the first element
185
someVar = myArray.shift(); // Remove first element and return it
186
myArray.push(3); // Add as the last element
187
someVar = myArray.pop(); // Remove last element and return it
188
192
193
// Get subarray of elements from index 1 (include) to 4 (exclude)
194
myArray0.slice(1,4); // = [false,"js",12]
195
197
// "hi","wr" and "ld"; return removed subarray
198
myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90]
199
// myArray0 === [32,false,"hi","wr","ld"]
201
// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
204
205
// Keys are strings, but quotes aren't required if they're a valid
206
// JavaScript identifier. Values can be any type.
211
212
// ... or using the dot syntax, provided the key is a valid identifier.
Jun 29, 2013
Jun 29, 2013
217
218
// If you try to access a value that's not yet set, you'll get undefined.
236
// An infinite loop!
237
}
238
239
// Do-while loops are like while loops, except they always run at least once.
251
// Breaking out of labeled loops is similar to Java
252
outer:
253
for (var i = 0; i < 10; i++) {
254
for (var j = 0; j < 10; j++) {
255
if (i == 5 && j ==5) {
256
break outer;
257
// breaks out of outer loop instead of only the inner one
258
}
259
}
260
}
261
269
// The for/of statement allows iteration over iterable objects (including the built-in String,
270
// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set,
271
// and user-defined iterables).
272
var myPets = "";
273
var pets = ["cat", "dog", "hamster", "hedgehog"];
274
for (var pet of pets){
275
myPets += pet + " ";
276
} // myPets = 'cat dog hamster hedgehog '
277
278
// && is logical and, || is logical or
279
if (house.size == "big" && house.colour == "blue"){
281
}
282
if (colour == "red" || colour == "blue"){
283
// colour is either red or blue
284
}
285
286
// && and || "short circuit", which is useful for setting default values.
292
grade = 'B';
293
switch (grade) {
294
case 'A':
295
console.log("Great job");
296
break;
297
case 'B':
298
console.log("OK job");
299
break;
300
case 'C':
301
console.log("You can do better");
302
break;
303
default:
304
console.log("Oy vey");
305
break;
306
}
307
308
309
///////////////////////////////////
310
// 4. Functions, Scope and Closures
318
// Note that the value to be returned must start on the same line as the
320
// automatic semicolon insertion. Watch out for this when using Allman style.
327
// JavaScript functions are first class objects, so they can be reassigned to
328
// different variable names and passed to other functions as arguments - for
329
// example, when supplying an event handler:
330
function myFunction(){
331
// this code will be called in 5 seconds' time
332
}
334
// Note: setTimeout isn't part of the JS language, but is provided by browsers
335
// and Node.js.
337
// Another function provided by browsers is setInterval
338
function myFunction(){
339
// this code will be called every 5 seconds
340
}
343
// Function objects don't even have to be declared with a name - you can write
344
// an anonymous function definition directly into the arguments of another.
345
setTimeout(function(){
348
349
// JavaScript has function scope; functions get their own scope but other blocks
350
// do not.
351
if (true){
355
356
// This has led to a common pattern of "immediately-executing anonymous
357
// functions", which prevent temporary variables from leaking into the global
358
// scope.
361
// We can access the global scope by assigning to the "global object", which
364
window.permanent = 10;
365
})();
366
temporary; // raises ReferenceError
367
permanent; // = 10
368
369
// One of JavaScript's most powerful features is closures. If a function is
370
// defined inside another function, the inner function has access to all the
374
// Inner functions are put in the local scope by default, as if they were
380
// setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
381
// exit immediately, and setTimeout will call inner afterwards. However,
382
// because inner is "closed over" sayHelloInFiveSeconds, inner still has
385
sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
387
///////////////////////////////////
388
// 5. More about Objects; Constructors and Prototypes
398
// When functions attached to an object are called, they can access the object
408
// What `this` is set to has to do with how the function is called, not where
409
// it's defined. So, our function doesn't work if it isn't called in the
410
// context of the object.
413
414
// Inversely, a function can be assigned to the object and gain access to it
419
myObj.myOtherFunc = myOtherFunc;
420
myObj.myOtherFunc(); // = "HELLO WORLD!"
422
// We can also specify a context for a function to execute in when we invoke it
428
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
429
430
// The `apply` function is nearly identical, but takes an array for an argument
431
// list.
432
433
anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
434
435
// This is useful when working with a function that accepts a sequence of
436
// arguments and you want to pass an array.
437
438
Math.min(42, 6, 27); // = 6
439
Math.min([42, 6, 27]); // = NaN (uh-oh!)
440
Math.min.apply(Math, [42, 6, 27]); // = 6
441
442
// But, `call` and `apply` are only temporary. When we want it to stick, we can
443
// use `bind`.
444
445
var boundFunc = anotherFunc.bind(myObj);
446
boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
447
454
// When you call a function with the `new` keyword, a new object is created, and
455
// made available to the function via the `this` keyword. Functions designed to be
461
myNewObj = new MyConstructor(); // = {myNumber: 5}
462
myNewObj.myNumber; // = 5
464
// Unlike most other popular object-oriented languages, JavaScript has no
465
// concept of 'instances' created from 'class' blueprints; instead, JavaScript
466
// combines instantiation and inheritance into a single concept: a 'prototype'.
467
468
// Every JavaScript object has a 'prototype'. When you go to access a property
469
// on an object that doesn't exist on the actual object, the interpreter will
470
// look at its prototype.
471
472
// Some JS implementations let you access an object's prototype on the magic
473
// property `__proto__`. While this is useful for explaining prototypes it's not
474
// part of the standard; we'll get to standard ways of using prototypes later.
475
var myObj = {
490
491
// Of course, if your property isn't on your prototype, the prototype's
492
// prototype is searched, and so on.
493
myPrototype.__proto__ = {
494
myBoolean: true
497
498
// There's no copying involved here; each object stores a reference to its
499
// prototype. This means we can alter the prototype and our changes will be
500
// reflected everywhere.
504
// The for/in statement allows iteration over properties of an object,
505
// walking up the prototype chain until it sees a null prototype.
506
for (var x in myObj){
507
console.log(myObj[x]);
508
}
509
///prints:
510
// Hello world!
514
515
// To only consider properties attached to the object itself
516
// and not its prototypes, use the `hasOwnProperty()` check.
517
for (var x in myObj){
518
if (myObj.hasOwnProperty(x)){
519
console.log(myObj[x]);
520
}
521
}
522
///prints:
523
// Hello world!
524
525
// We mentioned that `__proto__` was non-standard, and there's no standard way to
526
// change the prototype of an existing object. However, there are two ways to
529
// The first is Object.create, which is a recent addition to JS, and therefore
530
// not available in all implementations yet.
534
// The second way, which works anywhere, has to do with constructors.
535
// Constructors have a property called prototype. This is *not* the prototype of
536
// the constructor function itself; instead, it's the prototype that new objects
537
// are given when they're created with that constructor and the new keyword.
548
549
// Built-in types like strings and numbers also have constructors that create
550
// equivalent wrapper objects.
551
var myNumber = 12;
552
var myNumberObj = new Number(12);
553
myNumber == myNumberObj; // = true
562
if (new Number(0)){
563
// This code will execute, because wrapped numbers are objects, and objects
564
// are always truthy.
565
}
567
// However, the wrapper objects and the regular builtins share a prototype, so
568
// you can actually add functionality to a string, for instance.
574
// This fact is often used in "polyfilling", which is implementing newer
575
// features of JavaScript in an older subset of JavaScript, so that they can be
576
// used in older environments such as outdated browsers.
577
578
// For instance, we mentioned that Object.create isn't yet available in all
579
// implementations, but we can still use it with this polyfill:
580
if (Object.create === undefined){ // don't overwrite it if it exists
581
Object.create = function(proto){
582
// make a temporary constructor with the right prototype
589
590
// ES6 Additions
591
592
// The "let" keyword allows you to define variables in a lexical scope,
594
let name = "Billy";
595
596
// Variables defined with let can be reassigned new values.
597
name = "William";
598
599
// The "const" keyword allows you to define a variable in a lexical scope
600
// like with let, but you cannot reassign the value once one has been assigned.
601
602
const pi = 3.14;
603
604
pi = 4.13; // You cannot do this.
605
606
// There is a new syntax for functions in ES6 known as "lambda syntax".
607
// This allows functions to be defined in a lexical scope like with variables
608
// defined by const and let.
609
610
const isEven = (number) => {
611
return number % 2 === 0;
612
};
613
614
isEven(7); // false
615
616
// The "equivalent" of this function in the traditional syntax would look like this:
617
618
function isEven(number) {
619
return number % 2 === 0;
620
};
621
622
// I put the word "equivalent" in double quotes because a function defined
624
// The following is an example of invalid usage:
625
626
add(1, 8);
627
628
const add = (firstNumber, secondNumber) => {
629
return firstNumber + secondNumber;
630
};
Jun 29, 2013
Jun 29, 2013
631
```
635
The [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) (MDN) provides excellent documentation for
636
JavaScript as it's used in browsers.
638
MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) covers much of the concepts covered
639
here in more detail. This guide has quite deliberately only covered the
640
JavaScript language itself; if you want to learn more about how to use
641
JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core).
643
[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts
646
[JavaScript: The Definitive Guide](https://www.amazon.com/gp/product/0596805527/) is a classic guide and reference book.
648
[Eloquent JavaScript](https://eloquentjavascript.net/) by Marijn Haverbeke is an excellent JS book/ebook with
651
[javascript.info](https://javascript.info/) is a modern JavaScript tutorial covering the basics (core language and working with a browser)