SlideShare a Scribd company logo
JavaScript OMG!




          An introduction to the unusual
           and unexpected features of
                   JavaScript.

Bart.Wullems@ordina.be                  http://bartwullems.blogspot.com

                         www.visug.be
Introduction
• JavaScript(originally LiveScript) was
  developed by Brendan Eich of Netscape.
• He achieved this in a 6 weeks period…
• …for some parts he did an amazing job
• …for other parts it was…euhm… „less
  amazing‟ 
• EcmaScript 5 tries to solve most of the
  problems that JavaScript has today(and
  jQuery helps too…)
                   www.visug.be
www.visug.be
OMG #1 – Optional Semicolons
• Interpreter can try to figure out the end of
  statements
• WARNING: some dangerous edge cases
  exist!
  – E.g. Return keyword




                    www.visug.be
OMG #2 – Type System
• JavaScript types are primitive types or
  object types.
• Primitive types are Number, Boolean and
  String
• Number is a 64-bit floating point value
  – Challenge in building scientific/financial
    applications
  – No .NET‟s Decimal type to help out.
• There‟s also two other values null and
  undefined which are both values and types
                        www.visug.be
OMG #2 – Type System
• TypeOf
  – Returns the type of an instance of a fundamental
    type.
  – If it is not a fundamental type, typeof will return
    „Object‟:
• InstanceOf
  – Returns whether the object was constructed
    using the specified constructor.
  – Useful when attempting to check the type of one
    of your own defined object types.
  – Misleading if you create an instance of one of the
    built-in types using literal syntax.
                        www.visug.be
OMG #3 –
 Underflow, Overflow, Div by Zero
• Divide by zero does not throw any kind of
  error or exception
• Divide by zero returns an infinite value
• Divide zero by zero returns NaN
• 2 helpful functions:
  – isNan()
  – isFinite()


                   www.visug.be
OMG #4 – Regular Expressions
• JavaScript has built in support for regular
  expressions




                    www.visug.be
OMG #5 – Truthy and Falsy
• Everything is true unless it‟s:
  – Undefined, null, 0, -0, NaN, “”
• Can get tricky when converting from one
  type to another




                      www.visug.be
OMG #6 – The Global Object
• There IS a Global Object.
• Defining global variables and global
  functions means mutating the global
  object.




                   www.visug.be
OMG #7 – Expando Objects
• JavaScript has the very powerful/scary
  system which allows you to just expand
  objects with new properties
  – (unless those objects have been marked to
    disallow it)
• Reminder: Everything is an object!



                    www.visug.be
OMG #8 – Wrappers
• Wrapper objects = process of “boxing” in
  .NET.
• Treat primitive types not as objects to
  increase performance, use it as an object
  only when needed
• In JavaScript, this seems to called
  “Wrapper Objects” and it allows to treat a
  primitive like an object.

                   www.visug.be
OMG #9 – Type Conversions
• JavaScript has a pretty complex list of type
  conversions.
• Most of them are pretty intuitive.




                    www.visug.be
OMG #10 – Object to Primitive
          Conversions
• Objects convert to booleans very naturally by
  converting to true for every value that‟s not
  null or undefined.
• Converting objects to strings goes via
  toString() and then if that isn‟t appropriate
  (i.e. doesn‟t give some primitive value that
  can be converted to a string or doesn‟t exist)
  then it goes via valueOf() to try and get to
  some primitive value.

                     www.visug.be
OMG #11 – Variable scope and
           hoisting
• JavaScript has function scope instead of
  block scope.
• JavaScript will move all variable
  declarations to the beginning of the
  function scope.




                   www.visug.be
OMG #12 – Bitwise Operators
• The bitwise operators in the language
  behave as though they are working on 32-
  bit integers rather than as though they
  were working on 64-bit floating point
  values.




                  www.visug.be
OMG #13 – Equality and Strict
            Equality
• There are 2 ways to check equality in
  JavaScript. There‟s the regular “==” and
  then there‟s the “===”
• Use === or the “strict equality operator”
  – Comes with no surprises;




                    www.visug.be
OMG #14 – Use Strict
• Start using the “use strict” directive
  brought in for ECMAScript5
• Brings a long list of changes to the
  language (e.g. “all variables must be
  declared”, “it is a syntax error for a
  function declaration to have two or more
  parameters with the same name”) and so
  on.
• Windows 8 supports it already

                   www.visug.be
OMG #15 – Magic of Short-
  Circuiting ANDs and Truthy/Falsy
• In a language like C# it can be quite
  painful to index into a complex object
  model while all the time trying to protect
  yourself from the pains of a null reference
  exception.
• The magic of the AND operator returning
  the right value at the right time makes this
  a lot easier in JavaScript.

                    www.visug.be
OMG #16 – Function arguments
• JavaScript functions allow for very flexible
  argument usage (way beyond optional and
  named arguments).




                    www.visug.be
OMG #17 – Nested functions
• Define functions inside of functions
  and, optionally, form closures over the
  local variable state.




                    www.visug.be
OMG #18 – Arrays vs Lists
• JavaScript Arrays feel more like .NET‟s
  ArrayList in many ways.
  – You can just add things to an array whenever
    and wherever you feel like it;




                     www.visug.be
OMG #19 – Function Invocation
            Context
• If writing a plain old, vanilla function then
  the this pointer is set to the global object.
• ES5 strict mode comes along and try to
  tidy this up.




                    www.visug.be
OMG #20 – Nested functions and
      invocation context
• If I have a nested function inside a
  method then even it picks up the global
  object for its invocation context unless I‟m
  in strict mode when it throws an error.
• Pick up the this pointer yourself such that
  the nested function captures it.



                    www.visug.be
OMG #21 – Everything‟s a Function
• JavaScript allows the basic types of the
  language to be augmented.
• Adding a method to Object.prototype makes
  that method available to all objects.
• This also works for
  functions, arrays, strings, numbers, regular
  expressions, and booleans.
• For example, by augmenting
  Function.prototype, we can make a method
  available to all functions.
                    www.visug.be
OMG #22 – array.sort() won‟t sort
      numbers “correctly”
• The sort method sorts the contents of an array in
  place. It sorts arrays of numbers incorrectly.
• JavaScript‟s default comparison function assumes
  that the elements to be sorted are strings.
• Fortunately, you may replace the comparison
  function with your own.
  – Your comparison function should take two parameters
    and return 0 if the two parameters are equal, a
    negative number if the first parameter should come
    first, and a positive number if the second parameter
    should come first.

                        www.visug.be
OMG #23 – parseInt() needs help
• parseInt is a function that converts a string
  into an integer.
• It stops when it sees a nondigit, so
  parseInt("16") and parseInt("16 tons")
  produce the same result.
• If the first character of the string is 0, then
  the string is evaluated in base 8 instead of
  base 10. times.
• parseInt can take a radix
  parameter, recommendation to always
  provide it          www.visug.be
OMG #24 – Callbacks and Scope
• Callbacks and scope are not completely
  similar to C#
• Callbacks needs a pointer to the instance
  object(not required in C#)




                   www.visug.be
OMG #25 – ADVANCED: Function
    Literals Create Functions
• Functions are created for every instance of
  an object
  – Unless the function is defined on the
    prototype object




                      www.visug.be
OMG #26 – ADVANCED: Partial
     Application & Mapping
• What if we need a function where one of
  the operator‟s arguments is already given?
• For cases like that, something called
  partial application is useful.
• We want to take a function X and one or
  more arguments and then create a new
  function that calls X with both the original
  arguments and any newly passed ones.
• Very usefull in map-reduce context
                    www.visug.be
OMG #27 – ADVANCED: “Self
       Defining” Functions
• If you create a new function and assign it to
  the same variable that already holds another
  function, you‟re overwriting the old function.
• If you do this inside the body of the old
  function, the function overwrites and
  redefines itself
• Useful when your function has some initial
  peparatory work to do and it needs to do it
  only once. The self-defining function can
  update its own implementation.
                     www.visug.be
OMG #28 – ADVANCED: This or
             That?
• Same rules as for functions in OMG #24
  apply to events




                  www.visug.be
OMG #29 – String replace
• .replace method on strings replaces by
  default only the first match
• To replace all matches, you must use a
  Regular Expression and add the global
  modifier




                   www.visug.be
OMG #30 – The + operator
• In JavaScript + always results in
  concatenation when either of the
  operands is a string.
• This might catch you out if you're trying to
  add a number to, say, the contents of an
  input element (which will be a string), so
  you need to first cast to Number.


                    www.visug.be
OMG #31 – The new keyword
• JavaScript has the types Object, Array, Boolean, Number, String, and
  Function.
    – The explicit constructor is never required.
    – If you use the new keyword to construct one of these types, what you
      actually get is an object of type Object that inherits the prototype of the
      type you want to construct (the exception is Function).
    – Always use the literal syntax constructing one of these types to avoid
      any confusion.
• If you write your own constructor function and forget to include the
  new keyword, then bad things happen:
    – Calling a function with the new keyword creates a new object and then
      calls the function with that new object as its context. The object is then
      returned.
    – Calling a function without 'new' will result in the context being the
      global object if that function is not invoked on an object (which it won't
      be anyway if it's used as a constructor!)



                                   www.visug.be
OMG #32 – There is no integer
• Numerical calculations are comparatively
  slow because there is no Integer
  type, only Number
• Number is an IEEE floating point double-
  precision (64 bit) type.
• This exhibits some floating point rounding
  errors.


                   www.visug.be
OMG #33 – NaN
• The type of NaN (Not a Number) is...
  Number.
• NaN compared to anything is false.
• The only way to test whether a number is
  equal to NaN is with the helper function
  isNaN().



                   www.visug.be
OMG #34 – The arguments object
• Within a function, you can reference the
  arguments object to retrieve the list of arguments.
   – This object is not an Array but an array-like object.
   – Use the array splice function to create an array from
     the properties in arguments:
• When a function has explicit arguments in its
  signature, they can be reassigned and the
  arguments object will also be changed.
   – You can't rely on arguments to give you their original
     values.
   – In ES5 strict mode, arguments will always point to the
     original input argument values, as opposed to their
     current values.
                          www.visug.be
QUESTIONS?


         www.visug.be
Resources
•   Mike Taulty Javascript OMG!
•   A Collection of JavaScript Gotchas
•   WTF JS
•   A survey of the JavaScript programming
    language




                    www.visug.be

More Related Content

PPTX
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
PPTX
Exploring Kotlin language basics for Android App development
PDF
Metaprogramming with javascript
PPTX
JavaScript operators
PDF
Model with actors and implement with Akka
PPTX
Object Oriented Programming In JavaScript
PPTX
Airbnb Javascript Style Guide
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Exploring Kotlin language basics for Android App development
Metaprogramming with javascript
JavaScript operators
Model with actors and implement with Akka
Object Oriented Programming In JavaScript
Airbnb Javascript Style Guide

What's hot (20)

PDF
Paris Web - Javascript as a programming language
PDF
Functional Programming in Java
PPTX
AngularConf2015
PDF
Intro to javascript (4 week)
PPTX
JavaScript in Object-Oriented Way
ODP
Object Oriented Javascript
PPTX
Why I don’t want to develop iOS apps in Objective C
PDF
Advanced Reflection in Pharo
PPTX
Getting started with typescript
PPTX
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
PDF
TypeScript for Java Developers
PDF
TypeScript 2 in action
PPTX
2CPP04 - Objects and Classes
PDF
Reflection in Pharo: Beyond Smalltak
PDF
Advanced JavaScript - Internship Presentation - Week6
PDF
15 Minutes Null
PDF
Dynamically Composing Collection Operations through Collection Promises
PDF
Variables in Pharo5
PDF
Metaprogramming JavaScript
Paris Web - Javascript as a programming language
Functional Programming in Java
AngularConf2015
Intro to javascript (4 week)
JavaScript in Object-Oriented Way
Object Oriented Javascript
Why I don’t want to develop iOS apps in Objective C
Advanced Reflection in Pharo
Getting started with typescript
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
TypeScript for Java Developers
TypeScript 2 in action
2CPP04 - Objects and Classes
Reflection in Pharo: Beyond Smalltak
Advanced JavaScript - Internship Presentation - Week6
15 Minutes Null
Dynamically Composing Collection Operations through Collection Promises
Variables in Pharo5
Metaprogramming JavaScript
Ad

Viewers also liked (15)

PPT
Social Software and the Day School Librarian
PPT
Bb7 Sneak Peek
PDF
Analyzing probabilistic models in hierarchical BOA on traps and spin glasses
PPT
Verwaltung.Modern@Kehl
PPT
Reunion con Ruben R. (Vicepresidente C.PS.)
PDF
Silvio Bolsas ApresentaçãO
PPS
Humor Acido
PPTX
Techorama - Evolvable Application Development with MongoDB
PPTX
Git(hub) for windows developers
PDF
JavaScript Libraries: The Big Picture
PPTX
Tfs Monitor Windows Phone 7 App
PPTX
Building an enterprise app in silverlight 4 and NHibernate
PPTX
Convention over configuration in .Net 4.0
PPTX
Caliburn.micro
PPTX
Modyul2 angdaigdigsaklasikalattransisyunalnapanahon-140807210600-phpapp01
Social Software and the Day School Librarian
Bb7 Sneak Peek
Analyzing probabilistic models in hierarchical BOA on traps and spin glasses
Verwaltung.Modern@Kehl
Reunion con Ruben R. (Vicepresidente C.PS.)
Silvio Bolsas ApresentaçãO
Humor Acido
Techorama - Evolvable Application Development with MongoDB
Git(hub) for windows developers
JavaScript Libraries: The Big Picture
Tfs Monitor Windows Phone 7 App
Building an enterprise app in silverlight 4 and NHibernate
Convention over configuration in .Net 4.0
Caliburn.micro
Modyul2 angdaigdigsaklasikalattransisyunalnapanahon-140807210600-phpapp01
Ad

Similar to Javascript omg! (20)

PDF
Javascript for Intermediates
PPTX
IP Unit 2.pptx
PPTX
JavaScripts internals #1
PPT
Web development basics (Part-7)
PPTX
WT Unit-3 PPT.pptx
PDF
JavaScript Interview Questions Part - 1.pdf
PPTX
Java script
PDF
Kevin Whinnery: Write Better JavaScript
PPTX
Java script basics
KEY
Exciting JavaScript - Part I
ODP
JavaScript Object Oriented Programming Cheat Sheet
PPTX
AngularJS Beginners Workshop
PDF
New c sharp4_features_part_v
PPTX
Lecture 4- Javascript Function presentation
PDF
l2-es6-160830040119.pdf
PPTX
Implementing a JavaScript Engine
PDF
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
PPTX
Better Page Object Handling with Loadable Component Pattern
PPT
Presentation JavaScript Introduction Data Types Variables Control Structure
PDF
Integrating AngularJS into the Campus CMS
Javascript for Intermediates
IP Unit 2.pptx
JavaScripts internals #1
Web development basics (Part-7)
WT Unit-3 PPT.pptx
JavaScript Interview Questions Part - 1.pdf
Java script
Kevin Whinnery: Write Better JavaScript
Java script basics
Exciting JavaScript - Part I
JavaScript Object Oriented Programming Cheat Sheet
AngularJS Beginners Workshop
New c sharp4_features_part_v
Lecture 4- Javascript Function presentation
l2-es6-160830040119.pdf
Implementing a JavaScript Engine
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern
Presentation JavaScript Introduction Data Types Variables Control Structure
Integrating AngularJS into the Campus CMS

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Modernizing your data center with Dell and AMD
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
cuic standard and advanced reporting.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
Encapsulation_ Review paper, used for researhc scholars
Chapter 3 Spatial Domain Image Processing.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Monthly Chronicles - July 2025
Per capita expenditure prediction using model stacking based on satellite ima...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Modernizing your data center with Dell and AMD
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The AUB Centre for AI in Media Proposal.docx
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
cuic standard and advanced reporting.pdf
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding

Javascript omg!

  • 1. JavaScript OMG! An introduction to the unusual and unexpected features of JavaScript. Bart.Wullems@ordina.be http://bartwullems.blogspot.com www.visug.be
  • 2. Introduction • JavaScript(originally LiveScript) was developed by Brendan Eich of Netscape. • He achieved this in a 6 weeks period… • …for some parts he did an amazing job • …for other parts it was…euhm… „less amazing‟  • EcmaScript 5 tries to solve most of the problems that JavaScript has today(and jQuery helps too…) www.visug.be
  • 4. OMG #1 – Optional Semicolons • Interpreter can try to figure out the end of statements • WARNING: some dangerous edge cases exist! – E.g. Return keyword www.visug.be
  • 5. OMG #2 – Type System • JavaScript types are primitive types or object types. • Primitive types are Number, Boolean and String • Number is a 64-bit floating point value – Challenge in building scientific/financial applications – No .NET‟s Decimal type to help out. • There‟s also two other values null and undefined which are both values and types www.visug.be
  • 6. OMG #2 – Type System • TypeOf – Returns the type of an instance of a fundamental type. – If it is not a fundamental type, typeof will return „Object‟: • InstanceOf – Returns whether the object was constructed using the specified constructor. – Useful when attempting to check the type of one of your own defined object types. – Misleading if you create an instance of one of the built-in types using literal syntax. www.visug.be
  • 7. OMG #3 – Underflow, Overflow, Div by Zero • Divide by zero does not throw any kind of error or exception • Divide by zero returns an infinite value • Divide zero by zero returns NaN • 2 helpful functions: – isNan() – isFinite() www.visug.be
  • 8. OMG #4 – Regular Expressions • JavaScript has built in support for regular expressions www.visug.be
  • 9. OMG #5 – Truthy and Falsy • Everything is true unless it‟s: – Undefined, null, 0, -0, NaN, “” • Can get tricky when converting from one type to another www.visug.be
  • 10. OMG #6 – The Global Object • There IS a Global Object. • Defining global variables and global functions means mutating the global object. www.visug.be
  • 11. OMG #7 – Expando Objects • JavaScript has the very powerful/scary system which allows you to just expand objects with new properties – (unless those objects have been marked to disallow it) • Reminder: Everything is an object! www.visug.be
  • 12. OMG #8 – Wrappers • Wrapper objects = process of “boxing” in .NET. • Treat primitive types not as objects to increase performance, use it as an object only when needed • In JavaScript, this seems to called “Wrapper Objects” and it allows to treat a primitive like an object. www.visug.be
  • 13. OMG #9 – Type Conversions • JavaScript has a pretty complex list of type conversions. • Most of them are pretty intuitive. www.visug.be
  • 14. OMG #10 – Object to Primitive Conversions • Objects convert to booleans very naturally by converting to true for every value that‟s not null or undefined. • Converting objects to strings goes via toString() and then if that isn‟t appropriate (i.e. doesn‟t give some primitive value that can be converted to a string or doesn‟t exist) then it goes via valueOf() to try and get to some primitive value. www.visug.be
  • 15. OMG #11 – Variable scope and hoisting • JavaScript has function scope instead of block scope. • JavaScript will move all variable declarations to the beginning of the function scope. www.visug.be
  • 16. OMG #12 – Bitwise Operators • The bitwise operators in the language behave as though they are working on 32- bit integers rather than as though they were working on 64-bit floating point values. www.visug.be
  • 17. OMG #13 – Equality and Strict Equality • There are 2 ways to check equality in JavaScript. There‟s the regular “==” and then there‟s the “===” • Use === or the “strict equality operator” – Comes with no surprises; www.visug.be
  • 18. OMG #14 – Use Strict • Start using the “use strict” directive brought in for ECMAScript5 • Brings a long list of changes to the language (e.g. “all variables must be declared”, “it is a syntax error for a function declaration to have two or more parameters with the same name”) and so on. • Windows 8 supports it already www.visug.be
  • 19. OMG #15 – Magic of Short- Circuiting ANDs and Truthy/Falsy • In a language like C# it can be quite painful to index into a complex object model while all the time trying to protect yourself from the pains of a null reference exception. • The magic of the AND operator returning the right value at the right time makes this a lot easier in JavaScript. www.visug.be
  • 20. OMG #16 – Function arguments • JavaScript functions allow for very flexible argument usage (way beyond optional and named arguments). www.visug.be
  • 21. OMG #17 – Nested functions • Define functions inside of functions and, optionally, form closures over the local variable state. www.visug.be
  • 22. OMG #18 – Arrays vs Lists • JavaScript Arrays feel more like .NET‟s ArrayList in many ways. – You can just add things to an array whenever and wherever you feel like it; www.visug.be
  • 23. OMG #19 – Function Invocation Context • If writing a plain old, vanilla function then the this pointer is set to the global object. • ES5 strict mode comes along and try to tidy this up. www.visug.be
  • 24. OMG #20 – Nested functions and invocation context • If I have a nested function inside a method then even it picks up the global object for its invocation context unless I‟m in strict mode when it throws an error. • Pick up the this pointer yourself such that the nested function captures it. www.visug.be
  • 25. OMG #21 – Everything‟s a Function • JavaScript allows the basic types of the language to be augmented. • Adding a method to Object.prototype makes that method available to all objects. • This also works for functions, arrays, strings, numbers, regular expressions, and booleans. • For example, by augmenting Function.prototype, we can make a method available to all functions. www.visug.be
  • 26. OMG #22 – array.sort() won‟t sort numbers “correctly” • The sort method sorts the contents of an array in place. It sorts arrays of numbers incorrectly. • JavaScript‟s default comparison function assumes that the elements to be sorted are strings. • Fortunately, you may replace the comparison function with your own. – Your comparison function should take two parameters and return 0 if the two parameters are equal, a negative number if the first parameter should come first, and a positive number if the second parameter should come first. www.visug.be
  • 27. OMG #23 – parseInt() needs help • parseInt is a function that converts a string into an integer. • It stops when it sees a nondigit, so parseInt("16") and parseInt("16 tons") produce the same result. • If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. times. • parseInt can take a radix parameter, recommendation to always provide it www.visug.be
  • 28. OMG #24 – Callbacks and Scope • Callbacks and scope are not completely similar to C# • Callbacks needs a pointer to the instance object(not required in C#) www.visug.be
  • 29. OMG #25 – ADVANCED: Function Literals Create Functions • Functions are created for every instance of an object – Unless the function is defined on the prototype object www.visug.be
  • 30. OMG #26 – ADVANCED: Partial Application & Mapping • What if we need a function where one of the operator‟s arguments is already given? • For cases like that, something called partial application is useful. • We want to take a function X and one or more arguments and then create a new function that calls X with both the original arguments and any newly passed ones. • Very usefull in map-reduce context www.visug.be
  • 31. OMG #27 – ADVANCED: “Self Defining” Functions • If you create a new function and assign it to the same variable that already holds another function, you‟re overwriting the old function. • If you do this inside the body of the old function, the function overwrites and redefines itself • Useful when your function has some initial peparatory work to do and it needs to do it only once. The self-defining function can update its own implementation. www.visug.be
  • 32. OMG #28 – ADVANCED: This or That? • Same rules as for functions in OMG #24 apply to events www.visug.be
  • 33. OMG #29 – String replace • .replace method on strings replaces by default only the first match • To replace all matches, you must use a Regular Expression and add the global modifier www.visug.be
  • 34. OMG #30 – The + operator • In JavaScript + always results in concatenation when either of the operands is a string. • This might catch you out if you're trying to add a number to, say, the contents of an input element (which will be a string), so you need to first cast to Number. www.visug.be
  • 35. OMG #31 – The new keyword • JavaScript has the types Object, Array, Boolean, Number, String, and Function. – The explicit constructor is never required. – If you use the new keyword to construct one of these types, what you actually get is an object of type Object that inherits the prototype of the type you want to construct (the exception is Function). – Always use the literal syntax constructing one of these types to avoid any confusion. • If you write your own constructor function and forget to include the new keyword, then bad things happen: – Calling a function with the new keyword creates a new object and then calls the function with that new object as its context. The object is then returned. – Calling a function without 'new' will result in the context being the global object if that function is not invoked on an object (which it won't be anyway if it's used as a constructor!) www.visug.be
  • 36. OMG #32 – There is no integer • Numerical calculations are comparatively slow because there is no Integer type, only Number • Number is an IEEE floating point double- precision (64 bit) type. • This exhibits some floating point rounding errors. www.visug.be
  • 37. OMG #33 – NaN • The type of NaN (Not a Number) is... Number. • NaN compared to anything is false. • The only way to test whether a number is equal to NaN is with the helper function isNaN(). www.visug.be
  • 38. OMG #34 – The arguments object • Within a function, you can reference the arguments object to retrieve the list of arguments. – This object is not an Array but an array-like object. – Use the array splice function to create an array from the properties in arguments: • When a function has explicit arguments in its signature, they can be reassigned and the arguments object will also be changed. – You can't rely on arguments to give you their original values. – In ES5 strict mode, arguments will always point to the original input argument values, as opposed to their current values. www.visug.be
  • 39. QUESTIONS? www.visug.be
  • 40. Resources • Mike Taulty Javascript OMG! • A Collection of JavaScript Gotchas • WTF JS • A survey of the JavaScript programming language www.visug.be