SlideShare ist ein Scribd-Unternehmen logo
1 von 17
JavaScript Patterns

      Part Two
Error Objects


Built-in's you can throw
 ● Error, SyntaxError, TypeError, RangeError, etc.
 ● can be used with or without 'new'


All have properties
 ● name - of constructor
 ● message - string passed in constructor
 ● and others that are not universally supported


You can 'throw' any object
 ● add 'name' and 'message' to be consistent
 ● plus any other properties you want
 ● preferred method
The console


Use FireBug CommandEditor to experiment

LOG outputs traces
console.log("test", 1, {}, [1,2,3]);


DIR outputs enumerations
console.dir({one:1, two: {three: 3}});


ACCESS
window.name === window['name'];
Minimizing Globals


myglobal = "hello";
 ● makes a property on window


console.log(myglobal);
 ● the global 'this' is implied


console.log(window.myglobal);


console.log(window['myglobal']);


console.log(this.myglobal);
Implied Globals


Any variable you don't declare with var becomes property of global


this is bad
function sum(x,y){
result = x+y;
return result;
}


this is good
function sum(x,y){
var result = x+y;
return result;
}
Implied Globals (cont.)


Implied globals are not real variables, rather properties of the global object


this is bad
function foo(){
var a = b = 0;
}


this is good
function foo(){
var a, b;
a = b = 0;
}
Delete


Global variables, created with var, cannot be deleted


Global properties (declared without var) can be deleted


In general
  ● properties can be deleted
  ● variables can not be deleted
Accessing global object


from anywhere via 'window'


*don't EVER declare a local var using the word 'window'


to access global without using 'window' you can do the following from
anywhere, any level of nested scope:


....(){
    var G = (function(){
        return this;
    }());
Single var pattern


single place to look for all local variables


prevents logical errors: when a var is used before it's defined


helps minimize globals/implied globals


less code to write - only 1 'var' statement


can initialize if you want to
Single var pattern (cont.)


another good example of doing work in single var


can initialize and chain


function updateElement(){
  var element = document.getElementById("result"),
       style = element.style;
}
Variable Hoisting


you can put a 'var' statement anywhere in a function


but you shouldn't


all vars will all act as if they were declared at top of function
Loops


optimizing 'for'


least optimal:
for(var i = 0; i < myarray.length; i++){}


especially bad for dom collections since they are live queries
which are very expensive


better:
for(var i = 0, max = myarray.length; i < max; i++){}
Loops (cont.)


'for in' enumeration


use hasOwnProperty() to filter out the prototype properties


call it from the object you are iterating over
OR
from the prototype of Object
  ● avoids collisions with any redefinition of hasOwnProperty
  ● cached version of this can avoid an iterative long   property lookup
    all the way up the prototype chain
Types

There are 5 primitives:
    1. number
    2. string
    3. boolean
    4. null
    5. undefined


Primitives are NOT objects
     ○ no properties
     ○ no methods
     ○ however....there is temporary conversion


Literals are not necessarily primitives
  ● { } and [ ] are literals - not primitives
  ● "s", true, 3 are literals - are primitives
Types (cont.)


conversion


   ● parseInt(string, radix)
      ○ converts a string to a number
      ○ do not leave out the radix!
          ■ strings that begin with '0' are treated as octal
      ○ there are other ways to convert a string that are faster
but not be able to handle compound strings
like "08 hello"
Literals


{}, [], "", 3, true , / /


advantages over the built-in constructors
 ● more concise
 ● more expressive
 ● less error-prone
 ● emphasizes the fact that objects are mutable hashes, not classes


constructors can be deceitful
 ● new Object("hello") creates an object using the String constructor
Primitives


difference between number primitive and Number wrapper object


the primitive object wrappers have some useful functions,
but the literals are converted at runtime


if you need to augment the value and persist state, then use the wrapper -
primitives can not do this


wrappers without 'new' can be used to convert values to primitives

Weitere ähnliche Inhalte

Was ist angesagt?

Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
Charndeep Sekhon
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
Danial Mirza
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
abhay singh
 
What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 

Was ist angesagt? (20)

C# 4.0 dynamic
C# 4.0 dynamicC# 4.0 dynamic
C# 4.0 dynamic
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
oojs
oojsoojs
oojs
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享
 
Scala functions
Scala functionsScala functions
Scala functions
 
Type conversions
Type conversionsType conversions
Type conversions
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 

Andere mochten auch (17)

iOS release engineering
iOS release engineeringiOS release engineering
iOS release engineering
 
Clean Code
Clean CodeClean Code
Clean Code
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Android security
Android securityAndroid security
Android security
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Code Kata
Code KataCode Kata
Code Kata
 
Classic Mistakes
Classic MistakesClassic Mistakes
Classic Mistakes
 
JavaScript: The Good Parts
JavaScript: The Good PartsJavaScript: The Good Parts
JavaScript: The Good Parts
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part  1JavaScript: Patterns, Part  1
JavaScript: Patterns, Part 1
 
OpenGL ES on Android
OpenGL ES on AndroidOpenGL ES on Android
OpenGL ES on Android
 
Function Points
Function PointsFunction Points
Function Points
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
 
iOS App Dev
iOS App Dev iOS App Dev
iOS App Dev
 

Ähnlich wie JavaScript: Patterns, Part 2

gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
Javascript part1
Javascript part1Javascript part1
Javascript part1
Raghu nath
 

Ähnlich wie JavaScript: Patterns, Part 2 (20)

JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Java script
Java scriptJava script
Java script
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Aspdot
AspdotAspdot
Aspdot
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript part1
Javascript part1Javascript part1
Javascript part1
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Javascript
JavascriptJavascript
Javascript
 

Kürzlich hochgeladen

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
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 

JavaScript: Patterns, Part 2

  • 2. Error Objects Built-in's you can throw ● Error, SyntaxError, TypeError, RangeError, etc. ● can be used with or without 'new' All have properties ● name - of constructor ● message - string passed in constructor ● and others that are not universally supported You can 'throw' any object ● add 'name' and 'message' to be consistent ● plus any other properties you want ● preferred method
  • 3. The console Use FireBug CommandEditor to experiment LOG outputs traces console.log("test", 1, {}, [1,2,3]); DIR outputs enumerations console.dir({one:1, two: {three: 3}}); ACCESS window.name === window['name'];
  • 4. Minimizing Globals myglobal = "hello"; ● makes a property on window console.log(myglobal); ● the global 'this' is implied console.log(window.myglobal); console.log(window['myglobal']); console.log(this.myglobal);
  • 5. Implied Globals Any variable you don't declare with var becomes property of global this is bad function sum(x,y){ result = x+y; return result; } this is good function sum(x,y){ var result = x+y; return result; }
  • 6. Implied Globals (cont.) Implied globals are not real variables, rather properties of the global object this is bad function foo(){ var a = b = 0; } this is good function foo(){ var a, b; a = b = 0; }
  • 7. Delete Global variables, created with var, cannot be deleted Global properties (declared without var) can be deleted In general ● properties can be deleted ● variables can not be deleted
  • 8. Accessing global object from anywhere via 'window' *don't EVER declare a local var using the word 'window' to access global without using 'window' you can do the following from anywhere, any level of nested scope: ....(){ var G = (function(){ return this; }());
  • 9. Single var pattern single place to look for all local variables prevents logical errors: when a var is used before it's defined helps minimize globals/implied globals less code to write - only 1 'var' statement can initialize if you want to
  • 10. Single var pattern (cont.) another good example of doing work in single var can initialize and chain function updateElement(){ var element = document.getElementById("result"), style = element.style; }
  • 11. Variable Hoisting you can put a 'var' statement anywhere in a function but you shouldn't all vars will all act as if they were declared at top of function
  • 12. Loops optimizing 'for' least optimal: for(var i = 0; i < myarray.length; i++){} especially bad for dom collections since they are live queries which are very expensive better: for(var i = 0, max = myarray.length; i < max; i++){}
  • 13. Loops (cont.) 'for in' enumeration use hasOwnProperty() to filter out the prototype properties call it from the object you are iterating over OR from the prototype of Object ● avoids collisions with any redefinition of hasOwnProperty ● cached version of this can avoid an iterative long property lookup all the way up the prototype chain
  • 14. Types There are 5 primitives: 1. number 2. string 3. boolean 4. null 5. undefined Primitives are NOT objects ○ no properties ○ no methods ○ however....there is temporary conversion Literals are not necessarily primitives ● { } and [ ] are literals - not primitives ● "s", true, 3 are literals - are primitives
  • 15. Types (cont.) conversion ● parseInt(string, radix) ○ converts a string to a number ○ do not leave out the radix! ■ strings that begin with '0' are treated as octal ○ there are other ways to convert a string that are faster but not be able to handle compound strings like "08 hello"
  • 16. Literals {}, [], "", 3, true , / / advantages over the built-in constructors ● more concise ● more expressive ● less error-prone ● emphasizes the fact that objects are mutable hashes, not classes constructors can be deceitful ● new Object("hello") creates an object using the String constructor
  • 17. Primitives difference between number primitive and Number wrapper object the primitive object wrappers have some useful functions, but the literals are converted at runtime if you need to augment the value and persist state, then use the wrapper - primitives can not do this wrappers without 'new' can be used to convert values to primitives