So You Think You Know JavaScript
Upcoming SlideShare
Loading in...5
×
 

So You Think You Know JavaScript

on

  • 240 views

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 ...

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).

Statistics

Views

Total Views
240
Views on SlideShare
240
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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 So You Think You Know JavaScript Presentation Transcript

  • Guy Royse, Consultant Pillar Technology groyse@pillartechnology.com @guyroyse Clean Code TDD JavaScript People Crufty Code Working Alone COBOL Mean People
  • Source: http://xkcd.com/101/
  • Show JavaScript Problem Someone Tries to Solve It YES Are They Correct? Dispense Candy Anymore Problems? NO NO Try Again YES Game Over
  • 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; 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‘]
  • {} 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 this.premium / this.term; }; }; varmyPolicy = Policy(); varmyMonthlyAmount = myPolicy.calculateMonthlyAmount(); a) b) c) d) undefined -- the code will throw an exception null 100 600
  • 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);
  • {} var Policy = function(policyNumber) { this.policyNumber = policyNumber; this.compressPolicyNumber = function() { return this.policyNumber.replace(' ', ''); }; }; var policy = new Policy();
  • {} var createPolicy = function(policyNumber) { this = {}; this.policyNumber = policyNumber; this.compressPolicyNumber = function() { return this.policyNumber.replace(' ', ''); }; return this; };
  • {} 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 : 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
  • {} 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]; array[0]('Hola, mundo!');
  • {} var value = (function(value) { return value; })('Hello, World!');
  • 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!]
  • {} 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 where true is returned iterates items until false is returned iterates items until true is returned comparator function
  • 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']
  • {} varcreatePolicy = function(number) { varpolicyNumber = number; return { getPolicyNumber: function() { return policyNumber; } }; };
  • {} var policy = (function() { var policyNumber = '1234567890'; return { getPolicyNumber: function() { return policyNumber; } }; })();
  • {} JavaScript: The Good Parts Douglas Crockford JavaScript Patterns Stoyan Stefanov