Docsity

Advanced Javascript Notes, Study notes of Computer Programming

Toggle sidebar
bg1
Advanced JavaScript Essentials
Les son 1: Int ro duct io n to Advanced J avaS cript
Welco m e to Advanced JavaScript
Acces si ng the Co nso le
Using the Con so le
Go od Pro gram ming Style Practices
Testin g Co de in the Co ns o le
Interacting Directly in the Consol e
Co mmenting Yo ur Code
Quiz 1
Les son 2: Kno w Yo ur Ty pe s
Kno w Yo ur Types : Primitives and Ob jects
Prim itives
Some Interestin g Num bers
Objects
Enum eratin g Object Properties
Prim itives That Act like Objects
JavaScript is Dynam ically Typed
Quiz 1 Project 1 Proj ect 2 Proj ect 3
Les son 3: Trut hy, Fal se y, and Equ ali t y
Truthy, False y, and Equality
Value s That are Truthy or Fals ey
Impl ied Typecasting
Testin g Equality
Objects an d Truthy-nes s
Objects an d Equality
Quiz 1 Project 1 Proj ect 2
Les son 4: Co nst ru ct ing O bj e ct s
Co ns tructing J avaScript Objects
Co ns tructing an Obje ct with a Co ns tructo r Functio n
Co ns tructing an Obje ct Using a Litera l
Co ns tructing an Obje ct Using a Ge neric O bject Constructo r
So, What's the Best Way to Make an Object?
Initiali zing Valu es in Co ns tructo rs
this
Co ns tructing Array Objects
Quiz 1 Project 1 Proj ect 2
Les son 5: Pro to t ypes and Inhe rit ance
Object-O rien ted Pro gram ming in JavaScript
ins tanceo f
Prototype s
Prototype s o f Literal O bjects
What is a Proto type Go od Fo r?
The Pro totype Chain
Prototypa l Inheritance
When are Proto type Ob jects Created?
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Advanced Javascript Notes and more Study notes Computer Programming in PDF only on Docsity!

Advanced JavaScript Essentials

Lesso n 1: Int ro duct io n t o Advance d J avaScript Welco me to Advanced JavaScript Accessing the Co nso le Using the Co nso le Go o d Pro gramming Style Practices Testing Co de in the Co nso le Interacting Directly in the Co nso le Co mmenting Yo ur Co de Quiz 1 Lesso n 2: Kno w Yo ur T ype s Kno w Yo ur Types: Primitives and Objects Primitives So me Interesting Numbers Objects Enumerating Object Pro perties Primitives That Act like Objects JavaScript is Dynamically Typed Quiz 1 Pro ject 1 Pro ject 2 Pro ject 3 Lesso n 3: T rut hy, False y, and Equalit y Truthy, Falsey, and Equality Values That are Truthy o r Falsey Implied Typecasting Testing Equality Objects and Truthy-ness Objects and Equality Quiz 1 Pro ject 1 Pro ject 2 Lesso n 4: Co nst ruct ing Obje ct s Co nstructing JavaScript Objects Co nstructing an Object with a Co nstructo r Functio n Co nstructing an Object Using a Literal Co nstructing an Object Using a Generic Object Co nstructo r So , What's the Best Way to Make an Object? Initializing Values in Co nstructo rs this Co nstructing Array Objects Quiz 1 Pro ject 1 Pro ject 2 Lesso n 5: Pro t o t ype s and Inhe rit ance Object-Oriented Pro gramming in JavaScript instanceo f Pro to types Pro to types o f Literal Objects What is a Pro to type Go o d Fo r? The Pro to type Chain Pro to typal Inheritance When are Pro to type Objects Created?

hasOwnPro perty __pro to __ Setting the Pro to type Pro perty to an Object Yo urself Quiz 1 Quiz 2 Pro ject 1 Pro ject 2 Lesso n 6 : Funct io ns JavaScript Functio ns What is a Functio n? Different Ways o f Defining a Functio n Functio ns as First Class Values Ano nymo us Functio ns Returning a Functio n fro m a Functio n Functio ns as Callbacks Calling Functio ns: Pass-by-Value Return Quiz 1 Quiz 2 Pro ject 1 Pro ject 2 Lesso n 7: Sco pe Sco pe Variable Sco pe Functio n Sco pe Ho isting Nested Functio ns Lexical Sco ping Sco pe Chains Inspecting the Sco pe Chain Quiz 1 Pro ject 1 Lesso n 8 : Invo king Funct io ns Invo king Functio ns Different Ways to Invo ke Functio ns What Happens to this When Yo u Invo ke a Functio n Nested Functio ns When Yo u Want to Co ntro l Ho w this is Defined call() and apply() Functio n Arguments The Fo ur Ways to Invo ke a Functio n Quiz 1 Pro ject 1 Pro ject 2 Lesso n 9 : Invo cat io n Pat t e rns Invo catio n Patterns Recursio n Why Use Recursio n? Chaining (a la jQuery) Static vs. Instance Metho ds Quiz 1 Pro ject 1 Pro ject 2 Pro ject 3 Lesso n 10 : Encapsulat io n and APIs Encapsulatio n and APIs Privacy, Please An Example Private Variables

Introduction to Advanced JavaScript

Welco me to the O'Reilly Scho o l o f Techno lo gy's (OST) Intro ductio n to Advanced JavaScript co urse.

Course Objectives

When yo u co mplete this co urse, yo u will be able to : create an o bject-o riented JavaScript pro gram. structure yo ur pro grams to make use o f encapsulatio n where needed. write JavaScript using best co ding practices. make use o f patterns to structure yo ur co de. use and understand advanced techniques such as clo sures and recursio n. o btain and utilize info rmatio n abo ut the enviro nment in which JavaScript is running. Befo re we begin pro gramming, yo u need to learn a little abo ut the pro gramming enviro nment yo u'll be using. This first lesso n o f the co urse will help yo u with that.

Lesson Objectives

When yo u co mplete this lesso n, yo u will be able to : use OST's Sandbo x and learning to o ls. read abo ut what to expect in the Advanced JavaScript co urse. review JavaScript basics. use the Develo per To o ls in yo ur bro wser to access the JavaScript co nso le, which we'll be using extensively in this co urse. use co nso le.lo g to display messages in the co nso le (fo r debugging). use go o d pro gramming practices in yo ur co de.

Learning with O'Reilly School of Technology Courses

As with every O'Reilly Scho o l o f Techno lo gy co urse, we'll take a user-active appro ach to learning. This means that yo u (the user) will be active! Yo u'll learn by do ing, building live pro grams, testing them and experimenting with them— hands-o n! To learn a new skill o r techno lo gy, yo u have to experiment. The mo re yo u experiment, the mo re yo u learn. Our system is designed to maximize experimentatio n and help yo u learn to learn a new skill. We'll pro gram as much as po ssible to be sure that the principles sink in and stay with yo u. Each time we discuss a new co ncept, yo u'll put it into co de and see what YOU can do with it. On o ccasio n we'll even give yo u co de that do esn't wo rk, so yo u can see co mmo n mistakes and ho w to reco ver fro m them. Making mistakes is actually ano ther go o d way to learn. Abo ve all, we want to help yo u to learn to learn. We give yo u the to o ls to take co ntro l o f yo ur o wn learning experience. When yo u co mplete an OST co urse, yo u kno w the subject matter, and yo u kno w ho w to expand yo ur kno wledge, so yo u can handle changes like so ftware and o perating system updates. Here are so me tips fo r using O'Reilly Scho o l o f Techno lo gy co urses effectively: T ype t he co de. Resist the temptatio n to cut and paste the example co de we give yo u. Typing the co de actually gives yo u a feel fo r the pro gramming task. Then play aro und with the examples to find o ut what else yo u can make them do , and to check yo ur understanding. It's highly unlikely yo u'll break anything by experimentatio n. If yo u do break so mething, that's an indicatio n to us that we need to impro ve o ur system! T ake yo ur t im e. Learning takes time. Rushing can have negative effects o n yo ur pro gress. Slo w do wn and let yo ur brain abso rb the new info rmatio n tho ro ughly. Taking yo ur time helps to maintain a relaxed, po sitive appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u blew thro ugh all o f the co ursewo rk to o quickly.

Expe rim e nt. Wander fro m the path o ften and explo re the po ssibilities. We can't anticipate all o f yo ur questio ns and ideas, so it's up to yo u to experiment and create o n yo ur o wn. Yo ur instructo r will help if yo u go co mpletely o ff the rails. Acce pt guidance , but do n't de pe nd o n it. Try to so lve pro blems o n yo ur o wn. Go ing fro m misunderstanding to understanding is the best way to acquire a new skill. Part o f what yo u're learning is pro blem so lving. Of co urse, yo u can always co ntact yo ur instructo r fo r hints when yo u need them. Use all available re so urce s! In real-life pro blem-so lving, yo u aren't bo und by false limitatio ns; in OST co urses, yo u are free to use any reso urces at yo ur dispo sal to so lve pro blems yo u enco unter: the Internet, reference bo o ks, and o nline help are all fair game. Have f un! Relax, keep practicing, and do n't be afraid to make mistakes! Yo ur instructo r will keep yo u at it until yo u've mastered the skill. We want yo u to get that satisfied, "I'm so co o l! I did it!" feeling. And yo u'll have so me pro jects to sho w o ff when yo u're do ne.

Lesson Format

We'll try o ut lo ts o f examples in each lesso n. We'll have yo u write co de, lo o k at co de, and edit existing co de. The co de will be presented in bo xes that will indicate what needs to be do ne to the co de inside. Whenever yo u see white bo xes like the o ne belo w, yo u'll type the co ntents into the edito r windo w to try the example yo urself. The CODE TO TYPE bar o n to p o f the white bo x co ntains directio ns fo r yo u to fo llo w: CODE TO TYPE: White boxes like this contain code for you to try out (type into a file to run). If you have already written some of the code, new code for you to add looks like this. If we want you to remove existing code, the code to remove will look like this. We may also include instructive comments that you don't need to type. We may run pro grams and do so me o ther activities in a terminal sessio n in the o perating system o r o ther co mmand- line enviro nment. These will be sho wn like this: INTERACTIVE SESSION: The plain black text that we present in these INTERACTIVE boxes is provided by the system (not for you to type). The commands we want you to type look lik e this. Co de and info rmatio n presented in a gray OBSERVE bo x is fo r yo u to inspect and absorb. This info rmatio n is o ften co lo r-co ded, and fo llo wed by text explaining the co de in detail: OBSERVE: Gray "Observe" boxes like this contain information (usually code specifics) for you to observe. The paragraph(s) that fo llo w may pro vide additio n details o n inf o rm at io n that was highlighted in the Observe bo x. We'll also set especially pertinent info rmatio n apart in "No te" bo xes:

Note No tes pro vide info rmatio n that is useful, but no t abso lutely necessary fo r perfo rming the tasks at hand.

T ip Tips pro vide info rmatio n that might help make the to o ls easier fo r yo u to use, such as sho rtcut keys.

WARNING Warnings pro vide info rmatio n that can help prevent pro gram crashes and data lo ss.

Note

Bro wsers are co ntinualy updated with new versio ns that include new versio ns o f the co nso le. So , while the basic functio nality o f the co nso le will likely remain the same, yo ur versio n o f the co nso le may lo o k slightly different fro m what yo u see in this co urse. As yo u beco me familiar with the different bro wser co nso les, yo u'll be able to figure o ut ho w to use each o ne. Create a fo lder fo r yo ur wo rk. In the File Bro wser, right-click the Ho m e fo lder and select Ne w f o lde r... (o r click the Ho m e fo lder and press Ct rl+n ), type the new fo lder name AdvJ S , and press Ent e r. No w create a new HTML file, then add this co de: CODE TO TYPE:

Getting Started

Save this as basics.ht m l in yo ur /AdvJ S fo lder. No w create a new JavaScript file and add this co de: CODE TO TYPE: var onSale = true, inventoryLevel = 12, discount = 3; if (onSale && inventoryLevel > 10) { console.log("We have plenty left"); } if (onSale || discount > 0) { console.log("On sale!"); } else { console.log("Full price"); } Save this as basics.js in yo ur /AdvJ S fo lder. No w preview yo ur basics.ht m l file. Yo u'll see an empty web page. To see the result o f the JavaScript, o pen up yo ur bro wser's co nso le. To get instructio ns to access yo ur co nso le, click o n the link to whichever bro wser yo u're using: Chro me Safari Firefo x Internet Explo rer To access the co nso le in Chro me, use the Vie w | De ve lo pe r | J avaScript Co nso le menu:

Once yo u've enabled the co nso le, yo u may need to relo ad the page to see the o utput. Yo u'll see: There are many parts to the co nso le. Yo u'll beco me mo re familiar with so me o f them as we wo rk thro ugh the co urse. Co ntinue to the next step. To access the co nso le in Safari, use the De ve lo p | Sho w We b Inspe ct o r menu (if yo u do n't have De ve lo p enabled, yo u can enable it with Pre f e re nce s | Advance d | Sho w De ve lo p m e nu in m e nu bar ):

Co ntinue to the next step. To enable the Firefo x co nso le, use the T o o ls > We b De ve lo pe r > We b Co nso le menu and access the co nso le: Yo u may need to relo ad the page to see the o utput in the co nso le. No te that in Firefo x, the default lo catio n fo r the co nso le is abo ve the web page (unlike Chro me and Safari). Yo u can click o n the Po sit io n menu in the co nso le and select "bo tto m" o r "windo w" to change the po sitio n o f the co nso le. Cho o sing "windo w" will po p the co nso le o ut into a separate windo w. Co ntinue to the next step. To enable the Internet Explo rer co nso le, select T o o ls | F12 De ve lo pe r T o o ls and then select the Co nso le tab.

Yo u may need to relo ad the page to see the o utput in the co nso le.

Using the Console

Let's take a clo ser lo o k at the Chro me co nso le since that's the o ne we'll use in o ur examples thro ugho ut the co urse. Other bro wser co nso les have the same basic functio nality. We'll let yo u kno w when yo u need to use the Chro me co nso le specifically to fo llo w alo ng. There are several tabs acro ss the to p o f the co nso le, including the o ne we're o n, Co nso le. Yo u'll use Co nso le mo st o ften when lo o king at the results o f co nso le .lo g() , and debugging yo ur co de by checking to see if there are any JavaScript erro rs. In Safari, the equivalent is the Lo g tab sho wn in the screensho t; in Firefo x, it's the default view yo u see when yo u access We b Co nso le fro m the menu, and in IE, it's a tab labeled Co nso le. In Chro me, if yo u want to view the co nso le into a separate windo w, click o n the ico n in the bo tto m left co rner:

This can help yo u track do wn po tential bugs. There are who le lo t o f o ptio ns o n the right side o f the "So urces" panel, including "Call Stack," "Sco pe variables," and "Breakpo ints," all o f which we'll use later as we get into so me mo re advanced to pics. Make sure that yo u have do wnlo aded Chro me and have the latest versio n installed o n yo ur co mputer fo r testing. As o f this writing, the current versio n is 26. Yo ur versio n may be different, but that's o kay because the basic functio nality o f the co nso le is the same.

Note

Unfo rtunately, at this time, the o ther bro wsers do n't co me with the same to o l installed by default. Go ahead and do wnlo ad Chro me and get familiar with the co nso le to o ls, even if yo u typically use ano ther bro wser to create web pages. We'll explo re mo re o f the co nso le later, but fo r no w we'll take a clo ser lo o k at the co de.

Good Programming Style Practices

Let's review so me go o d practices fo r writing JavaScript pro grams: OBSERVE: var onSale = true, inventoryLevel = 12, discount = 3; if (onSale && inventoryLevel > 10) { console.log("We have plenty left"); } if (onSale || discount > 0) { console.log("On sale!"); } else { console.log("Full price"); }

T he variable s we use are all de clare d at t he t o p and give n de f ault value s. In general, it's go o d practice to declare yo ur variables at the to p o f yo ur file (o r at the to p o f a functio n, if they are lo cal variables), and to give them values. A variable that is not given a value is unde f ine d. That's o kay, but yo u need to be aware o f which variables have values and which do n't as yo u write yo ur pro gram. It's usually better practice to give yo ur variables default values, rather than leave them undefined. We've used the co mma-separated style to declare the variables. It's also a go o d idea to put each variable declaratio n o n a separate line. Still, yo u can always declare them with separate statements instead, like this: OBSERVE: var onSale = true; var inventoryLevel = 12; var discount = 3; Either way is fine, so just do whatever yo u prefer. Next, yo u'll see that we're using semico lo ns after every statement. While JavaScript do esn't require this currently, it's a go o d habit to develo p. If yo u leave the semico lo n o ff, JavaScript might interpret yo ur statements and expressio ns in a way yo u're no t anticipating. If yo u're in the habit o f leaving o ff yo ur semico lo ns, even o ccasio nally, start putting them in after every statement. It will make debugging yo ur co de a who le lo t easier. We suspect that future versio ns o f JavaScript may require semico lo ns to delimit statements anyway, so yo u may as well get in the go o d habit no w! OBSERVE: var onSale = true, inventoryLevel = 12, discount = 3; if (onSale && inventoryLevel > 10) { console.log("We have plenty left"); } if (onSale || discount > 0) { console.log("On sale!"); } else { console.log("Full price"); } Ano ther habit yo u sho uld get into is using curly brace s fo r every if (o r while o r f o r , and such) blo ck o f co de, even if there's just o ne statement in the blo ck. If yo u have o nly o ne statement in a blo ck, technically yo u do n't need to use the { and } characters to delimit the blo ck. Ho wever, this is a bad habit because it can cause yo u to miss erro rs. Always use the curly braces! Use plenty o f white space. It's better to add mo re white space and fo rmat yo ur co de so it's easy to read, than to scrimp o n space to make yo ur co de sho rter. Readability is vital when wo rking o n larger, mo re co mplex pro grams, and it's always po ssible to "minify" yo ur JavaScript later to take o ut the white space and make it mo re efficient to do wnlo ad.

Note

There are plenty o f "minificatio n" pro grams o ut there that can minify yo ur co de fo r yo u such as jsco mpress.co m and YUI co mpresso r. We'll co ver o ther go o d pro gramming practices and style suggestio ns thro ugho ut the co urse. We'll review them at the end o f each lesso n, so yo u'll get plenty o f practice. There are also quite a few go o d style guides o nline if yo u want to explo re this to pic further (no t all o f them agree o n everything, o f co urse). We like the Airbnb JavaScript Style Guide (github).

T esting Code in the Console

Let's practice using the co nso le to inspect values in o ur co de. Update yo ur file basics.js to define an o bject, re ct , and then display it using co nso le.lo g. Here, we define re ct as an object literal ; that is, an o bject we write as the value o f the variable using the { and } characters to delimit the o bject. Remember, an o bject is just a co llectio n o f key value pairs. In this case re ct has just two pro perties—width and height:

In Firefo x, it will lo o k like this: In IE, it will lo o k like this:

No tice that each is just a little different, but each co nso le sho ws yo u the same basic info rmatio n abo ut the o bject, including the two pro perty name/value pairs. No w, let's make a small change to the co de: CODE TO TYPE: var onSale = true, inventoryLevel = 12, discount = 3; if (onSale && inventoryLevel > 10) { console.log("We have plenty left"); } if (onSale || discount > 0) { console.log("On sale!"); } else { console.log("Full price"); } var rect = { width: 100, height: 50 }; console.log(rect); console.log("My object rect is: " + rect); and. In the co nso le, yo u see: OBSERVE: Object { width: 100, height: 50 } My object rect is: [object Object] Why do yo u think this is? Instead o f seeing the two pro perties that the o nject co ntains like we did befo re, we see just a string representatio n o f the o bject, "[o bject Object]". That isn't really helpful. In o ur co de, we're creating a string by co ncatenating the o bject, re ct , with the string "My o bject rect is: ", befo re o utputting the result to the co nso le. Previo usly, we passed the o bject itself to co nso le .lo g() , so the co nso le .lo g() functio n displayed the o bject. No w we're passing a string to co nso le .lo g(). When JavaScript co nverts the o bject to a string, we do n't get a very useful display o f the o bject. Make o ne last change to yo ur co de: CODE TO TYPE: var onSale = true, inventoryLevel = 12, discount = 3; if (onSale && inventoryLevel > 10) { console.log("We have plenty left"); } if (onSale || discount > 0) { console.log("On sale!"); } else { console.log("Full price"); } var rect = { width: 100, height: 50, toString: function() { return "Width: " + this.width + ", height: " + this.height; } }; console.log(rect); console.log("My object rect is: " + rect); console.log("My object rect is: " + rect.toString());

Firefo x: See the (2) next to the line o f o utput? That means that the same line o f o utput is displayed twice. IE:

Interacting Directly in the Console

So far, we've been using co nso le .lo g() to display messages in the co nso le, but yo u can interact directly with the co nso le to display the values o f variables, create new statements, and even mo dify yo ur web page. In yo ur bro wser's co nso le, yo u'll see a pro mpt which indicates where yo u can type yo ur o wn JavaScript. Click in the co nso le windo w next to the pro mpt, and type this: INTERACTIVE SESSION: > onSale true

Note The ">" character is the pro mpt; yo u sho uldn't type this part.

We typed the name o f the glo bal variable o nSale and pressed Ent e r. JavaScript respo nded with the value o f o nSale. Here's what the o utput lo o ks like in the bro wsers Chro me, Safari, Firefo x, and IE: