On Github mshalaby / introduction-to-javascript
by Mohammed Shalaby
A dynamic object-oriented general-purpose programming language
Standard of the core language of JavaScript
Also used in non-browser environments e.g. node.js
Provides:
Versions of ECMA-262:
// one line comment /* Multi-line comment */
Declared using var
var x = 2; // x is declared and initialized var y; // y is only declared (value is undefined) function test() { var z = 3; k = 5; // missing var } // x, y & k are global variables // z is a local variable
Declared using var
var x = 1; { var x = 2; } console.log(x); // outputs 2
if (x == 'yes') { doSomething(); } else { doSomethingElse(); } if (x == 'yes') { doSomething(); } else if (x == 'no') { doSomethingElse(); }
for (var x = 0; x < 10; x++) { doSomething(x); } while (x < 10) { doSomething(x); x++; }
Only one number type
100, 100.0, 1e2 are equivalent
64-bit floating point (same as Java's double)
0.1 + 0.2 // 0.30000000000000004
Special Number
typeof NaN // "number"
Result of erroneous operations
2 * 'a' // NaN
Toxic
5 + NaN // NaN
Not equal to any value (including itself)
NaN == NaN // false isNaN(NaN) // true
Special Number
1 / 0 // Infinity 1 / Infinity // 0 -1 / 0 // -Infinity
Represents numbers > 1.79769313486231580e+308
1.8e308 // Infinity
You can use it to check for Infinity, -Infinity & NaN
isFinite(NaN) // false isFinite(Infinity) // false isFinite(-Infinity) // false isFinite(1.7e+308) // true
Converts a value into a number
Number('') // 0 Number('0032') // 32 Number('123abc') // NaN Number('abc') // NaN
So does the '+' prefix operator
+'' // 0 +'0032' // 32 +'123abc' // NaN +'abc' // NaN
Also converts a value into a number
parseInt('123', 10) // 123
Stops at first non-digit character
parseInt('123abc', 10) // 123
If no radix is passed it defaults to 10
parseInt('32') // 32 (as decimal)
Always specify the radix
parseInt('0032', 10) // 32 parseInt('0032', 8) // 26 parseInt('11', 2) // 3
An object containing methods that act on numbers
abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tanMath.floor(12.53) // 12
Also contains some useful constants
E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2Math.PI // 3.141592653589793
0 or more 16-bit characters
A character is just a String of length 1
Immutable
number of 16-bit characters
'abc'.length // 3
'abc' == "abc" // true
'Java' + 'Script' // 'JavaScript'
Converts a value into a string
String(123) // '123'
Another way
'' + 123 // '123'
some examples
'cat'.toUpperCase() // 'CAT' 'bat'.charAt(1) // 'a' 'hello'.replace(/llo/, 'y') // 'hey' 'Alexandria'.indexOf('x') // 3 'banana'.lastIndexOf('n') // 4 'world wide web'.match(/(w\w*)/g) // ["world", "wide", "web"]
true - false
Converts a value into a boolean
Boolean(value) // true or false
!! value // true or false
6 possible falsy values
!! false // false !! null // false !! undefined // false !! '' // false !! 0 // false !! NaN // false
All other values are truthy
!! '0' // true
A deliberate non-value
var a = null; typeof a; // 'object'
An uninitialized value
var a; typeof a; // 'undefined'
An object is a container of properties
A built in function for creating objects
var object = new Object();
Very convenient for creating new objects
var object = {};
var person = { 'first-name': 'John' };
var city = { name: 'Alexandria', location: { latitude: 31.2, longitude: 29.9 } };
Passed around by reference
var a = b = c = {}; // the same empty object
var a = {}, b = {}, c = {}; // different empty objects
person['first-name'] // 'John' person['last-name'] = 'Smith'; person.age = 28;
Missing properties
person.nickname // undefined
removes properties
var person = { name: 'John', age: 20 }; delete person.age; person.age // undefined
Every object is linked to a prototype object
Provides inheritance
Protypes hold common functionality & data
Specifying a prototype
var p = {foo: 'bar'}; var a = Object.create(p); var b = Object.create(p); a.foo // 'bar' b.foo // 'bar'
Another way
function A (){ } A.prototype = {foo: 'bar'}; var a = new A(); var b = new A(); a.foo // 'bar' b.foo // 'bar'
Masking a prototype property
a.foo = 'blah'; // Added foo property to a a.foo // 'blah' b.foo // 'bar'
The best thing in JavaScript
Functions are objects
A function has a prototype property
Code reuse, Information hiding
4 parts:
function add (a, b) { return a + b; }; add(1, 2) // 3
When stored as a property of an object
var counter = { value: 0, increment: function (inc) { this.value += inc; } }; counter.increment(2); counter.increment(1); counter.value; // 3
Invoked with new prefix
New object linked to function's prototype property
function Car (speed) { this.speed = speed; }; Car.prototype.move = function() { return 'moving at ' + this.speed; }; var my_car = new Car('40 k/h'); var racing_car = new Car('200 k/h'); my_car.move(); // moving at 40 k/h racing_car.move(); // moving at 200 k/h
apply is a method of functions
2 parameters: value for this & array of arguments
var counter = { value: 1 }; function increment (inc) { this.value += inc; } increment.apply(counter, [3]); counter.value // 4
array-like object holding passed parameters
function sum () { var i, s = 0; for (i = 0; i < arguments.length; i += 1) { s += arguments[i]; } return s; }; sum(4, 8, 15, 16, 23, 42) // 108
No block scope
Only function scope
function foo () { var x = 1; var bar = function () { var x = 2 console.log(x); // 2 }; bar(); console.log(x) // 1 };
Inner functions have access to outer function's parameters and variables.
function incrementMaker(val) { var step = 2; return function (){ val += step; return val; }; } var increment = incrementMaker(3); increment(); // 5 increment(); // 7
Array-like objects
No linear allocated memory or computed offest access
var a = []; var misc = [ 'string', 98.6, true, null, undefined, ['nested', 'array'], {x: 1} ];
length property is not upper bound
var a = []; a.length // 0 a[10] = 1; a.length // 11 a[4] // undefined
var a = [0, 4, 9]; a.toString() a.toLocaleString() a.concat(item [,itemN]) // Returns a new array with added items a.join(sep) // Joins array elements into a string a.pop() // Removes and returns the last item a.push(item [,itemN]) // Adds one or more items to the end a.reverse() // [9, 4, 0] a.shift() // Removes and returns the first item a.slice(start, end) // Returns a sub-array a.sort([cmpfn]) // Takes an optional comparison function a.splice(start, delcount[, itemN]) // modify by replacing a section a.unshift([item]) // Add one item to the start
Provides structure & semantic content
<p>This is a paragraph</p> <ul> <li>item</li> <li>another item</li> </ul>
Provides style
<style> li.selected { background: yellow; } </style> ... <p>This is a paragraph</p> <ul> <li class="selected">item</li> <li>another item</li> </ul>
Provides interactivity
<style> li.selected { background: yellow; } </style> <script> function clickHandler(event) { event.target.classList.add('selected'); } </script> ... <p>This is a paragraph</p> <ul onclick="clickHandler(event)"> <li>item</li> <li>another item</li> </ul>
Script element with code inside
<script> alert('Hello'); </script>
Store source code in a separate file e.g. 'scripts.js'
alert('Hello');
Script element with src attribute
Browser issues a request for it
<script src="script.js"></script>
Set the src attribute to the URL for the external file
Browser issues a request for it
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
preceded by "javascript:"
javascript:alert('hello')
code also preceded by "javascript:"
<a href="javascript:alert('hello');">click me</a>
<input type="button" onclick="alert('hello');" value="Click Me" />
Provided by the browser to represent the tree of HTML nodes
html
<p id="my-element">Text here</p>
script
var p = document.getElementById('my-element'); p.innerHTML // "Text here"
html
<div> <p>One</p> <p>Two</p> </div> <p>Three</p>
script
var paragraphs = document.getElementsByTagName('p'); // returns an array paragraphs[1].innerHTML // Two
html
<div id="container" > </div>
script
var container = document.getElementById('container'); var p = document.createElement('p'); p.innerHTML = "Some text" container.appendChild(p);
html
<div id="container" > <p>Some text</p> </div>
Allows creating multiple / nested elements
html
<div id="container" > </div>
script
var container = document.getElementById('container'); container.innerHTML = '<p>One</p><p>Two<span>!</span></p>';
html
<div id="container" > <p>One</p> <p>Two<span>!</span></p> </div>
script
window.onload = function () { alert('ready'); };
html
<div id="container" > <p>One</p> </div>
script
var container = document.getElementById('container'); container.onclick = function (event) { alert(event.target.tagName); };
alerts 'p' on clicking the p element
html
<div> <input id="my-input" type="text" /> </div>
script
var inputElement = document.getElementById('my-input'); container.onkeyup = function (event) { alert(event.keyCode); };
alerts 13 on pressing the Enter key
use addEventListener
html
<div id="container" > <p>One</p> </div>
script
var container = document.getElementById('container'); container.addEventListener('click', function (event) { alert(event.target.tagName); }, true);
alerts 'p' on clicking the p element
html
<div id="container" > <p>One</p> </div>
script
var container = document.getElementById('container'); var p = container.firstChild; container.removeChild(p);
html
<div id="container" > </div>
Never mind this function... for now :)
function request(url, callback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { if (callback) { callback(this.responseText) } } } xmlhttp.open("GET",url ,true); xmlhttp.send(); }
It wraps the complexity of talking to the server for you.
And allows you to just use this simple call
request('items.json', function(responseText){ // Do somthing with the response text console.log(JSON.parse(responseText)); });
Document Object Model (DOM) | MDN
A re-introduction to JavaScript (JS Tutorial) - JavaScript | MDN