Guy Royse, Consultant
Pillar Technology
groyse@pillartechnology.com
@guyroyse

Clean Code
TDD
JavaScript
People

Crufty Co...
Source: http://xkcd.com/101/
Show
JavaScript
Problem

Someone
Tries to
Solve It
YES

Are They
Correct?

Dispense
Candy

Anymore
Problems?

NO

NO

Try ...
Rule #1
The first person
to answer correctly
wins
a candy bar.
Rule #2
You may not win more
than one candy bar.
So let others play the
game too.
Rule #3
If you break Rule #2,
I will give the candy bar
to the skinniest person
in the room.
Rule #4
If you break Rule #2
and are the skinniest
person in the room, I
will eat the candy bar.
Rule #5
In the event of any rules
dispute it is important
to remember,
I am always right.
Problem #1
varechoEchoEcho = function(value) {
varreturnValue = echoEchoEcho.lastValue;
echoEchoEcho.lastValue = value;
re...
{}
new String('foo')
new Number(42)
new Boolean(true)
function()

'foo'
42
true and false
['foo', 42, false]
{}
var foo = new Object();
{}
var foo = {};
{}
var foo = {
bool : true,
num : 42,
text : 'some text',
func : function() { return 2 + 2 },
obj : { foo : 1, bar : 2 }
}...
{}
var foo = { value : 42 };
foo.value = 23;
foo.otherValue = true;
delete foo.value;

// update
// create
// delete
{}
varfoo = { value : 42 };
varx = foo.value;
vary = foo['value'];

varval = 'value';
varz = foo[val];
{}
[]
Problem #2
var Policy = function() {
this.premium = 600;
this.term = 6;
this.calculateMonthlyAmount = function() {
return ...
var balance = 200.00;
var Account = function(acctBalance) {
this.balance = acctBalance;
this.deposit = function(amount) {
...
{}
var Policy = function(policyNumber) {
this.policyNumber = policyNumber;
this.compressPolicyNumber = function() {
return...
{}
var createPolicy = function(policyNumber) {
this = {};
this.policyNumber = policyNumber;
this.compressPolicyNumber = fu...
{}
var Foo = function() {
if (!this instanceof Foo) {
return new Foo();
}
this.bar = 42;
this.baz = 'Hello, World!'
};
Problem #3
var principal = 5000;
var calculate = function() {
return this.principal * 0.10;
};
var account = { principal :...
{}
function echo(value) {
return value;
}
{}
var echo = function(value) {
return value;
};
{}
var echo = function(value) {
return value;
};
var repeat = echo;
()
{}
var echo = function(value) {
return value;
};
echo('Hola, mundo!');
{}
var object = {
echo: function(value) { return value; }
};
object['echo']('Hola, mundo!');

var array = [object.echo];
a...
{}
var value = (function(value) {
return value;
})('Hello, World!');
Problem #4
varfoo = function() {
foo = function() {
return 'Polo!';
};
return 'Marco!';
};
var results = [];
results.push(...
{}
var foo = function() {
foo = function() { return 'Polo!'; };
return 'Marco!';
};

var bar = foo;
bar();
{}
var foo = [1,2,3];
var bar = [];
foo.forEach(function(item) {
bar.push(item * 10);
});
// bar == [10, 20, 30]
{}
[].forEach(fn)
[].filter(fn)
[].every(fn)

[].some(fn)
[].sort(fn)

iterates every item
creates new array of items
wher...
Problem #5
varfoo = (function() {
var count = 0;
var values = ['foo', 'bar', 'baz', 'qux'];
return function() {
count++;
r...
{}
varcreatePolicy = function(number) {
varpolicyNumber = number;
return {
getPolicyNumber: function() {
return policyNumb...
{}
var policy = (function() {
var policyNumber = '1234567890';
return {
getPolicyNumber: function() {
return policyNumber;...
{}
JavaScript: The Good Parts
Douglas Crockford

JavaScript Patterns
Stoyan Stefanov
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
So You Think You Know JavaScript
Upcoming SlideShare
Loading in …5
×

So You Think You Know JavaScript

620 views

Published on

Many folks think they know JavaScript. They know the syntax and can manipulate the DOM. Maybe they have even used jQuery. But do they really know it? I thought I did until I started digging and discovered that JavaScript is more than just a toy language for web pages. It's a full-fledged functional programming language chock full of richness. In this session, targeted at beginners, you will be introduced to some of this richness in an exciting game show format -- complete with prizes. You will learn about functions, objects,
closures, and revealing modules. And you'll leave a more informed JavaScript programmer (unless, of course, you already knew JavaScript in which case you'll just leave with a prize).

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
620
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Caveats - you’re going to learn some JavaScript stuff here - showing some of the cool features and misfeatures of JavaScript - not about what you should or shouldn't do -- for that you need to use your brain and maybe read some books for some guidance - not about HTML and the DOM
  • I Thought I Knew JavaScript could write function knew the syntax manipulate the DOM even use jQuery and prototypeBut I was wrong. There is a lot more going on. I had barely scratched the surface. In this session we are going to do more than scratch the surface.Talk will be about advance method invocations, objects and classes, closures, and prototypes if we have time.Discovered some cool stuff in learning JavaScript and today I’m going to share it in…..
  • Caveats - you’re going to learn some JavaScript stuff here - showing some of the cool features and misfeatures of JavaScript - not about what you should or shouldn't do -- for that you need to use your brain and maybe read some books for some guidance - not about HTML and the DOM
  • How it works - I present some sample code with multiple outcomes - you select the correct answer - I give out prizes
  • Everything is an object - even arrays, functions, numbers, strings, booleans
  • Defining an object - new Object();
  • Defining an object - this is overkill, probably easier to just do this.
  • Defining an object - and adding a few properties is easy from here – this is called an object literal or the module pattern
  • Add, update, remove
  • Accessing an object - simple dot notation - array notation - “reflection”
  • Objects are not arrays – arrays are objects
  • Why did this fail? - we didn't use the new operator - this is a really easy mistake to make - but the error wasn't in the penultimate line, it was in the last line - Policy is just a function - but what happened to what we assigned to this?
  • The default value for this is the global namespace (i.e. everywhere) - if you are in a browser this is window
  • This could be really bad for either the bank, or the customerThis is a common mistake and easy to make and it occurs because classes are really just a fiction in JavaScript.
  • What we really have is a specialized constructor function
  • By convention always capitalize class names - this is just code, nothing special – anything could go in here - this is defined as the object instance that was created
  • - this is what is really happening - there is actually a bit more happening here involving prototypes but we'll not get into that today
  • Function calls are easy to define - function keyword
  • Function calls are easy to define- assigning it to a variable - a bit more honest -- because they are easy to reassign
  • Function calls are easy to define - because they are easy to reassign
  • This is the key to invoking functions
  • Function calls are easy - just use () at the end of a variable
  • Function calls are easy - you can call functions on an object or in an array this way too
  • You can even call them on the fly using immediately executing functions
  • These are cool, but they can not work as expected so be careful
  • This code illustrates the problem – calling bar will always return 'Marco!'
  • Functions can be passed as arguments - create for using the strategy pattern
  • Functions can be passed as arguments - create for using the strategy pattern
  • A closure is a bit of code and variables that should otherwise be out of scope
  • Closures are great for private variables in JavaScript - policy number is now read only and not modifiable for this object
  • AKA the revealing module patternCombining closures and immediately invoked functions makes for wicked cool singletons - why, then we don't need a function to construct the object - this keeps the global namespace clean - and keeps others from calling code you don't intend to be called - it's the same as a protected constructor in Java
  • Functions can be passed as arguments - create for using the strategy pattern
  • So You Think You Know JavaScript

    1. 1. Guy Royse, Consultant Pillar Technology groyse@pillartechnology.com @guyroyse Clean Code TDD JavaScript People Crufty Code Working Alone COBOL Mean People
    2. 2. Source: http://xkcd.com/101/
    3. 3. Show JavaScript Problem Someone Tries to Solve It YES Are They Correct? Dispense Candy Anymore Problems? NO NO Try Again YES Game Over
    4. 4. Rule #1 The first person to answer correctly wins a candy bar.
    5. 5. Rule #2 You may not win more than one candy bar. So let others play the game too.
    6. 6. Rule #3 If you break Rule #2, I will give the candy bar to the skinniest person in the room.
    7. 7. Rule #4 If you break Rule #2 and are the skinniest person in the room, I will eat the candy bar.
    8. 8. Rule #5 In the event of any rules dispute it is important to remember, I am always right.
    9. 9. Problem #1 varechoEchoEcho = function(value) { varreturnValue = echoEchoEcho.lastValue; echoEchoEcho.lastValue = value; return returnValue; } var results = []; results.push(echoEchoEcho('foo')); results.push(echoEchoEcho('bar')); results.push(echoEchoEcho('baz')); a) b) c) d) undefined -- the code will throw an exception [undefined, 'foo', 'bar'] ['foo', 'bar', 'baz'] [null, 'foo', 'bar‘]
    10. 10. {} new String('foo') new Number(42) new Boolean(true) function() 'foo' 42 true and false ['foo', 42, false]
    11. 11. {} var foo = new Object();
    12. 12. {} var foo = {};
    13. 13. {} var foo = { bool : true, num : 42, text : 'some text', func : function() { return 2 + 2 }, obj : { foo : 1, bar : 2 } };
    14. 14. {} var foo = { value : 42 }; foo.value = 23; foo.otherValue = true; delete foo.value; // update // create // delete
    15. 15. {} varfoo = { value : 42 }; varx = foo.value; vary = foo['value']; varval = 'value'; varz = foo[val];
    16. 16. {} []
    17. 17. Problem #2 var Policy = function() { this.premium = 600; this.term = 6; this.calculateMonthlyAmount = function() { return this.premium / this.term; }; }; varmyPolicy = Policy(); varmyMonthlyAmount = myPolicy.calculateMonthlyAmount(); a) b) c) d) undefined -- the code will throw an exception null 100 600
    18. 18. var balance = 200.00; var Account = function(acctBalance) { this.balance = acctBalance; this.deposit = function(amount) { this.balance += amount; } }; var myAcct = Account(500.00); var myAcct = Account(0.0);
    19. 19. {} var Policy = function(policyNumber) { this.policyNumber = policyNumber; this.compressPolicyNumber = function() { return this.policyNumber.replace(' ', ''); }; }; var policy = new Policy();
    20. 20. {} var createPolicy = function(policyNumber) { this = {}; this.policyNumber = policyNumber; this.compressPolicyNumber = function() { return this.policyNumber.replace(' ', ''); }; return this; };
    21. 21. {} var Foo = function() { if (!this instanceof Foo) { return new Foo(); } this.bar = 42; this.baz = 'Hello, World!' };
    22. 22. Problem #3 var principal = 5000; var calculate = function() { return this.principal * 0.10; }; var account = { principal : 1000, interest : calculate }; var loan = { principal : 2000, charge : calculate }; var amount = account.interest() + loan.charge(); a) b) c) d) undefined -- the code will throw an exception 100 500 300
    23. 23. {} function echo(value) { return value; }
    24. 24. {} var echo = function(value) { return value; };
    25. 25. {} var echo = function(value) { return value; }; var repeat = echo;
    26. 26. ()
    27. 27. {} var echo = function(value) { return value; }; echo('Hola, mundo!');
    28. 28. {} var object = { echo: function(value) { return value; } }; object['echo']('Hola, mundo!'); var array = [object.echo]; array[0]('Hola, mundo!');
    29. 29. {} var value = (function(value) { return value; })('Hello, World!');
    30. 30. Problem #4 varfoo = function() { foo = function() { return 'Polo!'; }; return 'Marco!'; }; var results = []; results.push(foo()); results.push(foo()); results.push(foo()); a) b) c) d) undefined -- the code will throw an exception ['Marco!', 'Polo!', 'Polo!'] ['Marco!', 'Polo!', 'Marco!] ['Polo!', 'Marco!', 'Polo!]
    31. 31. {} var foo = function() { foo = function() { return 'Polo!'; }; return 'Marco!'; }; var bar = foo; bar();
    32. 32. {} var foo = [1,2,3]; var bar = []; foo.forEach(function(item) { bar.push(item * 10); }); // bar == [10, 20, 30]
    33. 33. {} [].forEach(fn) [].filter(fn) [].every(fn) [].some(fn) [].sort(fn) iterates every item creates new array of items where true is returned iterates items until false is returned iterates items until true is returned comparator function
    34. 34. Problem #5 varfoo = (function() { var count = 0; var values = ['foo', 'bar', 'baz', 'qux']; return function() { count++; return values[count]; }; })(); var results = [foo(), foo(), foo()]; a) b) c) d) undefined -- the code will throw an exception ['foo','bar','baz'] ['bar','baz','qux'] ['qux','baz','bar']
    35. 35. {} varcreatePolicy = function(number) { varpolicyNumber = number; return { getPolicyNumber: function() { return policyNumber; } }; };
    36. 36. {} var policy = (function() { var policyNumber = '1234567890'; return { getPolicyNumber: function() { return policyNumber; } }; })();
    37. 37. {} JavaScript: The Good Parts Douglas Crockford JavaScript Patterns Stoyan Stefanov

    ×