Douglas Crockford: The JavaScript Programming Language

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

It's a good talk for sure and so was his short book "JavaScript the good parts" but you generally need a pretty strong understanding of Js to make proper use of the info. I've found "JavaScript is Sexy" to be one of my favourite resources. Never tried one of their paid courses tho.

Where do you live? I've found learning practical JS challenging but am finally starting to put all the pieces together.

👍︎︎ 1 👤︎︎ u/robvert 📅︎︎ Feb 01 2016 🗫︎ replies

Try khan academy. They have awesome JavaScript tutorials.

👍︎︎ 1 👤︎︎ u/Blood_Fox 📅︎︎ Feb 01 2016 🗫︎ replies

You should also check the You don't know Javascript series, and also look at the Javascript courses at Udacity.

👍︎︎ 1 👤︎︎ u/GodlyTaco 📅︎︎ Feb 01 2016 🗫︎ replies

You could try reading Javascript & jQuery by Jon Duckett, although it can be quite easy if you already have a decent level of JS.

👍︎︎ 1 👤︎︎ u/raulng9 📅︎︎ Feb 01 2016 🗫︎ replies
Captions
good morning everybody welcome to the Blair Witch Project I'm sorry good afternoon everybody welcome to the JavaScript programming language I'm Doug Crockford of Yahoo and today we're going to talk about JavaScript these are the things we're going to cover today we're going to cover the history of the language we're going to talk a lot about the language itself and some of its advanced features we'll carry that on in in the advanced JavaScript class that will follow we'll talk about some of the platforms when javascript is available we'll talk about the state of the standards and we'll talk about programming style in javascript javascript is without a doubt - the world's most misunderstood programming language and this owes to a number of factors first off the name it has Java as its prefix so a lot of people think that JavaScript has something to do with Java maybe it's interpreted Java or a subset of Java or something like that it turns out it's none of those javascript is almost completely independent of Java it's a different language and the suffix script suggests that it's not a real programming language it's something again diminutive or not complete but in fact we're going to see javascript is a complete programming language in fact it's a pretty good one it was intentionally mispositioned at its creation by Netscape and Sun Microsystems and we'll talk about that history the language contains some design errors some of which have been corrected during the course of its evolution some have not and so it's a very popular language it's probably right now the world's most popular programming language if you consider all of the platforms in which it's deployed but the language has problems and we'll look specifically at those problems early on there were very bad implementations and the language received a very bad reputation as a result of those bad implementations the implementations have gotten good quite good in fact but the reputation of the language remains damaged the language has been typecast it's known primarily as the language of the browser and so the browser is we'll find out in the the class the theory of the DOM is a really hostile programming environment a lot of people think that the thing that makes the browser so difficult to do is JavaScript but it turns out javascript is not the problem there we'll look at that and as we go along the books about JavaScript are almost all universally bad so it's very difficult to learn the language from books because most of the books are full of bad advice and bad examples there's only one book that I recommend that's Dave Flanagan's definitive guide from O'Reilly the fifth edition I can say without fear that it is the least bad of a very large class of very very bad books so yeah it's that one the rhinoceros book I recommend it as highly as I can recommend a JavaScript book the standard which defines javascript was defined by ACMA the European computer Manufacturers Association we'll talk about them later unfortunately the standard itself is not very good it's very difficult to read and understand which contributed to the bad book problem because authors could not go to the standard in order to improve their understanding of what the language does finally javascript is a functional language in the way that Lisp and scheme or functional languages which puts JavaScript in a completely different class but this is virtually unknown so we'll be talking about this aspect of the language as we go forward in 1992 Jim Gosling was sitting in his office at Sun Microsystems he'd been working on a language which was going to be a successor to C++ Gosling's a really smart guy but not very good at naming things and so his working title for the language was C + + + + his friends told him jigna you can't call it that you're gonna have to call it something else so he looked out of this window hmm saw an oak tree and at that moment the name of his language was changed to oak Gosling then got spun out into a new startup called first person which was going to be developing technology for interactive television application and oak was used in those applications that company failed so in 1975 he was rolled back into son after having failed in interactive media they were sitting around trying to figure out well what do we do with oak now and in a conversation in a coffee shop they decided that what it really needed was a new name and so looking at the menu gosling decided to call it java at the same time they decided that one of the first applications they would demonstrate of this new language was a web browser because the web at that moment in time was starting to become hot so they called the browser hot Jala having that browser having almost the same name as the language that it was written in caused huge confusion which actually helped them there was so much hype at the time about how wonderful browsers were and how wonderful hot Java was and that caused a huge amount of excitement about the language itself meanwhile at Netscape they had looked at Java and decided this really isn't going to work in webpages it's way too heavy it's way too clumsy to do api's and web pages and they do form validation and the sorts of applications that they anticipated they wanted something much much wider Brendan Eich was at Netscape at the time his first idea was to do a dialect of scheme in the browser his manager said no there's no way the market will accept all those parentheses do something that looks like Java or Visual Basic don't do anything weird just do it a nice little scripting language and we'll let you do that so he decided to base his syntax on Java and created something which became known as live script live script was the first scripting language to be put into a web browser it was also the first scripting language to be put into a web server of the live wire platform that Netscape was developing at that time had a live script in the server the reason Netscape and Java were so exciting at the time was because it was thought that they were going to provide a way to escape from Microsoft if the web could be established as a way of writing applications in which we're not no longer dependent on operating systems then we can get free of Microsoft and the world will be a better place that created huge energy around both companies they came to the conclusion that they were more likely to win against Microsoft if they joined together if they didn't join together the Microsoft would beat them against each other and in would prevail so they decided to create an alliance and the stickiest part of the potential alliance was what to do with livescript son wanted Java to be the language of the browser it would be the way that we would add interactivity to the web netscape said that's fine except it doesn't work so we really need to stick with live script instead there was a big battle about that the Alliance almost fell apart then Marc Andreessen the founder of Netscape had a really devious idea he changed the name of live script to JavaScript I think he thought it was funny I thought I think it was way to poke son in the nose what happened instead was son claimed trademark ownership of JavaScript and so they had controlled the name going forward so the next year 1996 Microsoft looked at what was happening with JavaScript and said ok we need to knock that off so they reverse engineered JavaScript an extremely careful job in their reverse engineering they did not want to deal with the son about the trademark issue and so they called their implementation jscript a lot of people think that jscript and javascript are different but similar languages not the case they are just different names for the same language and the reason the names are different was to get around trademark issues for the same reason Microsoft changed the name of their implementation of java to j plus plus it wasn't because j plus plus was intended to be a different language it was just intended to stay away from sons lawyers that scape was alarmed at the fact that Microsoft had made a copy of their language and that Microsoft would probably go and mutate the language and they would lose control over it so in order to prevent that from happening they decided we need to make it a standard so that Microsoft won't be free to fiddle with it so they took it to the European computer manufacturers association or ACMA they might be wondering why would a software company in California go to the European computer Manufacturers Association which is headquartered in Geneva reason was they thought they could get a rubber-stamp there but what happened was when the meeting started Microsoft was a member as were a number of other companies and from the first day Netscape lost control and standards process and Microsoft pretty much dictated the course of the language from that point on in particular mistakes that Netscape had made in the first version of JavaScript Sun had copied in their reverse engineering of jscript and insisted that those errors remain in the standard because it was very important to Microsoft at that time to never do anything to cause anybody's program to break now they never apologized to me when they caused my programs to break but in the echo committee that was a really important thing and so those problems persist in the language and we'll look at some of those today now the good news about javascript is that it is not a web toy it is a real language it's a useful language it's a powerful language it is small but sophisticated and it is not a subset of Java it's a completely different language and if I can learn to think about it in the way that its particular strong it's a very effective language every programming language has a key set of ideas which should be distinct from any other language otherwise there's no reason to exist these are what I think are the key ideas in JavaScript the first one is load and go delivery that means that programs are delivered to the execution site as source code in other languages programs are delivered as executable files or as abstract class files is something like that JavaScript gets delivered as text reason for that is it was originally intended to be embedded into webpages web pages are text and so if you can put programs in the same medium it's really convenient and that's no longer the preferred way of delivering programs to browsers but that mode still exists in JavaScript second was loose typing this is really controversial a lot of the fashion right now is in strong typing allowing compilers to check as much as possible before the program gets deployed loose typing though has overwriting benefits there's much greater expressive power often programs tend to be easier to write in this case you don't get a choice that the language is loose typing so if you can learn to like loose typing you'll be more effective it has objects as general containers this was a brilliant idea we'll talk a lot about this where they have the unification of objects and hash tables so objects are completely dynamic things in which new members and new methods can be added at any time other key ideas prototypal inheritance this is really distinct from classical inheritance which we see in most other languages in prototypal inheritance objects inherit directly from other objects there are no classes this turns out to be a really powerful idea but it's not commonly understood very well so you see a lot of people trying to program in classical styles in a class free language and that's not effective but if you can learn to think in terms of prototypes JavaScript can be extremely effective the next powerful idea is lambda lambda is the use of functions as first-class objects this is something that we first saw in Lisp and scheme javascript has a really powerful idea we're going to talk a lot about that then finally linkage through global variables because of the load and go model JavaScript doesn't have any sort of linker so separate compilation units are all combined in a common global namespace which turns out to be on a really really bad idea has security problems reliability problems and other things we'll talk about how to mitigate those the JavaScript language has a small set of values those are number strings boolean's objects and the special values null and undefined we'll look at each of these there's only one number type in JavaScript there's no separate integer type there's just number and it's represented internally as 64-bit floating-point which is also known as I Triple E 754 which is also known as double which i think is a stupid name for a number type but that's where it's called historically because Fortran had something called double precision and the name stuck the problem with floating point is that it doesn't map well to common understanding of arithmetic so point one plus point two does not equal point three so you need to be really really careful when you're dealing with things like money because people expect it to add up right and floating point can only give you an approximation generally of decimal fractions so what you want to do if you're dealing with cents or with with dollar values is multiplying by hundred that way you're dealing at whole sense do the arithmetic and then scale it back there's a special value called nan which stands for not a number it is a result of undefined or erroneous operations for example if you divide something by zero the result will be nan it's toxic so any arithmetic operation which has nan as one of its inputs will have nan as its output so if you go through a whole series of computations and at the end of all those equations and statements you find a result is nan that tells you that someplace there was a problem but it doesn't give you a very good indication as to where that was nan is not equal to anything including man so nan equals man is false also men is not less than nan man is not greater than them man is a really perplexing value also in JavaScript even though nan stands for not a number it is a number if you ask the type of a value that is nan the result is number there's a number function which can convert a value such as a string into a number that's handy if you have something that you take out of a form field generally text field will be text you need to turn it into a number before you can do arithmetic on it the number function will return then if the string cannot be converted into a valid number javascript also has a plus prefix operator which does the same thing and we'll see that later there's a parse int function which is specialized for just parsing integers and generally you should always include the radix argument which tells it what base to calculate in the reason for that is it stops at the first nan digit character that it sees and if the first digit is zero it is allowed to interpret it as an octal constant and so a leading 0 could cause it to think it's octal and then the next digit is not an octal digit and so you get a result of 0 rather than result of 8 so for that reason I recommend when you're using parse int always use a radix one mistake that Java Script copied from Java was having a separate math object Java did that so it could easily jettison math for applications in which you didn't want to pay for having a a math library but it turns out that's just not useful and Java Script repeats the same mistake so the number of useful mathematical functions available these are some of them probably the most useful of them is going to be the floor method math dot floor is the thing you use to take the integer part of a number javascript has strings where a string is a sequence of zero or more 16-bit characters the encoding is in Unicode speak UCS to not utf-16 that's because javascript was created before unicode got to that level of maturity the difference between those two is that us ucs-2 is not aware of surrogate pairs for the extended character range now it turns out the extra million characters are very rarely used so it's generally not a problem but it's something to be aware of there's no separate character type in JavaScript so if you want to have talked about just one character it's just a string of one character it's just a short string that's not a separate type strings are immutable which means that once a string is made it cannot be modified so you can't go into the middle of an existing string and manipulate the characters you have to make a new string which you can easily do by concatenating together pieces of old strings similar strings are equal with the double equal operator which is good JA got that wrong and you can write string literals in either single quotes or double quotes both work the same way there are no magic quotes or semi quotes or anything like that in this language all strings have a length member which you can use to determine the number of 16-bit characters in it this is not necessarily the same as the number of Unicode characters in it again because it doesn't know about utf-16 there's a string function which can be used to turn a number into a string and they're also number methods which can do it maybe a little bit more gracefully strings also have methods strings are objects in this language so there are lots of useful methods that you can perform on strings to get characters from them or extract sub strings or search on them or perform other sorts of surgery on them you'll be glad to know they're exactly two boolean values in JavaScript and that they are true and false a lot of references can't make that claim there's a boolean function which will take a value and if the value is true thee it returns true and if the value is false E it returns false talk in a minute what truthy and falsy mean then there is null which is the value which isn't anything that's sometimes a useful thing to have and then there's undefined which is the value which isn't even that undefined is the default value for variables so if you define a variable and don't initialize it it gets initialized for you with the value undefined this can be really confusing because a variable can be both defined and have the value undefined at the same time I think maybe they could have picked a better name for this because it's trying to describe two states at once undefined is also the value that you get when you extract a a member from an object that doesn't have that number so it's the missing value value undefined so talked about truthy values and policy values these are the false e values false null undefined the empty string the number zero and man all other values including all objects and everything else that we're going to see in the language are true the-- the ones to watch out for are b string 0 it's not the same as number 0 so it is true the-- also the string false is true the-- even though it looks like it's false because all non empty strings are true the-- yes ah that's a good question case sensitivity all the key words that we're going to see in the language are lowercase there are some methods we'll see which are camelcase but generally it's all over case and it is case sensitive so those are the simple values everything else in the OP in the language is objects so you may have heard that javascript is not an object-oriented language I'm going to try to convince you that it is because it's all about objects for the rest of the day so in particular the style of object which is implemented in JavaScript is the dynamic object the unification of objects in hash table the new object constructor produces an empty container of name value pairs where a name can be any string and a value can be any value except undefined so we once we create an empty object we can augment it by adding new members to it members can be accessed with dot notation or with subscript notation objects provide both syntaxes which is a little different for most other object oriented languages now even though these things behave like hash tables there is no hash nature visible by that I mean there's no hash codes or rehash methods or anything like that in fact in in the jscript implementation ie they didn't even bother to implement hash tables they've got linked lists for these things so for some object operations that runs noticeably slower on jscript than in other implementations javascript is a loosely typed language which means that any variable is capable of receiving any kind of value and any parameter to a function can receive any kind of value and any kind of value can be returned from a function the language is not untyped the language actually has a pretty robust sense of what types are but it's very loose and that it allows any type to be used anywhere C is or JavaScript is syntactically a member of the C family it's got all the curly braces and everything it differs from seeing mainly in its type system which allows functions to be values that that's one of the big ideas in JavaScript and what distinguishes it syntax its identifiers or follow the same rules as most of the c languages an identifier starts with a letter or with an underbar or with a dollar sign and it's followed by zero or more letters digits under bars or dollar signs and the name will be case sensitive by convention all variables parameters methods and function names start with a lowercase letter except for constructors would start with an uppercase letter we'll talk about constructors later initial underbar should is reserved for implementations they seem to be really popular in a lot of people's programs I don't know why it doesn't seem to be any reason for them generally it's better not to use them just to make sure you don't have a conflict with some internal variable dollar sign was added to the ACMA specification specifically for machines meaning macro processors and program generators things like that so it's recommended you not use dollar signs in your own programs however some of the Ajax community has fallen in love with dollar signs and they using dollar signs all over the place so if you want to ignore the standard you can go ahead and do that javascript has a bizarre reserved word policy all of these words are reserved and but only the ones in boldface are actually used in the language they got really heavy-handed in what they chose to reserve also they apply this list in places where they shouldn't have when you retrieve certain things using the dot notation or member names cannot be reserved words this was just an error in the language which has not been corrected yet there are two styles of comments in the language you can do slash slash as a prefix or you can do slash star as a bracketed comment it has the same set of operators that you would expect to see in any C language most of them work the same way as they would in any other C language but there are some differences we'll go over those the plus sign is used for both addition and concatenation the rule is if both operands are numbers it adds them in it otherwise it turns them both of the strings and concatenates them this was a mistake in a language which is loosely typed having this kind of operator overloading was just dangerous and we see a lot of mistakes made from this for example you see that expression where you're trying to add a concatenated dollar sign to an addition but you end up concatenated it all together so you need to be careful that when you intend to add that the operands are numbers plus can also be used as a prefix operator which will confer to not ran into a number so plus the string 42 yields the number 42 we can add strings together by using the plus operator reason I put this one in parens was this one could be confused with plus plus which means something completely different and we don't want that confusion so it's best to avoid that construction division of two integers can produce a non integer results you need to watch out for that so 10 divided by 3 isn't 3 and it isn't exactly three and a third either it has equal and not equal operators unfortunately these operators can do type coercion which can interfere with producing the correct result of the comparison there's also a triple equal and a bang double equal operator which do exact equality of both value and type and I recommend you use those instead Netscape at some point recognized that they had made a mistake and so the way they want to correct it was to fix double equal to be exact and added triple equal to the language to be coercive but Microsoft said no we don't want to do that so they reversed it so language now requires triple equal when you want exact equality it's a little harder to type because you have to go bang bang bang instead of bang bang but programs will run a tiny bit faster and will probably be a little bit more reliable javascript has a logical and operator which is also known as the guard operator works a little differently than it does in some of the other c languages if the first operand is true the-- it returns the second operand otherwise returns the first operand it doesn't necessarily return true or false it can be used to avoid null references so I've got an if here if a is true the-- then a return a dot member otherwise I'll just return a I could write this here just as return a guarding a dot member does the same thing it's a lot smaller a lot faster similarly there's a logical or operator which is also called the default operator and it works the opposite is as the other one so if the first operand is true the-- the result is the first operand otherwise the result is the second operand we can use this to fill in default values so here we've got an input that we may have pulled out of a form element and we want to assign a value to last if input has a value that's what we'll put in there but if input is falsie we'll put that in there instead so you know we could write that as an if statement this is much more compact and if you get used to thinking of this as default then it's a really expressive way of writing these sorts of expressions it has bang the logical not operator if the first operand is true the-- the result is false otherwise the result is true if you say bang bang that'll produce a boolean because when you do that and do it again you'll get either true or false it has bitwise operators you might wonder what sense does a bitwise operator make in a language that doesn't have integers so the way they work is they take the floating-point number convert it into a 32-bit integer do the logical operation on it then convert it back into floating-point so some people when they use these operators they think that it's going to go faster you know if I'm going to do a shift instead of multiplying by 2 that's going to be a big win in this language don't do that if you don't intend for a bitwise operation don't use these operators because it's going to be slower JavaScript has a large set of statements which look pretty much like a set of statements you'd find in any of the other C languages but there are a few differences and we'll look at those first off it has label break which is a really nice thing it copied this from Java so I can put a label on a loop and then I can break from that loop and so if I have nested loops or nested switches I can bust out of the middle and get down to the bottom it's really handy it has a fourth statement which we can use to iterate for example through the elements of an array so I have an array called array I can go through its length and visit all of its members and in the body of the loop array sub I will be the current element being considered there's also a special version of the for statement which is for objects which allows us to iterate through all of the keys that in an object the syntax is a little bit different we say name in object and for each iteration through the loop name will be set to one of the keys from that object unfortunately we'll also go through all of the keys of every of the objects that this object inherits from which is usually not something that you want so to avoid against that you have to write as the first statement of the for if the object has that property then we'll do what we want to otherwise we probably want to reject it because of something we're dredging through the inheritance chain this is an annoyance and a lot of people who ignore this pattern end up having programs get broken when they work with other people's programs so this is a disgusting thing you have to do but I highly recommend that you do it in all of your four statements javascript has a switch statement just like the c languages which provides a multi-way branch but it has some advantages first off the switch value does not need to be a number it could be a string or anything else that's really really handy and the case values do not have to be constants they can be expressions which could also be handy so for example I could have a switch statement in which I'm comparing against strings and you know if I match one of those and I do that it still has the same broken switch statement as everything else in that you have to explicitly terminate each of the clauses that's unfortunate but that seems to be the standard and then it also has a default so you can catch all the else cases javascript has a throw statement so you can throw an exception from your code you can generate a an exception object by calling the the new constructor or you can use an object literal and make one in place if you don't want to go to that we'll and we'll talk more about object literals as we go on once you throw you might expect that the exception will be caught so javascript has a try statement you can try some bit of code and if an exception is thrown in it it will be caught in the catch Clause because we don't have classes in this language there will only be one catch clause you won't have one per exception class and your catch Clause will then have to determine what sort of exception it is and decide if it wants to handle it or throw it on or whatever any questions about that okay and there's a try statement or the there are exceptions which are built into the Java Script system itself so the JavaScript engine knows how to throw all of these exceptions and all of these exception constructors are available to you as well so you can throw any of these or you can make up your own exceptions javascript has a with statement which was intended as a convenience for dealing with objects but it there is an error in the way it was conceived and so I don't recommend you use it it's ambiguous and error-prone so here's an example we have a whip statement with some object foo equals null now it could mean Oh dot foo equals null or it could mean the global variable foo means null anybody have a guess as to which one it means well it turns out you can't tell it could do either of them depending on what o is so programming is hard enough if you're using constructs in which you can't predict when you read the program what the program is going to do best not to use it so I recommend stay away from the width statement javascript has a function statement which is used for declaring functions a function has a name an optional set of parameters and then a set of statements which get executed when the is invoked there's a var statement which defines variables within a function you don't specify types in this language so you don't say int a or something like that you just declare that it's a variable optionally you can initialize the variable with values so I can say var number of errors initialize to zero or I can just give a list of variables separated by commas now if you don't give an initialization value it will be set to undefined for you in JavaScript blocks do not have scope this is a departure from all of the other c languages i think maybe it was a bit of laziness when they were writing the compiler this causes people to think incorrectly about variable scope there is only function scope in JavaScript so if you declare a variable anyplace inside of a function it's visible everywhere in the function and if you declare a variable twice any function it only gets created once there's no error for that yeah so this was a mistake and the mistake persists in the language so yeah right that that's another good question javascript has implied Global's so if you yeah so we'll talk about these more later but if you create a variable and forget to declare it javascript assumes that you meant it to be a global variable so for example if you forget to define I you've created a global variable called I and if you make that same mistake in two places there's a good chance your programs going to fail javascript has a return statement actually two forms of them one in which it returns an expression and the other where it appears to return nothing except in JavaScript every function will return a result there is no void type in JavaScript so if you have a function which does not return something explicitly or falls through the bottom that function will return the undefined value except in the case of constructors in which you'll return the new object we'll talk about those in a little bit so we said everything else in the language is objects and objects can contain data and methods and objects can inherit from other objects so objects in this language are collections an object is an unordered collection of name value pairs were the names are strings and the values are any type including other objects it's very good for representing records and trees you can think of every object as being a little database we also have a literal notation in this language which is extremely convenient it provides a way of of conveniently creating a new object again the names can be strings but we names can also be simply names so in some cases the quote marks around keys are optional the values can be any expression : separate the names and values comma separate the pair object literals can be use anywhere that a value appears so here's an example of an object literal I declare a variable called my object which contains this object which has a name I'm going to go to in a grade and a level so you can think of it as creating this little table in memory in JavaScript where these are the keys and those are the values and then I can access that material in the language I can say my object name and that will set the name to Jack be nimble I can also use the subscript notation I can say my object to sub the name or the string go-to and it will do the same thing and put jail into the destination so these two notations are interchangeable in most cases except they're not in this case because go-to is reserved word and one of the errors in JavaScript is that I cannot have a reserved word in this position but I can have a string in that position so that's why you need to be aware of the reserved word policy another way that I could make an object is to have a maker function so I'll pass a bunch of material to the maker function and have it make an object for me and then return it so in this case I've got a maker function which will return recreate a NIP variable and then it will fill that object up here the empty curly braces mean make a new empty object so I then assigned to that object a name a go to a grade a level and then I return it okay so the other way I could have made my object would be to call a maker function and then pass the material that I want it to construct with now this Maker function could get arbitrarily complex instead of just taking the values it's passed and doing stuff with it it could go do computation or call other functions or look at other variables or whatever in order to decide how to build the thing but this is sort of the simplest kind of function that makes an object so here's a we've taken that same object and we've made the object a little a little bit more complicated because we've added a format field to it now and it's type is an object so this shows an example of how we can have nested objects in this notation but all scrunched up like that it could be really hard to read so it this can be a lot easier to understand if you use take advantage of pretty printing let's see in this case it's very clear what the structure of this object is going to be now the question was could I have a trailing comic here and the answer is sometimes oh I know really look at it an example later of how that becomes a problem so we can use an object literal anyplace we can expect a value so any place in language where we could have any kind of expression or variable we can stick one of these in there too so I can pass an object to my function and my function doesn't know if this was a predefined thing or something I defined on the spot it just gets an object with all those values in it and that can be pretty handy or here again I'm going to throw an exception an exception object should have a name type in a message I can just make it dynamically I don't need to create a constructor or call constructor to throw an exception I'll confess I once wrote a really horrible API in JavaScript I had it was some years ago I had a super div constructor which took like 10 or 20 parameters and it was really hard to remember what the names of all the parameters were and it turned out most of the time you didn't need all of them and then later we figured out that some of them really shouldn't been parameters at all they should have been in style and so shouldn't have been in this list but by then the API was stuck and we couldn't take them out without breaking it had I been smart what I would have done instead was pass an object to this thing and that object would allow me to of what would practically be named parameters wouldn't matter what order they're in it could detect when things are missing and provide suitable defaults that would have been a much cleaner API so generally if you find yourself doing something with more than a couple parameters in it step back and think about refactoring it as something that takes a single object one of the nice things about objects in this language is that they can be augmented by that I mean you can take an existing object and add new stuff to it at any time give it new members new methods and we do that simply by assignment so if I want to make an object that is bigger I don't need to make a new class in fact there are no classes I just do it so if I decided that I wanted to add a color model member to the format of this thing I just assign it and boom it's got it so the general pattern is I have an object the key for that object in a value that I'm assigning and this works anytime for any object when objects are created they're creating created with a secret link to another object this is the method by which inheritance is achieved because objects are able to inherit from other objects if we attempt to access a member from an object and that access fails the system will silently go to the object that that object was linked to and see if it has a member with that name and if it does it returns it and and computation goes on if it doesn't then it will finally return on undefined the secret link is not used in storing so if I store something to an object it goes to that object we never go down that chain we can use the object function to make a new empty object which has that linkage to object oh so this will this is the basic fundamental operator in prototypal inheritance we'll talk a lot about how this works so let me put in a picture for you maybe it'll make it clearer so I'm going to make my new object and I'm going to have it inherit from my old object by making it with the object function so with it what it creates in memory is a new object which is an empty object which contains the secret pointer to my old object so then I can go ahead and start augmenting this one so I can assign it a name it that creates a name in this object no change to this one because I'm doing the assignment to this one okay then I'm going to increment its level now this one initially didn't have a level so it went to this one it's got a level three plus equal add one to it store it here that creates a four here and then again I can augment it by adding another thing here but the other let's see if I ask this my new object what it's grade is there's no grade here so it'll be turn a it inherits that value from this object so linkage provides a simple inheritance mechanism any object can inherit from an older object some languages have classes methods constructors modules javascript has functions JavaScript functions do the work of all of those things instead of classical inheritance we have prototypal inheritance it accomplishes the same things but it does it differently it has I think greater expressive power but it's different if you don't understand that it's different it's going to be really frustrating so instead of organizing objects into rigid classes new objects can be made that are similar to existing objects and then customized object customization is a lot less work than making a class and it's a lot less overhead one of the keys to doing that is the object function the other key is functions in general and we'll talk about how those work yeah you object if the old dog - that's a good question what happens to the new object if the old object is set to undefined let me go back a little bit okay so suppose we say my old object equals undefined to make it go away well this object still exists so my old object was a reference to this value this value still exists so this linkage is not broken but the other thing that could happen is I could change this guy's grade to be the value this guy inherits is now B so he can be sensitive to the dynamic state of this object or I could delete the the grade member from this now he no longer has a grade yes that's a good question so what happens to this for once the level is stored into this object we no longer look at this one so this one's level is now self determined one thing which is odd though is if this guy ever deletes his level he'll now have this level because this one will now shine through again so sometimes deleting things doesn't cause them to disappear cause them to appear to mutate yes it's only single inherited so you only get one of these arrows per object but as we'll see you can have long linkages of these objects yes is there any way to change the linkage after the fact there is in Mozilla they have a non-standard thing and we'll look at that briefly in the advanced JavaScript class I don't recommend it because it's not standard and they won't work anywhere else and I think it's probably a bad idea anyway yeah does JavaScript cope with circular linkage you can't because an object can only be made from an existing object and those linkages cannot be changed so there is garbage collection in this language you'll be glad to know that and it's mark-and-sweep so cycles do get reclaimed okay so you can have this link going to another object in which you inherit properties the end of that link chain is always directly or indirectly object dot prototype it's always the last in the chain so object dot prototype is a place in the system where the system provides built-in methods for you it turns out that they're not very useful unfortunately there is one that we saw earlier has own property which is a little bit useful surprisingly there is no copy method for objects in JavaScript it seems like an omission just doesn't have it also it doesn't have an equals method in it which also seems like an omission there you can use equality operator which tells you if two references are the same object but it doesn't tell you if two objects contain the same stuff javascript just doesn't have that it seems odd but but they don't so there are three ways in which we can make a new empty object which we can then stuff full of good stuff we can use the new object constructor or we can use an empty object literal or we can call the object function passing it object dot prototype all three of these will do exactly the same thing return exactly the same result I recommend the empty object literal because it's the smallest and once you learn to read it this way it's also the most expressive objects are passed or objects can be passed as arguments to functions they can be returned by functions objects are always passed by reference they are not passed by value the double equal or triple equal operator compares object references but not values so it will return true only if both operands are the same object doesn't help if there's similar objects there is a delete statement which can be used to delete elements from an object you say delete the object and then sub the name or dot the name and that removes it actually changes its value to undefined which does the same thing objects are arrays in JavaScript are unusual they're not like in most other languages because array inherits from object the way arrays work is that array indexes are converted into strings and then used as names for retrieving values they're not the the position indexes into a list or a string of memory it's really efficient for sparse arrays and not very efficient for almost all other applications including the ones that we write it does have one advantage though there's no need to declare the length of an array when you're creating it because it doesn't matter and you also don't have to give the type of the stuff going into the array because that doesn't matter either yes what's a threshold of sparse pretty sparse you know if you've got like one percent population in your array then this is a really effective way to do it for anything in which memory tends to be pretty linear this is not an efficient implementation arrays have a length member which tells you which looks like it should be the number of elements in the array but it's not it is one larger than the highest integer subscript which depending on the composition of the array may or may not be the same as its actual length so what that does is allow you to use a traditional for loop to go through all of the members of the array so that the length operator does that or the length operand of member does that there are array literals in this language which works similarly to the object literals array literal is in square brackets with value separated by commas so here I can make my list which contains these three vegetables and then I can append to an array since the Rays don't actually have a length they don't actually have an allocation we can add new stuff to any array at any time so if I assign to my list added my list dot length this will be three so we assign the third subscript give it barley that changes the length of the array to four because the length is always one bigger than the last index that we assign to it our last biggest that we assign to it we can't use the dot notation with arrays because there's a confusion with dots and numbers but we can use the subscript notation and empty brackets is a preferred way to create a new array recommend you don't say new array to create a new array yes the fish needs zero 1 2 right it's a good question does this create something similar to having an object literal in which the keys are quote zero quote 1 and so on very very similar the difference is that it also has a reign Eicher which means that the length member means something and it also inherits the array methods and we'll look at those otherwise it's the same stuff so arrays have methods these are some of them we can concatenate arrays together we can join an array which means we turn all of its members into strings and concatenate them all together we can push and pop things on the end so we can treat it like a stack we can slice it sort it slice it we can do surgery to it we can delete members from an array by deleting them the same as we can with objects but it doesn't do what you think it does it removes the element from the array but it leaves a hole it doesn't change the subscripts of the other members if we want to get rid of the hole we need to use the splice method so let me show you an example of that I've kind of Ray containing a B C and D I delete subscript one because arrays start from zero we end up with this structure the indexes of these two didn't change if we want to close up the hole then we could use splice which says starting from the first index delete one thing and insert nothing in its place so that will then give us this result so since objects and arrays are so similar in this language I mean they're almost the same thing when to use one and when to use the other in fact if he uses the wrong one your program will probably work most of the time so you don't get good feedback when you're making a mistake so this is how you decide use objects when the names are arbitrary strings and use arrays when the names are sequential integers don't be confused by the term associative array and think that means you use an array in this language arrays and objects are both associative arrays but the thing they think that an associative array is is the object right okay so we talked about how objects have the secret links by which they inherit things arrays also have secret links and they get linked to array dot prototype you don't get to choose with arrays and we'll talk about the implications of that later so if you get a value how do you determine if it's an array or if it's an object as we'll see later there's a typeof operator in JavaScript but it doesn't help us to do this distinguishing so they're two methods that do work one is we can say value dot constructor does it equal array the other is we can say array instance or value instance of array and if that returns true then we can think it's an array although neither of these work if the value came from another frame it we'll talk later about why that is this is an omission in the language which I'm hoping gets fixed someday okay so we can't really use or we cannot inherit from an array effectively so you can't use arrays as prototypes the reason is that the thing that gets produced by the object operator is going to be an object it's not going to have array in nature the length member isn't going to work it won't won't be right but what you can do is you can augment an individual array by assigning methods to it since it is underneath an object it's able to receive any kind of value including functions and any kind of key not just numbers the other way you can augment an array is to augment all of the arrays in the system at once and you can do that by assigning methods to array dot prototype it will look later about how that works okay so functions are first class objects first of all in the computer science sense functions can be passed and returned and stored just like any other value this turns out to be really really powerful and important but also in the sense that JavaScript means an object it function inherits from object and can be a container of name value pairs it sounds really strange how can a function contain members a function could contain other functions what does it mean for a function to have methods we'll look at this okay javascript has a function operator which we use to create function objects over function values and it takes an optional name in a parameter list in a block of statements it looks a lot like the function statement but we can use this anyplace in the language where we can have an expression so we can pass functions to other functions we can assign functions to variables we can store them in objects we can return them from functions very very powerful but javascript calls a function other languages have called lambda it's a source of enormous expressive power and unlike most power constructs it's a secure construct where it's not the kind of thing that blows up in your hand it's something which can actually constrain scopes and and help you to keep your programs in check now earlier we saw the function statement which looks a lot like the function expression and it turns out that one is just a shorthand for the other so when you say a function statement what you actually end up doing is creating a variable and assigning a function value to it the function statement is a shorthand so this function foo expands to creating a foo variable which has that function as its value some people get confused about can I have functions with the same names as variables do they interact with each other the answer is yes there's one namespace for both of those things functions do not all have to be defined at the top level or on the left edge of the screen functions can be defined inside of other functions that turns out to be a really useful thing but it raises questions of scope you know what does a function know and when does it know it so the rule is an inner function has access to all of the variables and parameters of the function it's contained within this is known as static scoping or lexical scoping the other way to do this is dynamic scoping turns out for most applications static scoping is better so this is one of the things that JavaScript got right the scope that an inner function enjoys continues even after the parent function has returned this is called closure now this sounds really weird what does it mean that it still has access to a parent's function after the parent function has returned what's it mean let me show you an example this is something that's really popular right now in Ajax applications where it changed the color of something from yellow to white we're going to do with a fade function it will pass the function the ID of an HTML element and so we'll define a couple of variables we'll define a Dom variable which will contain a Dom element that we fetch based on that ID and we'll create a level variable which will set to 1 and then we'll create a step function nevermind yet what it does but we'll create a step function and then we'll call set timeout and what that does is in 100 milliseconds the system will call the step function for us and then the fade returns and it's finished it's all done so the parent function has returned suddenly 100 milliseconds later the system wakes up and calls the function that we passed in here ok so what does it do it defines H which is the hex value of the level what is level it's that it is the value of the parents variable and then it gets the computes the color for the background color what is Dom DOM is that variable so it has access to that variable it's not the value of the variable at the time that the function was created it's actually got a connection to that parents variable so down here we look to see if level is up to 15 yet and if it's not we will increment it it's not incrementing a copy it is incrementing that variable it still has access to it and then it will arrange to call itself again another 100 milliseconds and we'll keep doing this until it gets up to 15 and that stops now what happens if we want to fade two things at once okay so I'll call fade on that and fade on that will those two calls of fade interact with each other no because each of these functions when it's invoked has its own scope and so we can have multiple invocations of fade going at the same time they will not interfere with each other because all of these are local variables to the fade function so we'll talk about closure and Inter functions and this a lot more in the advanced class but this is probably the number one really powerful feature in JavaScript this is something that formerly we only saw in AI languages really really good stuff this is the thing that makes JavaScript worth your attention and why we can afford to look past its other failings because this is the first lambda language to go mainstream this is something that the MIT guys have not been able to do in 40 years so this is really really good stuff okay functions are objects so they can contain name value pairs just like other objects this could serve the same purpose as static members do in some of the classical languages so if we have a maker function or a constructor which acts like the constructor of a class it can contain methods and and other things which are used to the class and since functions are our values they can be stored in objects and when a function is stored in an object we call it a method if there are some rules on function invocation if a function is called with too many arguments the extra arguments are ignored and the function just receives the values it asked for if the function is called with too few values then undefined is used to fill in the missing values there is no implicit type checking of the arguments and and there's no checking of the number of arguments so you're pretty much on your own there there are four ways to call a function there is the function form the method form the constructor form in the apply form we'll talk about the apply form some in the advanced class but we'll talk about the first three here first let's look at the method form here we've got an object on which we're invoking a method then we have dot or a substring the method name and the arguments when the function is called in this form in addition to its regular parameters it gets a special extra parameter called this and this will be bound to this object so it gives that function access to the object that it was invoked in this allows the object to have that reference and allows us to reuse functions in lots of different objects or in different inheritance chains and it depends on the invocation to tell it which object it's linked to then there's the function form in which we don't have a function prefix on that we just have a function value that we're calling in this case this gets bound to the global object which is not very useful and it could be argued this was a mistake in the design of the language one of the ways it's a mistake is that it makes it really hard to write a helper function inside of a method because the helper functions and the method don't have access to this of the parent so one way we get around that if we need a inner function to have access to this is we define a variable called that and assign this to that then the inner function can use that because that will be available in closure in scope and we can use it it's annoying that we have to do this against another error and the design of language but it's it's in there and finally there's constructor form and it looks like function form except there's a new prefix when a function is called with the new operator a new object is created and assigned to this so it's another implied parameter going into the function if the function does not have an explicit return value then this will be returned by the function instead of undefined so summarize depending on the invocation form this can be either the global object or the object from which the method was obtained or the new object being constructed in addition to this functions also have access to another special parameter called arguments so when the function is invoked an additional parameter is given to it arguments is an array like object which contains everything that was passed to it so we talked about how if there were extra arguments they get ignored they don't get ignored now the arguments array will deliver everything that got passed so it allows us to loop over everything we can actually check the number of parameters in that way unfortunately it's not a real array and the way that javascript is it's in an array like object so it doesn't have access to the array methods it's a length attribute doesn't really work but it's a bit of a problem so here's a way to use it say I want to write a sum function I'll pass it any number of numbers and I however many numbers it gets it's going to add them all up and return the result so we're going to set n to b arguments.length and then we're going to loop till n and as we go we're going to get the next argument and add it to the total and then we're done we return it so this provides a convenient way of writing functions that take a variable set of parameters so one of the really powerful things in JavaScript is that we can extend the built-in types I can extend all of the objects at once by extending object that prototype or I can enhance all the arrays by assigning to array dot prototype and so on so let me show you an example of this a trim method is a method on strings which will get rid of whitespace at the beginning and the end of strings clean them up unfortunately JavaScript neglected to include such a method which is unfortunate because that's a really useful method but it's not a problem because I can write one I can assign to string prototype trim this function which contains a regular expression it which is gets passed to the replace method and it will do what I want it'll look for a pattern of white space a non-white space and and return something from the middle and I get exactly what I want here's a slightly more complicated example I've got a template string which has some meta variables in it and then I've got an object literal here with some interesting data and I'd like to be able to blast this data into that template and then stick it into the Dom tree this is really easy to do this is a very nice model of client-side HTML generation unfortunately JavaScript doesn't have a supplant method but fortunately it's really easy to write one so again I can go to string dot prototype dot supplant and then I've got another function which again calls replace there's a slightly more complicated thing on it basically I'm passing to replace a function which tells it how to do the substitution and again it has access through closure to the object that gets passed into supplant so being able to augment the basic types of the system it's really powerful I mean in Java you can't even extend string here we're not extending string we're fixing string we're making string do exactly what we want that turns out to be really powerful javascript has a type of operator which helps us to determine but the type of something is of if I put type of in front of an object value it returns the string object which is pretty good unfortunately if I put in front of an array it returns object which isn't wrong but it's not very helpful it doesn't distinguish that it's an object even worse if I pass it null their returns object that is wrong that's just a mistake I asked Brendan Eich how did that happen and he said in the first implementation of JavaScript he had tagged pointers and the tag value for objects was zero but he also used null for null pointers which also happens to have zeros of that spot he didn't notice it but the guys at Microsoft did because they copied that bug into jscript and they insisted that it stay in the standard javascript has an eval function this is powerful and dangerous eval gives you access to the JavaScript compiler and interpreter so you can pass eval a string and it will compile the string and execute it in the context of the function that's calling eval that makes eval extremely dangerous it's the most misused feature of the language recommend you don't use it ever if you ever find yourself in a situation where you feel you just have to use eval give me a call let me talk you out of it okay you don't be using eval um when you find you're needing to use it I'll explain it to you but there are a number of things wrong with it one is it wastes a lot of time you're often you're calling the compiler to do something which could have been done much easier that that's probably the biggest misuse we find that there are a lot of cases where people don't know how to use the subscript notation so instead they will concatenate dot notation things together and then eval them it's probably the slowest way of doing those sorts of things also defer certain kinds of checking to runtime that could have been done at compile time or at authoring time so it delays error detection so it makes it easier to ship bugs so and they're also security problems with it yeah a question is should you use eval with JSON turns out that is the only time when it's correct to use eval and then it's only correct if you can absolutely trust your server not only that its intentions are good but that it is not incompetent because if the server is actually acting as a proxy and sends bad stuff without filtering it then it's wrong to use it in that case too so if there's any doubt about the competence of your data source then you need to use the parse Jason method instead of eval he says always doubt that's good advice there is also a new function function in JavaScript which also gives you access to the compiler in fact this is the thing that eval calls in fact the reason the eval is in the language why would they put such a dangerous thing in the language the reason is the browser uses it so when the browser gets a script tag or the browser sees an event handler on the page the browser calls eval saying what should I do with this so it was there for its convenience they exposed it to us as well it's probably better that they hadn't but they did so eval calls the new function function and it takes a string which is the body of a function and it compiles it and returns a function object which is then executable this shouldn't be used for the same reason that eval shouldn't be used and I see it misused in exactly the same ways javascript have or Java has both int and integer types one of them is a simple value and the other is an object which wraps that simple value I think it makes Java unnecessarily complicated javascript copied that pattern to absolutely no advantage of the occasional reasons for why it was useful in Java made no sense in JavaScript this is now recognized as an error in the language so don't use it don't ever be saying new boolean or new string or new number this is particularly problem from people who are coming from Java because they're used to saying new string but this doesn't do the same thing this creates an object which wraps a string value which isn't the same as a string value this one is particularly troublesome because if you say new boolean of false its value is false but the value is truthy so you just you don't want to go there Wow it's confession time I've been telling you about using the object function to create objects it turns out Java Script doesn't have that object function it's a prototype old language but they failed to to implement the core operator that you would have in a prototyping language which is make another object based on another object they instead did a very complicated thing with constructors and prototypes interacting with new all that stuff can be encapsulated into this one call though and in the advanced class I'll explain why this function works and why you should use it but Jesse and no if you go typing an object and it throws it back at you it's because you need to type this in first okay so one of the powerful things about JavaScript dog objects is that we could augment them we can directly modify individual objects and give them just the characteristics we want we can do this without creating classes and then we can take our new objects and use them as the prototypes for other new objects at which we can also augment think of this as working with the grain that deep down javascript is a prototypal language and if we can learn to think prototype alee then we can use the language much more effectively and in the advanced class we'll be talking more about the prototypal and parasitic inheritance patterns which are really effective in this language we don't need formal classes in order to get code reuse or extension in this language just don't need it javascript has a global object we talked about how one of the problems with javascript is that instead of having a linker everything gets resolved in a common global namespace that namespace is the global object it is implemented as a JavaScript object and it is the object that dares not speak its name and by that I mean it doesn't have a name in JavaScript it is the global object and it's important and it's on the present and it's always there but there's no direct way of saying that and always getting at it sometimes this points to it for example we saw in function form in vacations this gets bound to the global object instead of to something useful so it is possible to get access to it but it's not reliable on web browsers the global object is the window object and the way they made that work was they assigned to the global object a window member whose value is the global object and once so when you say window dot something that goes to the global object finds window in it which points to itself and then it knows what to do so if you ever wonder it is it faster to say document dot something or window dot document dot something it's faster to just to say document because when you say window you're actually doing one more loop through the lookup thing than you had to do you end up getting to the same place well it turns out one of the reasons why this is really bad idea is that global variables are evil the functions within an application can clobber each other and cooperating applications can clobber each other so the use of global namespace has to be minimized otherwise it's a good chance that as our programs get bigger or as we mash up we're as we work with libraries or other components we're going to get failures this is the problem is intensified by another era in JavaScript which is the implied global NE var which was not properly declared is assumed to be global by default this makes it real this was intended to make it easy for people to program so you didn't have to know about the client defining variables you just write and if your program never gets bigger than that that's probably not a problem we're now writing programs in JavaScript which we're much bigger than what we're originally anticipated and in the current world implied Global's are a big problem one of the ways we can protect ourselves from that is to use a program that I wrote called jeaious lint which is basically a JavaScript compiler written in JavaScript which will go through your code and look at all of your scopes and your definitions and help you find out where your Global's are and other stuff so I highly recommend that you put your programs through jslint we'll talk about that more in a little bit so Java scripts got this global namespace and we know that's bad but we've got tools for dealing with that for example we've got objects and every object is its own namespace now every object has its own distinct set of names so we can build our own namespaces using our objects so one of the things we're doing at Yahoo now is we have declared a yahoo object which is the one global object that we need and everything else that we're doing gets stored hierarchically inside of that object so that way we can have lots of stuff written by lots of different groups and different properties they all go to a registry to make sure that they don't interact in that space and then we can have confidence that we're going to reduce the collisions with our advertisers and with third-party libraries and user scripts when we get them in all that other stuff so if you're at Yahoo highly recommend you be using the yahoo object you can read about it here on the Twiggy if you're not at Yahoo don't be using the yahoo object make up your own object we recommend that you pick an all uppercase name because that's the least likely to accidentally get used put all your stuff in there again if we can all try to reduce as much as possible the number of global variables we're making we also reduce the likelihood that we're going to collide yeah do namespaces and here it they can in the sense that namespaces are just objects and objects can inherit so you could make a super yahoo object which inherits from another yahoo object super does not exist in this language the other thing we'd like to be able to do is encapsulate and function scope can be yes that's a really good question so you've got an HTML file and that file might have some JavaScript in it and it loads additional scripts how does it all get down together all of that all of those scripts all become part of one space all of those scripts become part of one space I'm sorry yeah that's the problem I think that was the one of the big design errors in the language so that's why it's so important that we look at these methods for trying to mitigate collisions in this environment so the other thing we can do is take advantage of function scope you know one of the rules of scope is that variables defined inside of a scope are not visible outside of the scope and so that gives us a very nice way of doing encapsulation in fact we can use an anonymous function to wrap our application now we'll look a lot at more at this on in the advanced class I'll just give you a preview of how this works suppose we want to create a a trivia service we decide that it's important to put a trivia question on every page we put out and so in the Yahoo object we create a trivia object which will be responsible for making things and it will have a gettin exposer method and a show poser method whatever else we need in order to make the trivia game work and we want to set it up so that this is a little sealed subsystem that it creates no global variables of its own and has no leakage except for the methods that we choose to reveal so we assigned to Yahoo trivia the result of this function and here we define all the common variables that these methods are going to want to share and any common functions that they're going to want to use helper functions or whatever we can put those here as well and then we return an object which is these and then we invoke that function so what we're assigning to trivia is not this function it's the result of calling this function which is this object in because of closure these methods will forever be bound to these private variables and private functions it's okay if you're confused right now we'll make this clear at the advanced class this is a really powerful platform that allows to make our programs much more reliable so um one of the most controversial things about JavaScript is its type system javascript chose to trade type safety for dynamism a lot of people wouldn't make that trade-off but that's the the trade-off that they made so javascript has no caste operator which is a good thing reflection is really easy in this language because you can always look at an object and ask what are you about you know do you have this method you have this value so reflection is easy in this language and so you step back and you ask well why do we have inheritance at all why is inheritance important I contend that we get two things from inheritance one of them is automatic casting because a type system in which you have to explicitly cast things I contend doesn't really give you any type safety so automatic casting is important but in JavaScript we never cast an object reference is always an object reference so that doesn't get us anything the other reason we want inheritance is for code reuse and as we've seen and as we will see JavaScript provides many many patterns for code reviews that we don't need classical inheritance in order to accomplish those so ultimately what JavaScript does is create brittleness for flexibility is it a trade-off is the right trade-off I don't know but that's the that's the state of the language so that's what we have to work with I've found over the years of working with JavaScript I used to be of the the religion that said yeah absolutely brutally strong type systems figure it all out at compile-time I have now been converted to the other camp I found that the expressive power in JavaScript is so great I've not felt that I've lost anything and giving up the early protection particularly since I brought my own tools to make sure that I get some reliability anyway we'll talk about that again later for completeness javascript has a date object it was based on JavaScript on Chavez date class so as a result it was not y2k ready it was only 1995 I guess they didn't see it coming but they have since fixed it hmm javascript has regular expressions it did it copies some of the Perl conventions regular expression literals are enclosed in slashes which is old problem syntactically since slashes already mean comments and division so you have to be careful about where regular expressions can go this is a regular expression which matches regular expressions at least that's what I claimed it is there's really no way you can tell looking at it what it actually accepts and what it rejects regular expressions are a bizarre notation I think they're really difficult to read it frightens me that we use rely on them so much for validation and for securing our systems when we have really no idea what this is doing doesn't seem to me the basis of any kind of system of security but they're really popular and so Java scripts got them and I use them a lot but I recommend be really really careful with them because it's really easy to get them wrong and you don't get much indication that you did Reds are a way of doing concurrency the JavaScript specification is neutral on threads doesn't say it has number doesn't have them there are some language processors like the SpiderMonkey JavaScript engine which does provide thread support most application environments such as browsers do not provide thread support all the browser's at the application level are single threaded which is really good because threads are evil it's really hard to think well about threads they don't belong at the application level so it's just as well that we don't have them javascript is provided on lots of platforms now it's obviously in all of the browsers it's also finding its way into operating systems now in windows script host and in dashboard on the macintosh it's in yahoo widgets formerly known as confabulate ER it's got a JavaScript engine built into it it's finding itself in desktop applications Dreamweaver and Photoshop have JavaScript built in PDF has javascript built into it now it can be embedded now into virtually any application so the time that you invest in learning JavaScript it's going to be helpful in doing web development but it's useful in a whole lot of other environments too so I think it's definitely worth the trouble to learn it a JavaScript like language is ActionScript which is found in flash this is a list of differences for ActionScript 2 a lot of flash community contends that ActionScript is an equipage it's not it's not compatible programs written for one will probably not work in the other there is a newer language called ActionScript 3 which is in the the current flash is also not compatible with JavaScript and that's a problem for for Adobe they'd really like flash to be based on a standard programming language and the way they got to ActionScript 3 was there was a proposal for a necklace crypt - that was developed by Microsoft and Mozilla Arbor Netscape I guess at the time but they couldn't agree on the details and and at some point they so enraged the Ekman committee that they didn't want any part of it and so it never became a standard not knowing how it was going to turn out Macromedia when they hadn't implemented it anyway and so they tried to get in front of a standard and instead unstandardized 4x the extensions 2x for XML this is something that was proposed by DEA and it provides for XML literals in the language so any place you can have angle bracket things and write out expressions it uses the app sign for getting at attributes inside of XML expressions sort of XPath type expressions inside of JavaScript it's implemented in Firefox but not most other places in particular Microsoft has not implemented it it's not in IE seven who knows if it's going to be in IE 8 in a year and a half so you know as I always say nine percent is not enough and the big problem with this is it's all syntax errors for for the old JavaScript so in if you load JavaScript with with the e4x features you get a syntax error program doesn't run you get a syntax error we don't get paid so you can't if around this stuff because the compiler rejects it and it all goes out so my advice is don't use e 4x as much as you might like an alternative to the Dom interface which is really horrendous for most applications this is not an alternative which is too bad now Microsoft had three people on the committee that standardized this all three voted yes so Microsoft cast three yes votes for the standard and then chose not to implement so that one's DOA or so it appears now there's some new activity going on a fourth edition of Vecna script the third edition was published in December of 1999 so the language has been sitting still for quite a long time and so in that time they've decided to take another attempt at creating a new standard based on it a very large set of new features are being considered include type declarations classes yields deconstruction a whole lot of stuff some of it is likely to be very popular particularly for the people who don't want to have to learn to think differently it might be possible to use this language that way it's going to have an object model which is more Java like but at the same time it's going to have to be compatible with the old model and it's not clear if those two worlds are going to play where it can be completely loosely typed and strongly typed at the same time one thing we do know is it's going to turn from a small language to a large language I'm not sure this is necessarily a good thing Mozilla is pushing this Adobe is also pushing it very very hard Adobe wants it to be a standard Microsoft is really not paying attention to it so it's not clear if they're going to adopt this one either and no word from Safari yet they haven't paid attention but I'm guessing if Microsoft goes along Safari we'll have to but we don't know what Microsoft's going to do let's talk now about style programming style isn't about personal taste it's about rigor and expression about clearness and presentation it's about product adaptability and longevity good rules help us to keep the quality of our programs high this is style is important in all programming in all programming languages but particularly in JavaScript because the language is so soft because it's loosely typed because it has errors in its design and some other factors it's really easy for a program to collapse into a puddle of confusion if you don't have really strict style rules working for you since so little else about the language is strict so I've just covered that most of the world's body of JavaScript programs is crap I believe that's well it's particularly true of JavaScript and it doesn't need to be I believe it is possible to write really good programs in JavaScript but it does require attention to style so we're going to look at some code conventions that have developed specifically for JavaScript you can read about them at JavaScript Crockford comm /co dot HTML my ambition is to eventually turn these into Yahoo standards and and have all of web development and all the JavaScript development at Yahoo conforming to these I think it really will make us more productive and improve the quality of our code which should ultimately make us all a lot happier as well so these are some of the specific things I'm recommending in JavaScript when the compiler sees an error it attempts to replace a nearby line feed with a semicolon and try again this should freak you out they it can mask errors so I recommend that you always use the full correct forms including semicolons in all the right places this was done intentionally in the language this is an intentional error in order to make the language friendlier for beginners now syntax is complicated you don't know where all the semicolons are supposed to go don't worry about it but JavaScript syntax is based on C and C has semicolons for a reason the grammar is ambiguous without semicolons JavaScript has those ambiguities that try to resolve the ambiguities by aliasing line feeds into semicolon so replaced one ambiguity with another not generally a good idea so be strict in your syntax because of semicolon insertion you need to be particularly cautious with line breaking because certain copy/paste errors are not detected by the JavaScript compiler so I recommend that you always break a line after one of the punctuate errs and that you not break a line after a name string or number or a closing operator or or an increment operator this will help detect certain errors easier or make them possible to detect avoid tricky expressions using the comma operator and also don't use extra commas and array literals this is a good way to write in a rate literal this is the bad one the difference is this one has a comma why is it bad because Netscape will tell you that the length of this is 3 and ie will tell you that the length is 4 in doing cross browser stuff is hard enough without this kind of stuff getting in the way I recommend that you always use blocks around structured statements so this one is 2 characters more than that one but this is provably a source of errors particularly in large projects or ongoing projects or projects with lots of programmers on them it's really easy for this one to get corrupted whereas this one tends not to so this resilience is well worth the 2 extra characters plots don't have scope in JavaScript so don't use block strictly for scope so I recommend that blocks only be used in the structured statements and nowhere else define all of your variables at the beginning of the function since you have function scope rather than block scope put them where you know they're going to be in some languages you like to define them as close to the site of first use as possible and that makes a lot of sense in other languages unfortunately it doesn't really make sense in this one so some of the style rules I'm recommending are different from rules that you may have seen in other contexts but that's because this language is different than other languages he may have worked with it javascript like the C languages has expression statements but those can mask errors particularly when you have semicolon insertion going on so I recommend that the only expression statements be assignment expressions and invocation expressions in no other case should you be using expressions as statements so it's okay to call a function you have to be able to do that but using an end operator here to control flow I think is a bad thing I'd rather see this written as an if avoid fall through in switch statements every Clause should explicitly break a return or throw do not use assignment expressions in the conditional parts of ifs and Wiles the reason is that this is more likely to mean that and so if you're in the habit of writing this form it's really difficult to determine when the mistake occurred so it's much better to never do this be aware that double equal and not equal do type coercion so this statement appears to do with this statement does but actually does what this statement does so a statement which appears to do one thing and does another can lead to errors so I recommend figure out which of these you mean and write this one whichever one it is in some cases it means putting an extra equal sign I'm happy to pay one more character in that case if you're just looking for a value which is false II then this form is actually smaller and faster so you're better off with it one place where I've seen this one used is they pull a out of an object and they look to see if it's under if it's null but the thing they were really looking for was undefined but they were confused about the difference between null and undefined so they actually had two errors that canceled each other out that's a bad way to program better not to be making so many errors only put labels on the statements that make sense with labels so do four switch and while and never ever use JavaScript : as a label and also avoid as much as possible using JavaScript URLs that I think was a bad idea in the browsers and something we should try to get away from so jslint is a program which will check for all of these things and will provide an automatic search for all of these and we'll help uncover errors in your program also give you a map of all the variable definitions in your program showing which are bound in closures and which aren't and give you a list of all of the field names that are used in your program this can be extremely helpful in in improving the quality of your programs and can also be helpful in debugging jslint does all of that it can find things which are really hard to find in debugging it provides a lot of the safety that we liked strong typing for even though we don't get strong typing in this language having automatic detection of errors is really helpful thing jslint is available as a web page so you can just paste your program in it and and it'll check it locally it's also available now as a confabulate err widgets and can also be run in the desktop getting built into text editors now it's going into eclipse so again I highly recommend that you be running all your programs through jeaious lint one warning though jeaious lint will hurt your feelings bad is a cruel arbitrary program it but if you can stand it and listen to its advice it will make your programs better so wrap up these are what I think are the key ideas in JavaScript loading code delivery in which programs are delivered as text loose typing which takes some getting used to but I think is a very powerful thing objects as general containers which I think was brilliant prototypal inheritance which turns out to be a pretty useful thing I mean it's why javascript is succeeding in the thing that Java was intended to do and failed at lambda which is probably the best idea in the history of computer science and linkage through global variables which is probably the worst idea in the history of computer science it's all there in one language it's JavaScript we'll continue next week with the theory of the DOM and the week after with advanced JavaScript I hope that you'll all come for those I'll see you next week good night everybody you
Info
Channel: YUI Library
Views: 460,036
Rating: 4.9671612 out of 5
Keywords: crockford, javascript, programming, webdev, frontend engineering, yahoo, yui
Id: v2ifWcnQs6M
Channel Id: undefined
Length: 109min 55sec (6595 seconds)
Published: Thu Aug 25 2011
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.