Javascript omg!

40
www.visug.be An introduction to the unusual and unexpected features of JavaScript. JavaScript OMG! [email protected] http://bartwullems.blogspot.com

description

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…

Transcript of Javascript omg!

Page 1: Javascript omg!

www.visug.be

An introduction to the unusual and unexpected features of JavaScript.

JavaScript OMG!

[email protected] http://bartwullems.blogspot.com

Page 2: Javascript omg!

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…)

Page 3: Javascript omg!

www.visug.be

Page 4: Javascript omg!

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

Page 5: Javascript omg!

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

Page 6: Javascript omg!

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.

Page 7: Javascript omg!

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

Page 8: Javascript omg!

www.visug.be

OMG #4 – Regular Expressions

• JavaScript has built in support for regular expressions

Page 9: Javascript omg!

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

Page 10: Javascript omg!

www.visug.be

OMG #6 – The Global Object

• There IS a Global Object.• Defining global variables and global

functions means mutating the global object.

Page 11: Javascript omg!

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!

Page 12: Javascript omg!

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.

Page 13: Javascript omg!

www.visug.be

OMG #9 – Type Conversions

• JavaScript has a pretty complex list of type conversions.

• Most of them are pretty intuitive.

Page 14: Javascript omg!

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.

Page 15: Javascript omg!

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.

Page 16: Javascript omg!

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.

Page 17: Javascript omg!

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;

Page 18: Javascript omg!

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

Page 19: Javascript omg!

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.

Page 20: Javascript omg!

www.visug.be

OMG #16 – Function arguments

• JavaScript functions allow for very flexible argument usage (way beyond optional and named arguments).

Page 21: Javascript omg!

www.visug.be

OMG #17 – Nested functions

• Define functions inside of functions and, optionally, form closures over the local variable state.

Page 22: Javascript omg!

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;

Page 23: Javascript omg!

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.

Page 24: Javascript omg!

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.

Page 25: Javascript omg!

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.

Page 26: Javascript omg!

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.

Page 27: Javascript omg!

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

Page 28: Javascript omg!

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#)

Page 29: Javascript omg!

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

Page 30: Javascript omg!

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

Page 31: Javascript omg!

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.

Page 32: Javascript omg!

www.visug.be

OMG #28 – ADVANCED: This or That?

• Same rules as for functions in OMG #24 apply to events

Page 33: Javascript omg!

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

Page 34: Javascript omg!

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.

Page 35: Javascript omg!

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!)

Page 36: Javascript omg!

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.

Page 37: Javascript omg!

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().

Page 38: Javascript omg!

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.

Page 39: Javascript omg!

www.visug.be

QUESTIONS?