Javascript
fundamentals
About the speaker
var Terrance = function() {
var me = [
"Daddy",//Daddy First
"Professional Web Dev",
"Web Enthusiest",
"FANBOY",
"musicm122.blogspot.com"
];
return me;
};
Outline
-
Why oh why Javascript?
-
History
-
Language Basics
-
Objects
- Functions
- Structuring Javascript
- Pitfalls and Pain points
- Shinny things
- The MOAR You KNOW
Why oh why Javascript (seriously)
-
Javascript is Ubiquitous
write once...... -
The direction the world is moving
-
Javascript a Highly Expressive Language
(believe it or not) -
Because Javascript loves you and wants to be your friend.
(no, really)
Quotes by Semi Famous people
Atwood's Law: any application that can be written in JavaScript, will eventually be written in JavaScript
Jeff Atwood
Javascript is the Assembly language for the web.
Scott Hanselman
Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C's clothing. This makes JavaScript a remarkably powerful language.
Douglas Crockford: JavaScript: The Good Parts
A little History
- Written at Mosaic by Brendan Eich under the name Mocha and later LiveScript, EMCAScript, and JScript
-
Influenced heavily by java, self and scheme
-
Currently Trademaked by Oracle:"JavaScript" is a trademark of
Oracle Corporation. It is used under license for technology invented and
implemented by Netscape Communications and current entities such as the
Mozilla Foundation
- EMCA standard 262
Language Basics
Hello World
Looping Constructs
//for loop
for (var i = 0; i < myArr.length; i++) { console.log("for loop item " + myArr[i]); } //for in loop, used for enumerating properties for (var item in person) { console.log("for in loop item = " + item); } //while loop while (i < 5) { i++; if (i == 3) continue; n += i; } //do while do { i += 1; console.log("do while loop item = " + i); } while (i < 5);
Objects
Objects
var dog = {}; // 1
var cat = Object.create(null); // 2
var mongoose = new Object(); // 3
var dog = { bark:alert("WOOF!"),//method color:"black", //string age:3 //integer };
dog.bark(); //accessing an objects method
alert(dog.age); // accessing an object's property
alert(dog["age"]); //also accessing an object's property
Objects
Key Value Pairs (Think built in hash table or dictionary)
var dog = {
bark:alert("WOOF!"),
color:"black",
age:3
};
The property color can be referenced in two ways.
alert(dog.color);
alert(dog["color"]);
Objects
JSON (Javascript Object Notation)
In JSON
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
In XML
<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
Objects
Differences between JSON and Javascript Objects
The keys must be strings (i.e. enclosed in double quotes ") in JSON. The values can be :
-
string
-
number
-
JSON object
-
array
-
true
-
false
- null
Objects
function myfunction(x){
// x is equal to 4 x = 5; // x is now equal to 5
}
var x = 4; alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4
function alterObject(obj) { obj.foo = "hello world"; } var myObj = { foo: "goodbye" };
alterObject(myObj);
alert(myObj.foo); // "hello world" instead of "goodbye"
Objects
var defaults = {
zero: 0,
one: 1
};
var myOptions = Object.create(defaults);
var yourOptions = Object.create(defaults);
// When I want to change *just* my options
myOptions.zero = 1000;
// When you wanna change yours
yourOptions.one = 42;
// When we wanna change the **defaults** even after we've got our options
// even **AFTER** we've already created our instances
defaults.two = 2;
myOptions.two; // 2
yourOptions.two; // 2
Objects
//usage: var str = " somestring ".trim();
//output: "somestring"
//Credits to http://blog.stevenlevithan.com/archives/faster-trim-javascript
String.prototype.trim = function () {
return this.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
};
Functions
Functions
//function declaration ||the function statement
function add(a,b){
return a + b;
}
//The function expression (function operator)
//Function Literal
var add = function (a, b) {
return a + b;
};
//The Function constructor
var add = new function(a, b){
return a+b;
}
Functions
About the "New" operator
- Creates an empty object
- Sets the internal [[prototype]] property equal to the external prototype of the newly instantiated object.
- Calls the constructor function the type with a context of the newly created object (in other words the 'this' points to the new object)
Functions
Examples
In order to understand recursion, one must first understand recursion.
Lather, Rinse, Repeat
function fib(n){ return n<2?n:fib(n-1)+fib(n-2); } console.info(fib(20));
Functions
one more......
Functions
- Can be Passed as arguments
- Can be Returned as values
- Can be Assigned to a variable or stored in data structures.
- Can be Nested
- Can be Anonymous (lambda expression)
Where there are first class functions there are....
Functions
A closure is any function which closes over the environment in which it
was defined. This means that it can access variables not in its
parameter list.
//foo "encloses bar" hense the name "closure"
function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp));
}
bar(10);
}
foo(2);
Structuring Javascript
(Design Patterns)
Pitfalls and Pain Points
- Global Scope by default
- No concept of Namespace (require.js)
- The Search for 'Truthy'ness (use '===' not '==')
-
Variable Hoisting (single var && strict mode )
- 'this' scoping or "execution Context" (the calling func gets the 'this')
- Raw ajax (use jQuery or another ajax lib)
Pitfalls and Pain Points
- Arrays ('Poor performance and memory consumption')
- New Semantics can cause confusion
- Prototypes Semantics can cause confusion('Design Patterns')
- eval (just don't use it)
- auto semicolon insertion ( use K&R Brace Style)
- DOM incompatibility issues artifacts of the "Browser Wars" (use jquery)
Additional Resources
(TEH MOAR U KNOW!!!)
QA & Help
Free books
No so free books but still worthwhile
continued...
People
Javascript Koans
(bonus round)
open up a terminal and type the following:
git clone https://github.com/mrdavidlaing/javascript-koans
Then go to the directory where the repo you made is located
open up KoansRunner.html
Have fun ;)
A Prize for the furthest along
javascript fundamentals
By Terrance Smith
javascript fundamentals
- 3,513