Javascript omg!


Published on

This session is an introduction to the weird side of JavaScript, and it definitely has a weird side! .NET developers will find a lot of intriguing "features" when they begin to write code in the world's most widely used language. Join us to learn about all the gotchas to watch out for and discover some of the great functionality that JavaScript has to offer…

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Javascript omg!

  1. 1. JavaScript OMG! An introduction to the unusual and unexpected features of
  2. 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…)
  3. 3.
  4. 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
  5. 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
  6. 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.
  7. 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()
  8. 8. OMG #4 – Regular Expressions• JavaScript has built in support for regular expressions
  9. 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
  10. 10. OMG #6 – The Global Object• There IS a Global Object.• Defining global variables and global functions means mutating the global object.
  11. 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!
  12. 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.
  13. 13. OMG #9 – Type Conversions• JavaScript has a pretty complex list of type conversions.• Most of them are pretty intuitive.
  14. 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.
  15. 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.
  16. 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.
  17. 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;
  18. 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
  19. 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.
  20. 20. OMG #16 – Function arguments• JavaScript functions allow for very flexible argument usage (way beyond optional and named arguments).
  21. 21. OMG #17 – Nested functions• Define functions inside of functions and, optionally, form closures over the local variable state.
  22. 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;
  23. 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.
  24. 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.
  25. 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.
  26. 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.
  27. 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
  28. 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#)
  29. 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
  30. 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
  31. 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.
  32. 32. OMG #28 – ADVANCED: This or That?• Same rules as for functions in OMG #24 apply to events
  33. 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
  34. 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 youre 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.
  35. 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 wont be anyway if its used as a constructor!)
  36. 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.
  37. 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().
  38. 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 cant 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.
  39. 39. QUESTIONS?
  40. 40. Resources• Mike Taulty Javascript OMG!• A Collection of JavaScript Gotchas• WTF JS• A survey of the JavaScript programming language