SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 

Tendances (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
 

En vedette (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
 

Similaire à "Javascript" por Tiago Rodrigues

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
Javascript Ks
Javascript KsJavascript Ks
Javascript Ks
ssetem
 

Similaire à "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
 

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

Plus 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
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

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...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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 ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

"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