Loading presentation...

Present Remotely

Send the link below via email or IM


Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.


I Didn't Know I Could Do That With JavaScript!!!

New to JavaScript? Only use JavaScript with frameworks like jQuery? Want to know about some of the power and interesting behavior that JavaScript provides? Well, then, this is for you.

David Hoerster

on 29 April 2015

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of I Didn't Know I Could Do That With JavaScript!!!

I didn't know it could do that! Journey into JavaScript "JavaScript isn't typed"
"Everything's a string"

JavaScript has types, and you can convert to types

I Didn't Know JavaScript Could Do That!!! Do More with Operators
and Types Only 3 types
- Boolean
- String
- Number (float) Types in JavaScript Some special reserved "types"
- null
- undefined
- NaN / Infinity

That's about it!

Small set of types to work with
Simple to understand, but sometimes can cause confusion More than just types True/False or Truthy/Falsy?
Boolean values are either true or false
All other objects evaluate to some implicit boolean value
"truthy or falsy" Equality Tests Assignment and Conversion This talk is to introduce some lesser-known or understood concepts of JavaScript
Geared towards developers new to JavaScript or primarily been users of frameworks

According to Douglas Crockford, JavaScript is one of the world's most popular and misunderstood programming languages The Necessary Bits "I love developing for the web, but I try to avoid JavaScript" Some Quotes "JavaScript is just an ugly language that doesn't give you much" "It's useful for validation" "jQuery is awesome because it hides JavaScript from me" C# MVP (April 2011)
Co-Founder of BrainCredits (braincredits.com)
President of Pittsburgh .NET Users Group
Twitter - @DavidHoerster
Blog – http://geekswithblogs.net/DavidHoerster
Email – david@braincredits.com About Me Object based? What is JavaScript? Functional? Procedural? Prototypal? Type-Safe? Dynamic? me - circa 2007 We'll explore some features of JavaScript
Build on each of them
Start simple, but work up to some object-based constructs
Show how we can start building our JavaScript objects with namespaces, private members, constructors, etc.
Soon, your JavaScript experience begins to resemble OO

Let the fun begin with some talk about Operators and Types!! Roadmap var myBool = true;
var myStr = "hello",
myOtherStr = myBool.toString();
var myNum = 3;

alert(typeof myBool); //"boolean"
alert(typeof myStr); //"string"
alert(typeof myNum); //"number" Implicitly typed What happens here? alert(typeof null);
alert(typeof undefined);
alert(typeof NaN); Everything is "truthy", except...
"" (empty string)
NaN so What's Truthy and Falsy? These evaluate to "truthy" alert(0==false);
alert(1==true); What about? alert(undefined==false);
alert(undefined==null); Do I always want this to be true? Can I Check Type and Value in
Equality Checks? alert(3 == "3"); //true Double equals converts to common type and
checks value
Should 3 equal "3"?
Also, there's a little extra work to convert type Triple equals (=== and !==) checks both type and value
3 does not equal "3"
Little more efficient
But makes you think about your code and values being set more alert(3 === "3"); //false Can I Check Type and Value in
Equality Checks? Can I Check Type and Value in
Equality Checks? Triple Equals Operators (=== and !==) do
both a type and value check
3 does not equal "3"
Little more efficient
Makes you think about values in your
code more alert(3 === "3"); //false I can convert a value to a different type in JavaScript?
I didn't know it could do that! Convert to Number (+) Convert to Boolean (!!) var x = "3";
var y = +x; //number 3
alert(y === 3); //true var num = 0;
var b = !!0; //false
alert(b === false); //true Of course, converting to a string is easy -- toString() So we can convert variables to different types
What else can we do to make sure I assign properly? Assignment and Conversion Default Assignment (||) Assigns a default value to a variable if primary is falsy!
false, 0, undefined, null or empty string var agileWays = x || 100; //var gets value of x if not falsy...100 otherwise Guard Assignment (&&) If the first value is falsy, returns it; otherwise returns the second
Usually used as a null check var agileDave = agileWays && agileWays.Owner; // var gets Owner property if
// agileWays is not falsy It IS a typed language
You CAN convert between types
I CAN check type and value equality
I HAVE shortcuts to determine whether objects have value or not

OK, what's next? What Can JavaScript Do For Us So Far? Let's take a look at Objects and Functions What This Talk Is Not This talk is to explore some features of JavaScript that many developers are not aware of
We're not...
going to explore cool ways to manipulate the DOM
dig into frameworks like jQuery, knockout, ember, etc.
have super complex examples
Use simple examples that illustrate concepts and you can build on them What is an object in JavaScript?
Mostly everything that isn't a primitive (number, boolean, string)
At its core, an object is a hashtable JavaScript Objects var myObj = new Object();
myObj["myName"] = "Dave";
myObj["myJob"] = "Common Sense Evangelist";
alert(myObj["myName"] + " is a " + myObj["myJob"]);
//Dave is a Common Sense Evangelist And items in the hashtable are also accessible via dot notation alert(myObj.myName + " is a " + myObj.myJob);
//Dave is a Common Sense Evangelist And objects can be created using the curly brace shorthand Since JavaScript is functional, functions are first class objects
Pass them as parameters or variables
Create them on the fly
Very powerful
Dynamic invocation is very useful
Think of a menu bar example...

Menu items could have an attribute that maps to an action to perform when clicked.

Grab the attribute and then invoke the function mapped to that object using the hashtable notation Dynamically Invoking Functions on Objects funcToCall = $(this).data("click"); agileWays[funcToCall](); Objects can contain pretty much any JavaScript construct
Even objects and functions JavaScript Objects var agileWays = agileWays || {}; //default assignment
agileWays.sayHi = function() { alert("hi"); };
agileWays.sayHi(); //hi I can execute an object's function using hashtable syntax, too agileWays["sayHi"](); //hi Notice two things
I added functions to an object and had them execute immediately
I could access the functions either through dot notation ("statically" typed) and also via a string (dynamic??)
What happens here? JavaScript Objects var funcName = "sayHi";
agileWays[funcName](); //'hi' or error?? Not quite, but some concepts are present
Objects seen so far (e.g. agileWays) have been pretty static
I can create instances by using a constructor
I didn't know that!! Object Oriented JavaScript? var AgileWays = AgileWays || {};

AgileWays = function(fName, lName) {
//keep hold of this
var me = this;

//public "properties"
this.firstName = fName;
this.lastName = lName;

//private method
function getFullName() {
return me.firstName + " " + me.lastName;

//public method
this.fullName = function() { return getFullName(); };
}; Notice that public methods
are defined using 'this' Private methods are declared
as inner functions Private members declared with 'var'
Public members declared with 'this' You betcha...sort of
Start using the concept of prototype in JavaScript
Prototype chaining
Similar to, but not, constructor chaining What About Inheritance? function BaseAgile() {
this.companyName = "AgileWays";
this.getRevenue = function() { alert('Millions and millions...someday'); };

function AgileWays() {

AgileWays.prototype = new BaseAgile();
AgileWays.prototype.showName = function() {

var myAgile = new AgileWays();
myAgile.getRevenue(); //Millions and millions...
myAgile.showName(); //AgileWays Allows you to assign a base object to a object's prototype
Those base object members are then available
You can add new methods to your object's prototype in addition to the base
You can chain levels of inheritence together
When you call a function, the runtime will look for the function on the current object
It will walk the chain all the way back to Object What Does Prototype Inheritance Do? Available on each object
Invoked with an object is constructed
Can be used to add functions to existing objects The Prototype Object Object.prototype.saySomething = function() { alert("hi...I'm saying something"); };

var x = 10,
agileWays = {};

x.saySomething(); //"hi...I'm saying..."
agileWays.saySomething(); //"hi...I'm saying..." function AgileWays() {
this.companyName = "AgileWays";
this.showCompany = function() { alert("We are " + this.companyName + "!"); };

var myAgile = new AgileWays();

AgileWays.prototype.showSomethingElse = function() { alert("this is something else"); };

//notice I can call a function after myAgile is constructed
myAgile.showSomethingElse(); We CAN invoke functions several different ways
Functions ARE first class objects in JavaScript
Objects HAVE constructors
Objects CAN 'inherit' base object functionality
Objects CAN have functionality injected into them that affect all objects
Even existing instances

So what's next?

Let's look at creating object namespace hierarchies and putting it all together! So Where Are We? Not true namespacing like .NET provides
Not a logical container containing classes
More of a naming convention to prevent global namespace pollution
Every function without namespace is part of the global namespace
Can lead to name clashing
See this in jQuery when other libraries also define '$'
Namespacing provides organization and reduces clutter in global namespace
Also see how to provide member scoping, too! Namespacing in JavaScript Pretty easy - just name it! Creating the Namespace var Agile = Agile || {}; //new object creation...top level namespace This is establishing an object in the global namespace named 'Agile'
Everything else we create will be tied off this...not global I like Dan Wahlin's explanation of the Revealing Module Pattern (see resources)
Create the object's constructor
Associate member variables and functions in the prototype
Only reveal to the user those items you want to reveal
Remember -- var's in functions are like 'private'...this is 'public'
Prototype is self-executing function, so that object is immediately returned Add Objects To Our Namespace Agile.Team = function() {

Agile.Team.prototype = (function() {
var members = [],
addMember = function(devName) {
alert('Welcome ' + devName);
displayMembers = function() {

return {
add : addMember,
display : displayMembers
}()); Just 'new' them up!
But we can only use what we have revealed!! Using Our Namespaced Objects var myAgileTeam = new Agile.Team();
myAgileTeam.add('Dave'); //Welcome Dave
myAgileTeam.add('Joe'); //Welcome Joe
myAgileTeam.display(); //Dave,Joe Let's see some other tools we've looked at in action Using the Revealing Module Pattern, we can use a base object as our prototype, but we could also use composition: Composition Using Base Objects function BaseAgile(){
this.sayHi = function() { alert('hello'); };

Agile.Team.prototype = (function() {
var members = [],
baseStuff = new BaseAgile(),
addMember = function(devName) {
alert('Welcome ' + devName);
displayMembers = function() {

return {
add : addMember,
display : displayMembers,
hi : baseStuff.sayHi //composition of base methods


myAgileTeam.hi(); //hello Compose Team
using BaseAgile Only reveal what
you want We CAN create base object behavior
We CAN use that behavior in other objects, either as child objects
or through composition
We CAN hide implementation within our JavaScript objects and
only reveal what we want
We CAN avoid polluting the global namespace by creating our own
object hierarchies
We CAN logically group our logic in namespaces, which allows
for easier maintenance and more clearly expressing
the logic's intent So Where Are we? JavaScript is a little language that provides a lot
Functional, object-based, prototypal, dynamic, etc.
Pretty flexible...but that also causes confusion about it
Hopefully you were able to come away from this talk and say
I Didn't Know JavaScript Could Do That! Wrapping Up Douglas Crockford's blog on JS: http://javascript.crockford.com/
Helen Emerson's JavaScript series: http://helephant.com/2008/08/17/how-javascript-objects-work/
Dan Wahlin's blog on Revealing Module Pattern
http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx Resources While we're not looking at super cool DOM manipulations, you can always try this Some Cool Things javascript:document.body.contentEditable='true'; document.designMode='on'; void 0 Or you can try the rotation image JavaScript snippet javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.getElementsByTagName("img"); DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px"; DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}R++}setInterval('A()',5); void(0); When converting, keep in mind JS will try to convert to
best fit var a = 3,
b = 4;
alert('$' + a + b); JavaScript is a pretty dynamic language
What happens here? Some Other Cool JavaScript Features var x = 3;
eval('var y = 4');
alert(x + y); 'y' is part of the current scope
Can be used like any other variable
These features make JavaScript "weird"
But we can harness the weirdness to bring order to our JavaScript logic Markup Dynamic Menu Invocation <ul>
<li data-click="func1"><a href='#'>Click Me</a></li>
<li data-click="func2"><a href='#'>No, click me</a></li>
<li data-click="func3"><a href='#'>Really, I'm the one to click</a></li>
</ul> JavaScript var agileWays = agileWays || {};
agileWays.func1 = function() { alert('you clicked function 1'); };
agileWays.func2 = function() { alert('you clicked function 2'); };
agileWays.func3 = function() { alert('you clicked function 3'); };

var funcToCall;
funcToCall = $(this).data("click");
}); First class objects in JavaScript
Can pass around like any other variable Functions in JavaScript function doSomething(f, x){
var i=0;

var myFunc = function() { alert('I do something'); };
doSomething(myFunc, 3); Much like Func<> and Action<> in .NET
Syntax is a bit more concise
Types implied
Provides much of the power of JavaScript We've seen the power of functions
Dynamic invocation
Attach to objects (on the fly?)
Pass as variables
Let's take things a step further and use functions as the basis of our object model
Everything becomes a function
And as a result, we can do some pretty impressive things Next Steps... Pirates Fan What happens here? Prototype Abuse? Number.prototype.toString = function() { return 'dave'; }; I can override what's on the prototype
Need to be careful of this
Proper structuring of objects and functions can help Imagine a file consisting of many functions
What object are they associated with?
Global namespace (object -> big hashtable)
Can create clutter, and also bad side effects Also Need To Watch Function Clashing function sayHi(name){ return 'hi ' + name; }

function sayHi(name){ return 'hello ' + name; }

var stuff = 3,
theUL = $('ul'),
writer = function(text) { theUL.append('<li>' + text + '</li>'); };

writer(sayHi("dave")); All Of These (?)
Full transcript