SlideShare a Scribd company logo
1 of 82
Download to read offline
JavaScript
A Primer In Far Too Many Parts
History
Mocha
                     April 1995    LiveScript
                                  JavaScript


Brendan Eich
CTO, Mozilla Corp.
JScript



JavaScript
         ECMAScript


                       ActionScript
Basics
Data Types
• number
• string
• boolean
• object
• null
• NaN
• undefined
Strings




• Are Objects, have methods
Strings


"Foo" + "Bar";        //"FooBar"

var str = "Lorem Ipsum Dolor Sit Amet";

str.toLowerCase();    //"lorem ipsum dolor sit amet"
str.toUpperCase();    //"LOREM IPSUM DOLOR SIT AMET"
str.split(" ");       //["Lorem", "Ispum", "Dolor", "Sit", "Amet"]
str.substring(6,9);   //"Ips"

new String("Lorem Ipsum Dolor Sit Amet") == str; //true
String to Number


parseInt("56");        //56
parseInt("42.567");    //42
parseInt("asdf");      //NaN
parseInt("5a6");       //5
parseFloat("24.68");   //24.68
parseFloat("asdf");    //NaN
parseFloat("24a");     //24
Objects

• “Dictionary” / “Associative Array”
• Key: Value or 'Key': Value
  • Without ': A-Z0-9 only
• Does not keep intrinsic ordering
• Accessed keys using . (dot) or [] notation
Objects

var object = {
    foo: 'value',
    'complex key': 0,
    bar: {
        nested: true
    }
};

object.foo;                //'value'
object.['complex key'];    //0
object.bar.nested;         //true
object.bar['nested'];      //true
object['bar'].nested;      //true
object['bar']['nested'];   //true
in or hasOwnProperty()


• Tough call:
  • .hasOwnProperty() more consistent
  • in checks inherited properties
     • Used in for loop
in

var test   = {
    foo:   'value',
    bar:   'value',
    baz:   'value'
}

for (var key in test) {
    console.log(key + ": " + test[key]);
}

//PRINTS:
//foo: value
//bar: value
//baz: value
Arrays


• Special object
• Numerical keys only
• Keeps intrinsic ordering
• Short ([]) and Long (new Array()) syntax
Arrays

var arrayShort = [
    'one',
    'two'
];
arrayShort[2] = 'three';

var arrayLong = new Array();
arrayLong[0] = 'one';
arrayLong[1] = 'two';
arrayLong[2] = 'three';

//arrayShort: ["one", "two", "three"]
//arrayLong: ["one", "two", "three"]
Arrays
var arr = [1,2,3,4,6];

arr.indexOf(2);     //1
arr.join(':');      //"1:2:3:4:6"
arr.pop();          //6
//[1,2,3,4]
arr.push(7);        //5
//[1,2,3,4,7]
arr.reverse();      //[7,4,3,2,1]
arr.shift();        //1
//[2,3,4,7]
arr.unshift(8);     //5
//[8,2,3,4,7]
arr.slice(1);       //[2,3,4,7]
arr.slice(1,3);     //[2,3]
arr.slice(-3);      //[3,4,7]
arr.slice(-3,-1);   //[3,4]
Arrays



var arr1 = [1,2,3];
var arr2 = [3,4,5];

arr1.concat(arr2);    //[1,2,3,3,4,5]
Functions

• Are Objects as well
• “Elevated”
  • You can use a named function before it is
    defined in code

  • Function definitions are elevated to the top
Functions


function Foo() {
    //...
}

Foo(); //valid
Bar(); //valid

function Bar() {
    //...
}
Functions


function Foo() {

}

Foo.bar = "value";

'bar' in Foo;       //true
Foo.bar == "value"; //true
Function Arguments


• No way to assign default arguments
• But arguments are not required
  • If an argument is not specified, it is set to
    undefined
arguments



• A special variable found inside a function
• A not-quite array object containing all the
 function arguments
arguments


function sum() {
    var x = 0;
    for (var i = 0; i < arguments.length; ++i) {
        x += arguments[i];
    }
    return x;
}
sum(1, 2, 3); //6
typeof



• Determines a variables type
• Returns a string
typeof


typeof   true;        //"boolean"
typeof   12;          //"number"
typeof   "string";    //"string"
typeof   [];          //"object"
typeof   {};          //"object"
typeof   NaN;         //"number"
typeof   null;        //"object"
typeof   undefined;   //"undefined"

function Foo() {}
typeof Foo;       //"function"
Comparison
• a == b / a != b
  • A and B compared by value alone
  • 1 == “1” evaluates to true
• a === b / a !== b
  • A and B compared by value and by type
  • 1 === “1” evaluates to false
window, document
• Built in, global, Objects
• window
  • Provides access to the browser window
  • The “global” object: foo === window.foo
  • Things like window.location.href, etc
• document
  • Provides access to the current DOM
Scoping
Global & Local

• Functions are the only way to create new
 scopes

• Variables defined with var are local
• Variables defined without var are global
• Global variables are members of window
Global & Local

var outerScope = 10;
var outerScope2 = 10;

function Foo() {
    var outerScope   =   20;
    var innerScope   =   20;
    globalVariable   =   30;
    outerScope2      =   40;
}

Foo();

alert(outerScope);         //10
alert(outerScope2);        //40
alert(innerScope);         //error
alert(globalVariable);     //30
Lexical Scoping
function Foo() {              function Foo() {
    var baz = 1;                  var baz = 1;
    return Bar();
}                                 function Bar() {
                                      return baz;
function Bar() {                  }
    return baz;
}                                 return Bar();
                              }
Foo(); //baz is not defined
                              Foo(); //1
Closures
Closures

• First-Class
  • Can assign functions to variables, pass as
     arguments and return as values

• Anonymous
  • Not required to have a name
• A function that “closes over” variables defined
  outside itself
Closures

function Foo() {
    var count = 0;

    return function() {
        count = count + 1;
        return count;
    };
}

var bar = Foo();

bar(); //1
bar(); //2
bar(); //3
Closures

function createAdder(amount) {
    return function(input) {
        return input + amount;
    };
}

var add2 = createAdder(2);

add2(2); //4
add2(8); //10

var add3 = createAdder(3);

add3(3); //6
add3(7); //10
Module Pattern

   (function(exports, undefined){
       //ALL your code here

       var localVar = "bar"
       globalVar    = "baz";

       exports.foo   = "bat";
   })(window);

   alert(localVar);             //error
   alert(globalVar);            //"baz"
   alert(window.globalVar);     //"baz"
   alert(foo);                  //"bat"
   alert(window.foo);           //"bat"




BEWARE: export (singular) is a reserved word in Safari
this
this


• Trips everyone up
• Special variable used within a function
• Refers to the “contextual object”
• Changes based on where a function executes
this

var Foo = {
    bar: "bar",
    baz: function() {
        return this.bar;
    }
};

Foo.baz(); //"bar"

Foo.bar = "bat";
Foo.baz(); //"bat"

var baz = Foo.baz;
baz();     //undefined
this

var Foo = {
    bar: "bar",
    baz: function() {
        return this.bar;
    }
};

Foo.bat = function() {
    return this.bar + "bat";
};

Foo.bat(); //"barbat"
call & apply



• Methods in the function prototype
• Change the context in which a function
 executes!
call & apply

var Foo = {
    bar: "bar",
    baz = function(param1, param2) {
        return this.bar + param1 + param2;
    }
};

var Foo2 = {
    bar: "123"
};

Foo.baz("baz", "bat"); //"barbazbat"

Foo.baz.apply(Foo2, "baz", "bat"); //"123bazbat"
Foo.baz.call(Foo2, ["baz", "bat"]); //"123bazbat"
Exceptions
Exceptions



• All errors are thrown
• Classic try...catch...finally blocks
Exceptions


try {
    funcDoesNotExist();
} catch (e) {
    alert(e); //ReferenceError: funcDoesNotExist is not defined
} finally {
    //Always Executes
}
Exceptions
function Foo() {
    throw new Error("Message");
}

function Bar() {
    throw "Message";
}

try {
    Foo();
} catch (e) {
    e.message == "Message"; //true
}

try {
    Bar();
} catch (e) {
    e == "Message"; //true
}
Prototype
OOP... Kinda...

• Almost no real difference between a dictionary
 and an object

• Named Functions double as object constructors
• Function objects contain a prototype
 dictionary that is copied to instance when
 using new
OOP... Kinda...

                                   Foo
function Foo() {
    //The "Constructor"
}
                                   ‣ bar
Foo.bar = function() {
    //A "Static" Function
                                   ‣ prototype
}
                                    ‣ baz
Foo.prototype.baz = function() {    ‣ constructor
    //A "Method"
};                                  ‣ __proto__
new

                                 instance
var instance = new Foo();

instance.baz();      //works
instance.bar();      //error     ‣ __proto__

Foo.bar();           //works
                                  ‣ baz
Foo.baz();           //error
                                  ‣ constructor
Foo.prototype.baz(); //works
                                  ‣ __proto__
                                     ‣ ...
new

                                 instance
instance.bat = function() {
    /* ... */
}
                                 ‣ bat
instance.bat();      //works
                                 ‣ __proto__
Foo.bat();           //error
                                  ‣ baz
Foo.prototype.bat(); //error
                                  ‣ constructor
                                  ‣ __proto__
                                     ‣ ...
Overriding Prototype
function Foo(baz) {
    this.baz = baz;
}

Foo.prototype.bar = function() {
    return this.baz;
};

var foo1 = new Foo(1);
var foo2 = new Foo(2);

foo1.bar(); //1
foo2.bar(); //2

Foo.prototype.bar = function() {
    return this.baz * 2;
};

foo1.bar(); //2
foo2.bar(); //4
Asynchronous
Asynchronous



• setTimeout, setInterval allow you to have code
 executing asynchronously while other code
 executes
setInterval



var id = setInterval(function() {
    //Code to execute every 1000 milliseconds
}, 1000);

//clearInterval(id); to stop
setTimeout



var id = setTimeout(function() {
    //Code to execute after 1000 milliseconds have passed
}, 1000);

//clearTimeout(id); to cancel
Nifty Trick


setTimeout(function() {
    //Code to run in parallel
    //while the code after is
    //executed.
}, 1);

//Code here will execute immediately
//without waiting on the above
DOM
DOM



• Document Object Model
• API to interact with the HTML/XHTML
 document
DOM


var paragraph = document.createElement('p');
var content = document.createTextNode("Lorem Ipsum");

paragraph.appendChild(content);
paragraph.classList.add('my-class');

document.getElementsByTagName('body')[0].appendChild(paragraph);
JSON
2001   JSON




Douglas Crockford
     Awesome
JSON

• JavaScript Object Notation
• Serialization format that is basically JavaScript
 code minus comments

• Can be eval()’ed
• Minimal overhead compared to XML
  • No advanced parsers needed
JSON
{"menu": {                                <menu id="file" value="File">
   "id": "file",                            <popup>
   "value": "File",                           <menuitem value="New"
   "popup": {                                           onclick="CreateNewDoc()" />
     "menuitem": [                            <menuitem value="Open"
       {"value": "New",                                 onclick="OpenDoc()" />
        "onclick": "CreateNewDoc()"},         <menuitem value="Close"
       {"value": "Open",                                onclick="CloseDoc()" />
        "onclick": "OpenDoc()"},            </popup>
       {"value": "Close",                 </menu>
        "onclick": "CloseDoc()"}
     ]
   }
}}
jQuery
January 2006   jQuery




John Resig
Author, jQuery
jQuery


• Cross-browser JavaScript library
• Simplifies and normalizes DOM, AJAX, etc.
• Centers around using extended CSS selectors
 to grab an element(s)
jQuery
$("div").addClass("special");
                                Find all div tags
                                Add class special
jQuery
$("#foo")                              <div id="foo"></div>
  .html("<strong>bar</strong> baz");
                                       <div id="foo">
                                           <strong>bar</strong> baz
                                       </div>
jQuery
$('img.preview').hide();
$('.button').click(function(){   •Hide all images with
});
    $('img.preview').show();     the class preview
                                 •When element with the
                                 class button is clicked,
                                 show all images with the
                                 class preview
Animation
$('.button').click(function(){
    $('img.preview')
                                     When .button is clicked,
        .fadeOut(600, function() {   fade out img.preview
            $(this).remove();
        });                          over 600 milliseconds
});
                                     and then remove it from
                                     the DOM
Events



• jQuery wraps an event handling system
• Handles browser events, AJAX events, and
 custom events
Events


$(document).ready(function() {
    //Only execute when the document fires
    //its onready event (page is done loading)
});

$(document).bind('ready', function() {
    //Equivalent to the above
});
Events



$('img').hover(function(){
    //Do something when user hovers over
    //any img tag
});
AJAX

• Asynchronous JavaScript And XML
  • Though never use XML, use JSON
• jQuery has an AJAX library
• Wraps all the different browser quirks
  • IE is weird
AJAX


$.ajax({
  url: "test.php",
  success: function(data){
      $('div.status').addClass("done")
                     .html(data);
  }
});
Resources



http://api.jquery.com/
Tools
Chrome/Safari Devel. Tools
Firefox FireBug

More Related Content

What's hot

Javascript Primer
Javascript PrimerJavascript Primer
Javascript PrimerAdam Hepton
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Data Con LA
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app developmentopenak
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift OverviewKaz Yoshikawa
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsSolv AS
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About RubyKeith Bennett
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Workhorse Computing
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroAdam Crabtree
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnıl Sözeri
 

What's hot (20)

Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About Ruby
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Similar to JavaScript Primer

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptHong Liu
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...Mathias Bynens
 
Javascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyJavascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyThorsten Suckow-Homberg
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
Javascript - The core
Javascript - The coreJavascript - The core
Javascript - The corerenchenyu
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11Uilian Ries
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Writing Ruby Extensions
Writing Ruby ExtensionsWriting Ruby Extensions
Writing Ruby ExtensionsMatt Todd
 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developersAndrew Eddie
 

Similar to JavaScript Primer (20)

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
 
Javascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyJavascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the Ugly
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Javascript - The core
Javascript - The coreJavascript - The core
Javascript - The core
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Es.next
Es.nextEs.next
Es.next
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
Effective ES6
Effective ES6Effective ES6
Effective ES6
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
this
thisthis
this
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Writing Ruby Extensions
Writing Ruby ExtensionsWriting Ruby Extensions
Writing Ruby Extensions
 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developers
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 

JavaScript Primer

  • 1. JavaScript A Primer In Far Too Many Parts
  • 3. Mocha April 1995 LiveScript JavaScript Brendan Eich CTO, Mozilla Corp.
  • 4. JScript JavaScript ECMAScript ActionScript
  • 6. Data Types • number • string • boolean • object • null • NaN • undefined
  • 8. Strings "Foo" + "Bar"; //"FooBar" var str = "Lorem Ipsum Dolor Sit Amet"; str.toLowerCase(); //"lorem ipsum dolor sit amet" str.toUpperCase(); //"LOREM IPSUM DOLOR SIT AMET" str.split(" "); //["Lorem", "Ispum", "Dolor", "Sit", "Amet"] str.substring(6,9); //"Ips" new String("Lorem Ipsum Dolor Sit Amet") == str; //true
  • 9. String to Number parseInt("56"); //56 parseInt("42.567"); //42 parseInt("asdf"); //NaN parseInt("5a6"); //5 parseFloat("24.68"); //24.68 parseFloat("asdf"); //NaN parseFloat("24a"); //24
  • 10. Objects • “Dictionary” / “Associative Array” • Key: Value or 'Key': Value • Without ': A-Z0-9 only • Does not keep intrinsic ordering • Accessed keys using . (dot) or [] notation
  • 11. Objects var object = { foo: 'value', 'complex key': 0, bar: { nested: true } }; object.foo; //'value' object.['complex key']; //0 object.bar.nested; //true object.bar['nested']; //true object['bar'].nested; //true object['bar']['nested']; //true
  • 12. in or hasOwnProperty() • Tough call: • .hasOwnProperty() more consistent • in checks inherited properties • Used in for loop
  • 13. in var test = { foo: 'value', bar: 'value', baz: 'value' } for (var key in test) { console.log(key + ": " + test[key]); } //PRINTS: //foo: value //bar: value //baz: value
  • 14. Arrays • Special object • Numerical keys only • Keeps intrinsic ordering • Short ([]) and Long (new Array()) syntax
  • 15. Arrays var arrayShort = [ 'one', 'two' ]; arrayShort[2] = 'three'; var arrayLong = new Array(); arrayLong[0] = 'one'; arrayLong[1] = 'two'; arrayLong[2] = 'three'; //arrayShort: ["one", "two", "three"] //arrayLong: ["one", "two", "three"]
  • 16. Arrays var arr = [1,2,3,4,6]; arr.indexOf(2); //1 arr.join(':'); //"1:2:3:4:6" arr.pop(); //6 //[1,2,3,4] arr.push(7); //5 //[1,2,3,4,7] arr.reverse(); //[7,4,3,2,1] arr.shift(); //1 //[2,3,4,7] arr.unshift(8); //5 //[8,2,3,4,7] arr.slice(1); //[2,3,4,7] arr.slice(1,3); //[2,3] arr.slice(-3); //[3,4,7] arr.slice(-3,-1); //[3,4]
  • 17. Arrays var arr1 = [1,2,3]; var arr2 = [3,4,5]; arr1.concat(arr2); //[1,2,3,3,4,5]
  • 18. Functions • Are Objects as well • “Elevated” • You can use a named function before it is defined in code • Function definitions are elevated to the top
  • 19. Functions function Foo() { //... } Foo(); //valid Bar(); //valid function Bar() { //... }
  • 20. Functions function Foo() { } Foo.bar = "value"; 'bar' in Foo; //true Foo.bar == "value"; //true
  • 21. Function Arguments • No way to assign default arguments • But arguments are not required • If an argument is not specified, it is set to undefined
  • 22. arguments • A special variable found inside a function • A not-quite array object containing all the function arguments
  • 23. arguments function sum() { var x = 0; for (var i = 0; i < arguments.length; ++i) { x += arguments[i]; } return x; } sum(1, 2, 3); //6
  • 24. typeof • Determines a variables type • Returns a string
  • 25. typeof typeof true; //"boolean" typeof 12; //"number" typeof "string"; //"string" typeof []; //"object" typeof {}; //"object" typeof NaN; //"number" typeof null; //"object" typeof undefined; //"undefined" function Foo() {} typeof Foo; //"function"
  • 26. Comparison • a == b / a != b • A and B compared by value alone • 1 == “1” evaluates to true • a === b / a !== b • A and B compared by value and by type • 1 === “1” evaluates to false
  • 27. window, document • Built in, global, Objects • window • Provides access to the browser window • The “global” object: foo === window.foo • Things like window.location.href, etc • document • Provides access to the current DOM
  • 29. Global & Local • Functions are the only way to create new scopes • Variables defined with var are local • Variables defined without var are global • Global variables are members of window
  • 30. Global & Local var outerScope = 10; var outerScope2 = 10; function Foo() { var outerScope = 20; var innerScope = 20; globalVariable = 30; outerScope2 = 40; } Foo(); alert(outerScope); //10 alert(outerScope2); //40 alert(innerScope); //error alert(globalVariable); //30
  • 31. Lexical Scoping function Foo() { function Foo() { var baz = 1; var baz = 1; return Bar(); } function Bar() { return baz; function Bar() { } return baz; } return Bar(); } Foo(); //baz is not defined Foo(); //1
  • 33. Closures • First-Class • Can assign functions to variables, pass as arguments and return as values • Anonymous • Not required to have a name • A function that “closes over” variables defined outside itself
  • 34. Closures function Foo() { var count = 0; return function() { count = count + 1; return count; }; } var bar = Foo(); bar(); //1 bar(); //2 bar(); //3
  • 35. Closures function createAdder(amount) { return function(input) { return input + amount; }; } var add2 = createAdder(2); add2(2); //4 add2(8); //10 var add3 = createAdder(3); add3(3); //6 add3(7); //10
  • 36. Module Pattern (function(exports, undefined){ //ALL your code here var localVar = "bar" globalVar = "baz"; exports.foo = "bat"; })(window); alert(localVar); //error alert(globalVar); //"baz" alert(window.globalVar); //"baz" alert(foo); //"bat" alert(window.foo); //"bat" BEWARE: export (singular) is a reserved word in Safari
  • 37. this
  • 38. this • Trips everyone up • Special variable used within a function • Refers to the “contextual object” • Changes based on where a function executes
  • 39. this var Foo = { bar: "bar", baz: function() { return this.bar; } }; Foo.baz(); //"bar" Foo.bar = "bat"; Foo.baz(); //"bat" var baz = Foo.baz; baz(); //undefined
  • 40. this var Foo = { bar: "bar", baz: function() { return this.bar; } }; Foo.bat = function() { return this.bar + "bat"; }; Foo.bat(); //"barbat"
  • 41. call & apply • Methods in the function prototype • Change the context in which a function executes!
  • 42. call & apply var Foo = { bar: "bar", baz = function(param1, param2) { return this.bar + param1 + param2; } }; var Foo2 = { bar: "123" }; Foo.baz("baz", "bat"); //"barbazbat" Foo.baz.apply(Foo2, "baz", "bat"); //"123bazbat" Foo.baz.call(Foo2, ["baz", "bat"]); //"123bazbat"
  • 44. Exceptions • All errors are thrown • Classic try...catch...finally blocks
  • 45. Exceptions try { funcDoesNotExist(); } catch (e) { alert(e); //ReferenceError: funcDoesNotExist is not defined } finally { //Always Executes }
  • 46. Exceptions function Foo() { throw new Error("Message"); } function Bar() { throw "Message"; } try { Foo(); } catch (e) { e.message == "Message"; //true } try { Bar(); } catch (e) { e == "Message"; //true }
  • 48. OOP... Kinda... • Almost no real difference between a dictionary and an object • Named Functions double as object constructors • Function objects contain a prototype dictionary that is copied to instance when using new
  • 49. OOP... Kinda... Foo function Foo() { //The "Constructor" } ‣ bar Foo.bar = function() { //A "Static" Function ‣ prototype } ‣ baz Foo.prototype.baz = function() { ‣ constructor //A "Method" }; ‣ __proto__
  • 50. new instance var instance = new Foo(); instance.baz(); //works instance.bar(); //error ‣ __proto__ Foo.bar(); //works ‣ baz Foo.baz(); //error ‣ constructor Foo.prototype.baz(); //works ‣ __proto__ ‣ ...
  • 51. new instance instance.bat = function() { /* ... */ } ‣ bat instance.bat(); //works ‣ __proto__ Foo.bat(); //error ‣ baz Foo.prototype.bat(); //error ‣ constructor ‣ __proto__ ‣ ...
  • 52. Overriding Prototype function Foo(baz) { this.baz = baz; } Foo.prototype.bar = function() { return this.baz; }; var foo1 = new Foo(1); var foo2 = new Foo(2); foo1.bar(); //1 foo2.bar(); //2 Foo.prototype.bar = function() { return this.baz * 2; }; foo1.bar(); //2 foo2.bar(); //4
  • 54. Asynchronous • setTimeout, setInterval allow you to have code executing asynchronously while other code executes
  • 55. setInterval var id = setInterval(function() { //Code to execute every 1000 milliseconds }, 1000); //clearInterval(id); to stop
  • 56. setTimeout var id = setTimeout(function() { //Code to execute after 1000 milliseconds have passed }, 1000); //clearTimeout(id); to cancel
  • 57. Nifty Trick setTimeout(function() { //Code to run in parallel //while the code after is //executed. }, 1); //Code here will execute immediately //without waiting on the above
  • 58. DOM
  • 59. DOM • Document Object Model • API to interact with the HTML/XHTML document
  • 60.
  • 61. DOM var paragraph = document.createElement('p'); var content = document.createTextNode("Lorem Ipsum"); paragraph.appendChild(content); paragraph.classList.add('my-class'); document.getElementsByTagName('body')[0].appendChild(paragraph);
  • 62.
  • 63. JSON
  • 64. 2001 JSON Douglas Crockford Awesome
  • 65. JSON • JavaScript Object Notation • Serialization format that is basically JavaScript code minus comments • Can be eval()’ed • Minimal overhead compared to XML • No advanced parsers needed
  • 66. JSON {"menu": { <menu id="file" value="File"> "id": "file", <popup> "value": "File", <menuitem value="New" "popup": { onclick="CreateNewDoc()" /> "menuitem": [ <menuitem value="Open" {"value": "New", onclick="OpenDoc()" /> "onclick": "CreateNewDoc()"}, <menuitem value="Close" {"value": "Open", onclick="CloseDoc()" /> "onclick": "OpenDoc()"}, </popup> {"value": "Close", </menu> "onclick": "CloseDoc()"} ] } }}
  • 68. January 2006 jQuery John Resig Author, jQuery
  • 69. jQuery • Cross-browser JavaScript library • Simplifies and normalizes DOM, AJAX, etc. • Centers around using extended CSS selectors to grab an element(s)
  • 70. jQuery $("div").addClass("special"); Find all div tags Add class special
  • 71. jQuery $("#foo") <div id="foo"></div> .html("<strong>bar</strong> baz"); <div id="foo"> <strong>bar</strong> baz </div>
  • 72. jQuery $('img.preview').hide(); $('.button').click(function(){ •Hide all images with }); $('img.preview').show(); the class preview •When element with the class button is clicked, show all images with the class preview
  • 73. Animation $('.button').click(function(){ $('img.preview') When .button is clicked, .fadeOut(600, function() { fade out img.preview $(this).remove(); }); over 600 milliseconds }); and then remove it from the DOM
  • 74. Events • jQuery wraps an event handling system • Handles browser events, AJAX events, and custom events
  • 75. Events $(document).ready(function() { //Only execute when the document fires //its onready event (page is done loading) }); $(document).bind('ready', function() { //Equivalent to the above });
  • 76. Events $('img').hover(function(){ //Do something when user hovers over //any img tag });
  • 77. AJAX • Asynchronous JavaScript And XML • Though never use XML, use JSON • jQuery has an AJAX library • Wraps all the different browser quirks • IE is weird
  • 78. AJAX $.ajax({ url: "test.php", success: function(data){ $('div.status').addClass("done") .html(data); } });
  • 80. Tools