SlideShare uma empresa Scribd logo
1 de 70
JavaScript
            The World's Most Misunderstood Programming Language




Tiago Rodrigues
tmcrodrigues@gmail.com
http://trodrigues.net
What is it ?

  JavaScript IS NOT Java
What is it ?

  JavaScript IS NOT Java

  Created in 1995 by Netscape (LiveScript)
What is it ?

  JavaScript IS NOT Java

  Created in 1995 by Netscape (LiveScript)

  ECMAScript standard
    JScript and ActionScript, also based on ECMAScript
What is it ?

  JavaScript IS NOT Java

  Created in 1995 by Netscape (LiveScript)

  ECMAScript standard
    JScript and ActionScript, also based on ECMAScript

  Dynamic, Weakly typed
What is it ?

  JavaScript IS NOT Java

  Created in 1995 by Netscape (LiveScript)

  ECMAScript standard
    JScript and ActionScript, also based on ECMAScript

  Dynamic, Weakly typed

  Object Oriented, Prototype based
What is it ?

  JavaScript IS NOT Java

  Created in 1995 by Netscape (LiveScript)

  ECMAScript standard
    JScript and ActionScript, also based on ECMAScript

  Dynamic, Weakly typed

  Object Oriented, Prototype based

  Functional features
What can we do with it ?

  Scripting language created for programmatic access of
  webpage objects
What can we do with it ?

  Scripting language created for programmatic access of
  webpage objects


  Currently also used for:

     Application scripting

     Server side scripting
JavaScript we see everyday

This application (Google Docs)
JavaScript we see everyday

Gmail, SAPO Mail, Google Reader
JavaScript we see everyday

Rich text editors
JavaScript we see everyday

Ads
JavaScript we see everyday

Comment systems (SAPO Comments, Disqus)
Why people hate it

  Bad uses

    Popup ads, annoying animations
Why people hate it

  Bad uses

     Popup ads, annoying animations

  Bad practices lead to slower code
Why people hate it

  Bad uses

     Popup ads, annoying animations

  Bad practices lead to slower code

     Many books advocated wrong practices for years

     Lots of bad tutorials and bad code all over the web

     People didn't want to learn, so they replicated the bad
     code
Why developers hate it

  Standard is incoherent
Why developers hate it

  Standard is incoherent

     Being solved !
Why developers hate it

  Standard is incoherent

     Being solved !


  Bad implementations
Why developers hate it

  Standard is incoherent

     Being solved !


  Bad implementations


  Browser differences
Why developers hate it

  Standard is incoherent

     Being solved !


  Bad implementations


  Browser differences


  However, it will take time...
Learning the language

  Basic syntax is similar to C-like languages


  Code goes in .js files or HTML <script> tag


  Comments are the same as C


  alert("Hello world ! JavaScript is awesome !");
Variables

  var hello = "world";

  var keyword: local variable

  No need to declare types
Variables
 Variable types

  Numbers         var   num = 1;
  Strings         var   str = "hi !";
  Objects         var   obj = new Object();
  Arrays          var   arr = ["string", 2];
  Functions       var   fun = function() {};
  Regexps         var   regexp = /^jssrocks/;



    Numbers, Strings, Regexps and Functions are
    really Objects
Variables

  Be careful...

     "30a".parseInt();

     "40.5".parseInt();

     "40.5".parseFloat();
Variables

  Strings

     Concatenation

        "Tiago" + " " + "Rodrigues"
Variables

  Strings

     Concatenation

        "Tiago" + " " + "Rodrigues"

        typeof(26 + "px"); // string

        typeof 26; // number
Variables

  Other values

     true, false

     null

     undefined
Control structures

  Control structures

     if (cond) { ... } else { ... }

     while (cond) { ... }

     do { ... } while (cond);

     for (cond) { ... }

     switch (expr) { case ... : ... ; break; }

     try { ... } catch (exception) { ... }
Learning the language

  Control structures

     for (var i=0; i<10; i++) { ... }

     for (var i in obj) { ... }
Objects

var obj = {
    property: value
}
Objects

var obj = {
    "name": "content",
    other_name: 1,
    this_is_an_array: [1, 2, 3],
    "this-would-be": "wrong"
}

alert(obj.name); // content

alert(obj["name"]); // content
Functions


function add(a, b) {
    return a + b;
}
Functions


function add(a, b) {
    return a + b;
}

  Wrong ! Function goes global !
Functions


function add(a, b) {
    return a + b;
}

  Wrong ! Function goes global !

  But functions are objects !

var add = function(a, b) {
    return a + b;
}
Functions


var module = {
    add: function(a, b) {
        return a + b;
    },
    sub: function(a, b) {
        return a - b;
    }
}

module.add(1, 2); // 3
Context

  Why is context so important ?

var fun = function(){
    var num = 1;
    silly_var = 2;
    alert(num); // 1;
}

alert(num); // undefined

alert(silly_var); // 2
Context

   Why is context so important ?

var module = {
    str: "blah",
    print: function() {
        alert(this.blah);
    }
}

module.print(); // blah

However, this can be ambiguous, so be careful.
Functional features

  Let's go functional !

var fun = function(callback) {
    callback();
}

fun(function() {
    alert("I'm anonymous !");
});
Closures

var fun = function() {
    var num = 1;
    var inner = function() {
        alert(num);
    }
    inner(); // nothing happens...yet
}

fun(); // 1

inner(); // undefined
Available objects

    Numbers, Strings, Arrays all have methods

    There are many more available objects:

        Math, Date, etc*




* https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference
Available objects

  Examples:

var str = "Tiago Rodrigues";
str.split(" "); // ["Tiago", "Rodrigues"];


Math.sqrt(36); // 6


var arr = [4, 6, 3, 7];
arr.sort(); // [3, 4, 6, 7]
Object orientation

  But JavaScript is Object Oriented

  So how do we create object instances ?

  We use prototypes !
Classes

  Defining a class

var Book = function(name) {
    this.init(name);
}

  Book is a constructor
Prototypes

     Let's add attributes and methods to our class

Book.prototype = {
    name: "", // this is an attribute

       // this is a method
       init: function(name) {
           this.name = name;
       },

       sayName: function() {
           alert(this.name);
       }
};
Prototypes

  So let's create some books

var good_parts = Book("The Good Parts");

good_parts.sayName(); // The Good Parts


var def_guide = Book("The Definitive Guide");

def_guide.sayName(); // The Definitive Guide
Prototypes

  But why is this so great ?

Book.prototype.removeName = function() {
   this.name = "";
}

  Extending default objects

String.prototype.trim = function() {
   return this.replace(/^s+|s+$|n+$/g, '');
}

" trim me      ".trim(); // "trim me"
The Document Object Model

 API for (X)HTML files

 Tree representation of all the objects in a file

 Each object has properties and methods

 Not the same in every browser

    Mostly IE not up to date
The Document Object Model

 window represents your browser window

 document represents your current document

 document.forms is an array with all your form fields

 Many other objects are available
Selecting objects


<div id="content">
    blah
</div>


var div = document.getElementById("content");

alert(content.innerHTML); // blah
Event handling

<a href="#" onClick="alert('hi')">click me</a>

<a href="#" id="link">click me</a>
Event handling

<a href="#" onClick="alert('hi')">click me</a>

<a href="#" id="link">click me</a>

On the JS file:
var lnk = document.getElementById("link");
if (lnk.addEventListener){
     lnk.addEventListener(
          'click', handler, false);
} else if (lnk.attachEvent){
     lnk.attachEvent('onclick', handler);
}
Object properties

<a href="#" id="link">click me</a>

On the JS file:
var lnk = document.getElementById("link");

lnk.href = "file.html";

lnk.style.color = "#000";
Basic output on a browser

  Alert

alert("Hi !");

  Confirm

confirm("Are you there ?");
// returns true or false

  Prompt

prompt("What's your name ?");
Timing

  Flashing an alert box after 5 seconds

setTimeout(function() {
    alert("click me !");
}, 5000);
Timing

  Flashing an alert box after 5 seconds

setTimeout(function() {
    alert("click me !");
}, 5000);

  Flashing a box every 5 seconds

var int = setInterval(function() {
    if(confirm("Stop ?")) {
        clearInterval(int);
    }
}, 5000);
JSON    

     JavaScript Object Notation *

{
        "name" : "Tiago Rodrigues",
        "age" : 24,
        "profession" : "JavaScript developer"
}

     Other languages have similar structures

     There are libraries available on every popular language


* http://json.org
Ajax

    Asynchronous Javascript And XML*

    Fetching content through JavaScript

         with the use of the XMLHttpRequest object

    Server doesn't send an entire page, only what's needed

    Insert the content in the current page through JavaScript




* http://adaptivepath.com/ideas/essays/archives/000385.php
Ajax




* http://adaptivepath.com/ideas/essays/archives/000385.php
Ajax

 Content can be

    HTML

    XML

    JSON
Libraries and frameworks

  Extend the base language

  Abstract browser differences

     Selectors

     Events

     AJAX

  Add widgets and reusable modules
Libraries and frameworks

  Problems

    Many library users don't learn the base language
Libraries and frameworks

  Problems

    Many library users don't learn the base language

    Because of this, they abuse the base language
Libraries and frameworks

  Problems

    Many library users don't learn the base language

    Because of this, they abuse the base language

    This leads to performance problems
Libraries and frameworks

  Problems

    Many library users don't learn the base language

    Because of this, they abuse the base language

    This leads to performance problems

    So...be careful !
Libraries and frameworks

     Prototype / script.aculo.us

     jQuery / jQuery UI

     Dojo

     LibSAPO.js

     Many others: extjs, Mootools, etc

     Ajaxian* has a great list


* http://ajaxian.com
Good practices

     Unobtrusive JavaScript
       Not blocking possible actions
       Making them available without JavaScript

     Progressive Enhancement and Graceful Degradation
        Build your website with no JavaScript at all
        Add it later to improve user experience
        This way, the website will degrade gracefully

     Verify your code !
        http://jslint.com/


* http://andr3.net/blog/post/141
Other uses

  Server Side JS
     Narwhal
     Node.js

  Adobe AIR / Tweetanium
  Extensões Google Chrome
  Extensões Mozilla Firefox (Jetpack)
  Phonegap, Mojo, W3C Widgets (Opera widgets)
  Platform scripting
     .NET
     J2EE (Rhino)
References

  Books
     JavaScript: The Definitive Guide
     JavaScript: The Good Parts

  http://javascript.crockford.com

  http://developer.mozilla.org

Mais conteúdo relacionado

Mais procurados

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroAdam Crabtree
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 

Mais procurados (20)

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript OOP
JavaScript OOPJavaScript OOP
JavaScript OOP
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 

Destaque

第六、七週
第六、七週第六、七週
第六、七週fudy9015
 
Rehabilitación de la afasia y de trastornos asociados j peña - casanova
Rehabilitación de la afasia y de trastornos asociados   j peña - casanovaRehabilitación de la afasia y de trastornos asociados   j peña - casanova
Rehabilitación de la afasia y de trastornos asociados j peña - casanovaJavier Espinosa
 
Prototype e LibSAPO.js
Prototype e LibSAPO.jsPrototype e LibSAPO.js
Prototype e LibSAPO.jsSAPO Sessions
 
TonTonDungeon Introduction
TonTonDungeon IntroductionTonTonDungeon Introduction
TonTonDungeon IntroductionHaridRK
 
"Lunia Z" JP 2.4 Update plan
"Lunia Z" JP 2.4 Update plan"Lunia Z" JP 2.4 Update plan
"Lunia Z" JP 2.4 Update planmongju
 
루니아Z 기자간담회 PT자료
루니아Z 기자간담회 PT자료루니아Z 기자간담회 PT자료
루니아Z 기자간담회 PT자료mongju
 
Revista jane austen portugal maio 2011
Revista jane austen portugal maio 2011Revista jane austen portugal maio 2011
Revista jane austen portugal maio 2011Adriana Sales Zardini
 

Destaque (7)

第六、七週
第六、七週第六、七週
第六、七週
 
Rehabilitación de la afasia y de trastornos asociados j peña - casanova
Rehabilitación de la afasia y de trastornos asociados   j peña - casanovaRehabilitación de la afasia y de trastornos asociados   j peña - casanova
Rehabilitación de la afasia y de trastornos asociados j peña - casanova
 
Prototype e LibSAPO.js
Prototype e LibSAPO.jsPrototype e LibSAPO.js
Prototype e LibSAPO.js
 
TonTonDungeon Introduction
TonTonDungeon IntroductionTonTonDungeon Introduction
TonTonDungeon Introduction
 
"Lunia Z" JP 2.4 Update plan
"Lunia Z" JP 2.4 Update plan"Lunia Z" JP 2.4 Update plan
"Lunia Z" JP 2.4 Update plan
 
루니아Z 기자간담회 PT자료
루니아Z 기자간담회 PT자료루니아Z 기자간담회 PT자료
루니아Z 기자간담회 PT자료
 
Revista jane austen portugal maio 2011
Revista jane austen portugal maio 2011Revista jane austen portugal maio 2011
Revista jane austen portugal maio 2011
 

Semelhante a "Javascript" por Tiago Rodrigues

Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsAjax Experience 2009
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
Javascript Ks
Javascript KsJavascript Ks
Javascript Ksssetem
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and HowMike Wilcox
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsEugene Andruszczenko
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryRefresh Events
 

Semelhante a "Javascript" por Tiago Rodrigues (20)

Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Javascript Ks
Javascript KsJavascript Ks
Javascript Ks
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Goodparts
GoodpartsGoodparts
Goodparts
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Java script
Java scriptJava script
Java script
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 

Mais de Núcleo de Electrónica e Informática da Universidade do Algarve

Mais de Núcleo de Electrónica e Informática da Universidade do Algarve (12)

"GMail" por Artur Martins
"GMail" por Artur Martins"GMail" por Artur Martins
"GMail" por Artur Martins
 
"Estudo de implementação de alimentação eléctrica através de energia solar fo...
"Estudo de implementação de alimentação eléctrica através de energia solar fo..."Estudo de implementação de alimentação eléctrica através de energia solar fo...
"Estudo de implementação de alimentação eléctrica através de energia solar fo...
 
"Volunteer Computing with BOINC Client-Server side" por Diamantino Cruz e Ric...
"Volunteer Computing with BOINC Client-Server side" por Diamantino Cruz e Ric..."Volunteer Computing with BOINC Client-Server side" por Diamantino Cruz e Ric...
"Volunteer Computing with BOINC Client-Server side" por Diamantino Cruz e Ric...
 
"Parallel and Distributed Computing: BOINC Grid Implementation" por Rodrigo N...
"Parallel and Distributed Computing: BOINC Grid Implementation" por Rodrigo N..."Parallel and Distributed Computing: BOINC Grid Implementation" por Rodrigo N...
"Parallel and Distributed Computing: BOINC Grid Implementation" por Rodrigo N...
 
"Volunteer Computing With Boinc" por Diamantino Cruz e Ricardo Madeira
"Volunteer Computing With Boinc" por Diamantino Cruz e Ricardo Madeira"Volunteer Computing With Boinc" por Diamantino Cruz e Ricardo Madeira
"Volunteer Computing With Boinc" por Diamantino Cruz e Ricardo Madeira
 
"Estudo de implementação de alimentação eléctrica através de energia solar fo...
"Estudo de implementação de alimentação eléctrica através de energia solar fo..."Estudo de implementação de alimentação eléctrica através de energia solar fo...
"Estudo de implementação de alimentação eléctrica através de energia solar fo...
 
"Grid Computing: BOINC Overview" por Rodrigo Neves, Nuno Mestre, Francisco Ma...
"Grid Computing: BOINC Overview" por Rodrigo Neves, Nuno Mestre, Francisco Ma..."Grid Computing: BOINC Overview" por Rodrigo Neves, Nuno Mestre, Francisco Ma...
"Grid Computing: BOINC Overview" por Rodrigo Neves, Nuno Mestre, Francisco Ma...
 
“Web Services with Mobile Phones” por João Duro
“Web Services with Mobile Phones” por João Duro“Web Services with Mobile Phones” por João Duro
“Web Services with Mobile Phones” por João Duro
 
“Revision Control Systems: Subversion (SVN)” por Tiago Rodrigues
“Revision Control Systems: Subversion (SVN)” por Tiago Rodrigues“Revision Control Systems: Subversion (SVN)” por Tiago Rodrigues
“Revision Control Systems: Subversion (SVN)” por Tiago Rodrigues
 
“eSpeak” por Diogo Costa e Daniela Guerreiro
“eSpeak” por Diogo Costa e Daniela Guerreiro“eSpeak” por Diogo Costa e Daniela Guerreiro
“eSpeak” por Diogo Costa e Daniela Guerreiro
 
“LaTeX” por Manuel Rocha
“LaTeX” por Manuel Rocha“LaTeX” por Manuel Rocha
“LaTeX” por Manuel Rocha
 
“Squid” por Artur Martins, David Riedel e Florentino Bexiga
“Squid” por Artur Martins, David Riedel e Florentino Bexiga“Squid” por Artur Martins, David Riedel e Florentino Bexiga
“Squid” por Artur Martins, David Riedel e Florentino Bexiga
 

Último

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

"Javascript" por Tiago Rodrigues

  • 1. JavaScript The World's Most Misunderstood Programming Language Tiago Rodrigues tmcrodrigues@gmail.com http://trodrigues.net
  • 2. What is it ? JavaScript IS NOT Java
  • 3. What is it ? JavaScript IS NOT Java Created in 1995 by Netscape (LiveScript)
  • 4. What is it ? JavaScript IS NOT Java Created in 1995 by Netscape (LiveScript) ECMAScript standard JScript and ActionScript, also based on ECMAScript
  • 5. What is it ? JavaScript IS NOT Java Created in 1995 by Netscape (LiveScript) ECMAScript standard JScript and ActionScript, also based on ECMAScript Dynamic, Weakly typed
  • 6. What is it ? JavaScript IS NOT Java Created in 1995 by Netscape (LiveScript) ECMAScript standard JScript and ActionScript, also based on ECMAScript Dynamic, Weakly typed Object Oriented, Prototype based
  • 7. What is it ? JavaScript IS NOT Java Created in 1995 by Netscape (LiveScript) ECMAScript standard JScript and ActionScript, also based on ECMAScript Dynamic, Weakly typed Object Oriented, Prototype based Functional features
  • 8. What can we do with it ? Scripting language created for programmatic access of webpage objects
  • 9. What can we do with it ? Scripting language created for programmatic access of webpage objects Currently also used for: Application scripting Server side scripting
  • 10. JavaScript we see everyday This application (Google Docs)
  • 11. JavaScript we see everyday Gmail, SAPO Mail, Google Reader
  • 12. JavaScript we see everyday Rich text editors
  • 13. JavaScript we see everyday Ads
  • 14. JavaScript we see everyday Comment systems (SAPO Comments, Disqus)
  • 15. Why people hate it Bad uses Popup ads, annoying animations
  • 16. Why people hate it Bad uses Popup ads, annoying animations Bad practices lead to slower code
  • 17. Why people hate it Bad uses Popup ads, annoying animations Bad practices lead to slower code Many books advocated wrong practices for years Lots of bad tutorials and bad code all over the web People didn't want to learn, so they replicated the bad code
  • 18. Why developers hate it Standard is incoherent
  • 19. Why developers hate it Standard is incoherent Being solved !
  • 20. Why developers hate it Standard is incoherent Being solved ! Bad implementations
  • 21. Why developers hate it Standard is incoherent Being solved ! Bad implementations Browser differences
  • 22. Why developers hate it Standard is incoherent Being solved ! Bad implementations Browser differences However, it will take time...
  • 23. Learning the language Basic syntax is similar to C-like languages Code goes in .js files or HTML <script> tag Comments are the same as C alert("Hello world ! JavaScript is awesome !");
  • 24. Variables var hello = "world"; var keyword: local variable No need to declare types
  • 25. Variables Variable types Numbers var num = 1; Strings var str = "hi !"; Objects var obj = new Object(); Arrays var arr = ["string", 2]; Functions var fun = function() {}; Regexps var regexp = /^jssrocks/; Numbers, Strings, Regexps and Functions are really Objects
  • 26. Variables Be careful... "30a".parseInt(); "40.5".parseInt(); "40.5".parseFloat();
  • 27. Variables Strings Concatenation "Tiago" + " " + "Rodrigues"
  • 28. Variables Strings Concatenation "Tiago" + " " + "Rodrigues" typeof(26 + "px"); // string typeof 26; // number
  • 29. Variables Other values true, false null undefined
  • 30. Control structures Control structures if (cond) { ... } else { ... } while (cond) { ... } do { ... } while (cond); for (cond) { ... } switch (expr) { case ... : ... ; break; } try { ... } catch (exception) { ... }
  • 31. Learning the language Control structures for (var i=0; i<10; i++) { ... } for (var i in obj) { ... }
  • 32. Objects var obj = { property: value }
  • 33. Objects var obj = { "name": "content", other_name: 1, this_is_an_array: [1, 2, 3], "this-would-be": "wrong" } alert(obj.name); // content alert(obj["name"]); // content
  • 34. Functions function add(a, b) { return a + b; }
  • 35. Functions function add(a, b) { return a + b; } Wrong ! Function goes global !
  • 36. Functions function add(a, b) { return a + b; } Wrong ! Function goes global ! But functions are objects ! var add = function(a, b) { return a + b; }
  • 37. Functions var module = { add: function(a, b) { return a + b; }, sub: function(a, b) { return a - b; } } module.add(1, 2); // 3
  • 38. Context Why is context so important ? var fun = function(){ var num = 1; silly_var = 2; alert(num); // 1; } alert(num); // undefined alert(silly_var); // 2
  • 39. Context Why is context so important ? var module = { str: "blah", print: function() { alert(this.blah); } } module.print(); // blah However, this can be ambiguous, so be careful.
  • 40. Functional features Let's go functional ! var fun = function(callback) { callback(); } fun(function() { alert("I'm anonymous !"); });
  • 41. Closures var fun = function() { var num = 1; var inner = function() { alert(num); } inner(); // nothing happens...yet } fun(); // 1 inner(); // undefined
  • 42. Available objects Numbers, Strings, Arrays all have methods There are many more available objects: Math, Date, etc* * https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference
  • 43. Available objects Examples: var str = "Tiago Rodrigues"; str.split(" "); // ["Tiago", "Rodrigues"]; Math.sqrt(36); // 6 var arr = [4, 6, 3, 7]; arr.sort(); // [3, 4, 6, 7]
  • 44. Object orientation But JavaScript is Object Oriented So how do we create object instances ? We use prototypes !
  • 45. Classes Defining a class var Book = function(name) { this.init(name); } Book is a constructor
  • 46. Prototypes Let's add attributes and methods to our class Book.prototype = { name: "", // this is an attribute // this is a method init: function(name) { this.name = name; }, sayName: function() { alert(this.name); } };
  • 47. Prototypes So let's create some books var good_parts = Book("The Good Parts"); good_parts.sayName(); // The Good Parts var def_guide = Book("The Definitive Guide"); def_guide.sayName(); // The Definitive Guide
  • 48. Prototypes But why is this so great ? Book.prototype.removeName = function() { this.name = ""; } Extending default objects String.prototype.trim = function() { return this.replace(/^s+|s+$|n+$/g, ''); } " trim me ".trim(); // "trim me"
  • 49. The Document Object Model API for (X)HTML files Tree representation of all the objects in a file Each object has properties and methods Not the same in every browser Mostly IE not up to date
  • 50. The Document Object Model window represents your browser window document represents your current document document.forms is an array with all your form fields Many other objects are available
  • 51. Selecting objects <div id="content"> blah </div> var div = document.getElementById("content"); alert(content.innerHTML); // blah
  • 52. Event handling <a href="#" onClick="alert('hi')">click me</a> <a href="#" id="link">click me</a>
  • 53. Event handling <a href="#" onClick="alert('hi')">click me</a> <a href="#" id="link">click me</a> On the JS file: var lnk = document.getElementById("link"); if (lnk.addEventListener){ lnk.addEventListener( 'click', handler, false); } else if (lnk.attachEvent){ lnk.attachEvent('onclick', handler); }
  • 54. Object properties <a href="#" id="link">click me</a> On the JS file: var lnk = document.getElementById("link"); lnk.href = "file.html"; lnk.style.color = "#000";
  • 55. Basic output on a browser Alert alert("Hi !"); Confirm confirm("Are you there ?"); // returns true or false Prompt prompt("What's your name ?");
  • 56. Timing Flashing an alert box after 5 seconds setTimeout(function() { alert("click me !"); }, 5000);
  • 57. Timing Flashing an alert box after 5 seconds setTimeout(function() { alert("click me !"); }, 5000); Flashing a box every 5 seconds var int = setInterval(function() { if(confirm("Stop ?")) { clearInterval(int); } }, 5000);
  • 58. JSON     JavaScript Object Notation * { "name" : "Tiago Rodrigues", "age" : 24, "profession" : "JavaScript developer" } Other languages have similar structures There are libraries available on every popular language * http://json.org
  • 59. Ajax Asynchronous Javascript And XML* Fetching content through JavaScript with the use of the XMLHttpRequest object Server doesn't send an entire page, only what's needed Insert the content in the current page through JavaScript * http://adaptivepath.com/ideas/essays/archives/000385.php
  • 61. Ajax Content can be HTML XML JSON
  • 62. Libraries and frameworks Extend the base language Abstract browser differences Selectors Events AJAX Add widgets and reusable modules
  • 63. Libraries and frameworks Problems Many library users don't learn the base language
  • 64. Libraries and frameworks Problems Many library users don't learn the base language Because of this, they abuse the base language
  • 65. Libraries and frameworks Problems Many library users don't learn the base language Because of this, they abuse the base language This leads to performance problems
  • 66. Libraries and frameworks Problems Many library users don't learn the base language Because of this, they abuse the base language This leads to performance problems So...be careful !
  • 67. Libraries and frameworks Prototype / script.aculo.us jQuery / jQuery UI Dojo LibSAPO.js Many others: extjs, Mootools, etc Ajaxian* has a great list * http://ajaxian.com
  • 68. Good practices Unobtrusive JavaScript Not blocking possible actions Making them available without JavaScript Progressive Enhancement and Graceful Degradation Build your website with no JavaScript at all Add it later to improve user experience This way, the website will degrade gracefully Verify your code ! http://jslint.com/ * http://andr3.net/blog/post/141
  • 69. Other uses Server Side JS Narwhal Node.js Adobe AIR / Tweetanium Extensões Google Chrome Extensões Mozilla Firefox (Jetpack) Phonegap, Mojo, W3C Widgets (Opera widgets) Platform scripting .NET J2EE (Rhino)
  • 70. References Books JavaScript: The Definitive Guide JavaScript: The Good Parts http://javascript.crockford.com http://developer.mozilla.org