Learn How To Code PDF

You might also like

You are on page 1of 22

Learn to Code:

The Full Beginner's Guide


By Adam Dachis of Lifehacker.com
You can contact Adam Dachis, the author of this post, at
adachis@lifehacker.com. You can also follow him on
Twitter and Facebook
Learn How to Code Part I:
Variables and Basic Data Tyes
Link to YouTube ideo
!ant to learn how to code but don"t know where to start# !e"$e %ot you co$ered. !e"ll be teachin% you
the basics all week, and here"s your first lesson.
&re$iously we"$e pro$ided you with some resources for learnin% to code and %i$en you a broad
o$er$iew of the process, but now it"s time to %et down to business' !e"re offerin% a short ()( course,
step by step. You can"t learn to code o$erni%ht *or in a week+, but we"$e broken up the basics into a few
lessons that will be released as the first four parts in our brand new Li!ehac"er #ight $chool series.
,ach lesson will be $ideo-based *as you can see
abo$e+, but we"ll also pro$ide you with te.t notes
and files that you can refer to as well. ,ach lesson
is desi%ned to be a mana%eable chunk of
information that you can di%est in under (/
minutes *and often much less+. Althou%h we"re
startin% off our first pro%rammin% lesson at 0'))
A1 &2T, the followin% three lessons will be
released e$ery day at 3')) &1 &2T. Be sure to
come back and $isit us at the end of the day on
Tuesday, !ednesday, and Thursday this week to
finish learnin% the basics.
4ur first lesson is %oin% to be $ery simple and
consist of learnin% about basic $ariables and data
types. For the lessons in this series, we"re %oin% to
use 5a$a2cript as a model because it"s a synta.
that"s pretty easy to understand and it"s somethin%
that anyone with a te.t editor and a web browser can use. Because it"s an ,61A-based lan%ua%e, it
makes understandin% other ,61A-based lan%ua%es *like Action2cript+ much easier to learn. ,$en
better, you"ll find that knowin% how to write 5a$a2cript will make the transition to other ob7ect-oriented
pro%rammin% lan%ua%es much easier. Basically, 5a$a2cript is readily a$ailable to practically anyone
with a computer and a browser, so we think it"s a really %ood startin% point. 4nce you ha$e the basics
down it should be easy to be%in learnin% other lan%ua%es.
Let"s %et started8
%hat &re Variables'
You can think of $ariables as labeled 7ars that store different types of data. !hile there are se$eral kinds
of $ariables, today we"re only %oin% to look at three'
$tring - A strin% $ariable is a strin% of alphanumeric characters and allowed symbols that are
contained within 9uotation marks. For e.ample, :;ello world, <"m ()= years old today8: is an
e.ample of a strin%. 2trin%s can also be contained within sin%le 9uotes, which is useful if you
want to ha$e a strin% with a 9uotation like this' ":< hate the snow,: Laurel said." 2trin%s are
basically used for storin% te.t.
#u(ber - A number $ariable couldn"t be more strai%htforward because all number $ariables
store are numbers. You don"t store them within 9uotes like strin%s. <nstead, numbers can 7ust be
written as they are. <f you want to store the number 0 in a $ariable, you 7ust write 0.
Boolean - A boolean $ariable is one of two thin%s' true or false. This data type is kind of like an
on and off switch, so you can ask true or false 9uestions in your code. For e.ample, you mi%ht
ask :is the $ideo currently playin%#: The response you"d %et would be a boolean $ariable. True
would mean the $ideo is currently playin% and false would mean it is not.
2o how do you putt a $ariable to your code *or declare a $ariable, as it"s more traditionally called+# <n
5a$a2cript, all you need to do is this'
myVariable = "Hello world!";
There are a few of thin%s to notice here. First, the name
myariable. All pro%rammin% lan%ua%es ha$e somethin% called
reser$ed words, which means you can"t use them as $ariable
names. !hat they $aries, but if the name is sufficiently %eneric,
there"s a chance it could be a reser$ed word. To a$oid usin%
reser$ed words and screwin% up your code, 7ust decide on a
namin% scheme for your $ariables. <"$e put :my: in front of my
e.ample $ariable, but you"ll probably want to come up with
somethin% else. 2econd, you"ll notice a semicolon at the end of the
line. A semicolon is like a period at the end of a sentence in many
pro%rammin% lan%ua%es, and that is definitely the case in
5a$a2cript. <n nearly e$ery situation, you need to end your code
sentences with a semicolon so your computer doesn"t %et confused
when readin% it. The semicolon tells the computer, :4kay <"m all
done with this statement.: *>ote' 5a$a2cript is for%i$in%, and
sometimes you can %et away without the semicolon, but it"s %ood
practice.+
4ne more thin% to note is that 5a$a2cript is a loosely-typed lan%ua%e. There are *basically+ two kinds of
lan%ua%es' loosely-typed and strictly-typed. An e.ample of a strictly-typed lan%ua%e is Action2cript
*the lan%ua%e Flash apps are written in+, and the same $ariable declaration we 7ust wrote would look
like this in Action2cript ?'
var myVariable:String = "Hello world!";
The additions you"re seein% are the word var and the word String *with a colon in front of it+. The word
$ar tells the computer we"re about to declare a $ariable. The '2trin% attached to the $ariable"s name tells
the computer what type of $ariable it is and to not accept any other type. This is the reason for the term
strictly-typed. A loosely-typed lan%ua%e like 5a$a2cript is more fle.ible and doesn"t re9uire any of that.
This makes your code more fle.ible, but some will ar%ue it will also make it more error-prone. !e"re
not %oin% to %et into the pros and cons of strictly- and loosely-typed lan%ua%es here, but it"s %ood to be
aware of the basic differences now as you will most likely encounter them in your pro%rammin%
endea$ors.
>ow that you understand what $ariables are and how they work, we can try usin% them in some actual
5a$a2cript code.
Creating Variables and )sing the *a+a$crit &lert,- Function
Let"s create a simple ;T1L document that we can use to test our $ariables'
You"re %oin% to want to ha$e a better-defined ;T1L document when you"re actually writin% code, but
for our purposes this will work 7ust fine. 2a$e the code abo$e as a file called myscript.html *or anythin%
you want that ends in .html and doesn"t contain spaces or special characters+ and open it up in your web
browser. You"ll see absolutely nothin% other than :1y 2cript: in the title bar. !e still ha$e more work
to do. First, let"s declare a $ariable inside of the script ta%'
myariable @ /A
;ere we"$e 7ust declared a number. Let"s look at other $ariable types we can declare
myNumber = 5;
myString = "Hello world!";
myBoolean = true;
That %i$es us a number, a strin%, and a boolean. >ow let"s take that my2trin% $ariable and actually do
somethin% with it'
myNumber = 5;
myString = "Hello world!";
myBoolean = true;
alert(myString);
You"ll notice <"$e added the line alert(myString);. This calls a built-in 5a$a2cript function *we"ll
learn more about these later+ called alert() which creates a pop-up dialo%ue bo. for users to interact
with.
You ne$er really want to use these in practice becauseBas any
internet user likely knowsBalert bo.es are $ery annoyin%, but they
make for a %ood way to test your code, to make sure it works,
while you"re writin%. The parenthesis followin% alert allow you to
pro$ide alert with data it mi%ht need. >ot all functions will re9uire
that you %i$e it information, but alert needs to know what to alert
the user. <n this case, we %a$e it my2trin%, so the user will recei$e
a popup notification that says :;ello world8: Try this with your
other $ariables to %et popups with a number and a boolean $alue.
!hy %i$e alert*+ a $ariable and and not 7ust %i$e it the contents of the $ariable# !ell, if you said
alert*:;ello world8:+ you"d %et the same result in this e.ample, but $ariables are called $ariables
because they vary. The idea is that the contents, or $alues, of these $ariables will chan%e as users
interact with the pro%rams you write.
Learn to Code Part II:
%or"ing %ith Variables
Link to YouTube $ideo
<n our second :Learn to 6ode: lesson, we"ll be takin% a look at how to actually work with the $ariables
and data types we learned about in the first lesson. Cet e.citedBit"s time to put your new knowled%e to
work8
These lessons work best with the video, which you can see above, but we're also providing text for
reference below. Even if you do prefer to read, the videos will be more explicit and demonstrate how to
do everything we're discussing. f the text seems a bit too complicated, be sure to watch the video.
Creating a Variable $tate(ent
!e"re %oin% to create a $ariable statement so you can see how useful $ariables can be. ,$erythin% we"ll
be doin% in this lesson will take place between the <!ri"t# ta%s you created in your myscript.html
in the pre$ious lesson. First we"re %oin% to create four $ariables and then we"re %oin% to use them to
make a sentence. ;ere are the four $ariables you want to create'
var myName = "$dam";
var %ood&y"e = "a""le";
var number'aten = (;
var number&otal = );
You don"t ha$e to set their $alues to what you see abo$e. For e.ample, if your name is 1elissa then you
mi%ht want to set the $alue of the my>ame $ariable to :1elissa: instead. <f your name is really terrible
and embarrassin% *e.%. ;erpe+, it"s okay if you use mine. Anyway, let"s make a new $ariable called
my2tatement and combine our four $ariables to make a sentence. To do that we 7ust set my2tatement
like this'
var myStatement = myName * " ate " * number'aten * " " * %ood&y"e * "+";
You"ll notice that < added some words and spaces to make it a coherent sentence and a period so it"s
properly punctuated. You can assemble this sentence howe$er you"d like, but the abo$e e.ample will
%i$e you somethin% that works well. >ow, let"s test it. Dse the alert*+ function to $iew what we came up
with'
alert(myStatement);
!hat you should see in the alert is' $dam ate ( a""le+
4kay, %reat, so you 7ust wrote a useless sentence and didn"t e$en use one of the $ariables. >ow what#
Let"s do a little math. Try this sentence'
var myStatement = myName * " ate " * number'aten * " " * %ood&y"e *
", leaving " * (number&otal - number'aten) * " " * %ood&y"e * " le%t
over+";
!hat 7ust chan%ed# !ell, we altered the statement a little bit to also inform the user of how many
apples were left o$er after you or < had our way with the apples a$ailable to us. The important thin% to
notice here is the part of the code that says
(number&otal - number'aten). !hen you
add a strin% $ariable to practically anythin% *e$en a
number+, it creates another strin%. <f you add two
numbers to%ether, it actually does the math
*meanin% = E ? will e9ual / and not =?+. Because
we ha$e other strin%s in the mi., we need to make
sure this mathematical operation is carried out as
math first. By puttin% the mathematical statement in
parenthesis, the computer will know to perform that
operation first before considerin% it part of the bi%
lon% strin% $ariable we"re creatin%. 4b$iously we"re
not addin% these two numbers to%ether, but the
same rules apply for all mathematical operations.
!ith the chan%es to my2tatement made, alert*my2tatement+ should now show' $dam ate (
a""le, leaving . a""le le%t over+
That"s all we"re really %oin% to co$er today, but before you call it 9uits be sure to chan%e the contents of
your $ariables and see how my2tatement automatically updates when you reload the pa%e in your web
browser. This is your first small look at what makes pro%rammin% so useful. Feady for what"s ne.t# Co
check out Lesson ?, which tackles arrays and lo%ic statements. This is where thin%s %et a bit more
challen%in%, but also a lot more fun.
Learn to Code Part III:
&rrays and Logic $tate(ents
Link to YouTube ideo
You"$e mastered the basics of $ariables and made it half way throu%h our course, but are you up to the
challen%e of arrays and lo%ic statements# 4f course you are. Let"s %et started8
These lessons work best with the video, which you can see above, but we're also providing text for
reference below. Even if you do prefer to read, the videos will be more explicit and demonstrate how to
do everything we're discussing. f the text seems a bit too complicated, be sure to watch the video.
This is where thin%s %et a bit more complicated. There"s no need to be intimidated by what"s to come,
but 7ust know you mi%ht hit a point of frustration because we"re %oin% to co$er some of the more
comple.Bbut incredibly usefulBstuff today. This is %oin% to be the hardest *and lon%est+ part of the
be%inner lesson, but you can do it. You 7ust may need to rewind and practice a little bit more than with
the pre$ious two lessons.
First, we"re %oin% to learn about arrays. After that, we"re %oin% to take a look if statements and for
loops, and also how to use those tools with your array.
&rrays
An array is a type of $ariable, but it"s more like a bo. with a bunch of sections. Dnlike the simple
$ariables we"$e discussed before, arrays can contain more than one piece of data. Let"s take a look at
how an array can be defined and then we"ll talk about what it all means.
var my$rray = new $rray("/ia", "0eorge", "$dam", "1aloma", "2e%%rey");
<"$e 7ust created an array called my$rray that contains fi$e names. ,ach is separated by a comma and
each name is in 9uotes because they"re strin%s *if you for%ot what a strin% is, refer back to lesson one+.
As you mi%ht ha$e %uessed, arrays are really useful for storin% a bunch of similar data inside of one
$ariable for easy access. <t"s kind of like a mini database. !hen you want to access an item in an array
you do so by number.
my$rray345
The abo$e would resol$e to Lisa, because Lisa is the first name in the
array. <f you chan%ed the ) to a (, it would resol$e to Adam. <f you put
a number beyond the number of items currently in the array *like (=+,
you won"t %et anythin% at all.
That"s basically how arrays work. >ot too tou%h, ri%ht# There"s a ton
more that you can do with arrays *e.%. sortin%, splicin%, searchin%, etc.+
but we"re not %oin% to %et into all of that here. <f you"d like to skip
ahead a little bit and take a look at array methods in 5a$a2cript, check
this out. For now, thou%h, that"s all the information you really need.
For Loos
The %or loop is %oin% to be the most complicated thin% we"re %oin% to deal with today, and we"re
lookin% at it before the i% statement because we"re %oin% to use an i% statement to modify its
beha$ior. 2o what is a %or loop e.actly# Basically, a %or loop runs a chunk of code a specified
number of times and counts that number as it mo$es alon%. <ma%ine you"re a number $ariable called i.
*You can pretend that stands for < as in yourself, but it really stands for iterator.+ As i, you need to run a
mile and you"re at the startin% line of a 9uarter-mile track. To complete a mile, that means you ha$e to
run four laps around the track. Fepresented as a %or statement, that mi%ht look somethin% like this'
%or (i=4; i<.; i**)
6
run();
7
Let"s break this down. !hen you say %or, you"re
tellin% the computer you"re declarin% a %or statement.
That should make sense. That"s pretty much the same
as sayin% var before declarin% a $ariable. That"s the
easy part. The complicated part happens inside the
parentheses. Let"s look at each part indi$idually.
i./
!hen you use i<8!ode in t9e %or loo", it: a variable you 9ave to
de!lare+ ;t: not <ut t9ere %or you to ue+ =ou !ould ue any
letter, or a e>uen!e o% letter+ ;t doen:t really matter w9at you
!all t9i variable, but traditionally i is the way to %o. Because you"re declarin% it
inside of the %or loop, you can reuse it in another loop later. This $ariable is local to the %or loop and
won"t conflict with stuff outside of it. !hat we"re doin% here is settin% it to ). You don"t ha$e to start at
), but in this instance *and $irtually every other situation where you"ll use a %or loop+ it makes sense.
!e ha$en"t run any laps yet, so we"re startin% at Gero.
i01
A %or loop is desi%ned to run a bunch of code until you tell it to stop. This middle portion tells the for
loop how lon% to run. !e only want to run a mile, which is four laps, so we"re tellin% the %or loop that
so lon% as the $ariable i is less than H, keep %oin%. <f we wanted to run two miles, we could chan%e it
to i<?.
i22
The last condition is $ery simple' increase i by ( e$ery time this loop completes. You can use EE or B
to increase or decrease *respecti$ely+ a number by ( anywhere else in your code, too, but chances are
you"ll use it most with %or loops. This part is $ery important because we"re tellin% the for loop to stop
runnin% when i<8!ode i no longer le t9an t9e number .+ Be!aue i starts at
), we need to increment i by one each time the loops runs or it will run fore$er.
Inside the Curly Braces
The curly braces IJ currently has run*+ in it, but in this e.ample that"s not a real function. Basically,
you put whate$er code you want to run inside the curly braces. They"re 7ust around to section off the
specific code you want to run.
3ne 4ore Ti(e5 Please6
4kay, let"s 7ust run throu%h this one more time because it"s sort of complicated *or, at least, it was for
me the first time < learned it+'
The %or tells the computer that we"re definin% a %or loop.
i=4 sets a $ariable called i e9ual to ), which is our startin% point.
i<. tells the %or loop to stop once i is no lon%er less than the number H.
i** tells the %or loop to increment i by ( after each time it finishes runnin% the desi%nated
code.
All the desi%nated code that the %or loop is supposed to run needs to be placed inside the curly
braces.
Let's Put It to )se
4kay, let"s now make a %or loop that loops throu%h our array and alerts us of each name in the array.
That code should look somethin% like this'
%or (i=4; i<5; i**)
6
alert(my$rray3i5);
7
This real e.ample should look $ery similar to the fake e.ample we 7ust dissected e.cept for one thin%'
my$rray3i5. ,arlier we looked at how we can access the contents of an array by number, so
my$rray345 will %i$e us somethin% different than my$rray3@5. Because i is a number that
chan%es as the %or loop runs, each time the loop will access a different point in the array. This sa$es
you the trouble of writin% the code out fi$e times.
4kay, but what if we don"t know the len%th of the array# Fi%ht now we know there are fi$e elements,
but if you make a chan%e we"ll either be runnin% the loop more than we need to or we won"t be runnin%
it enou%h. !hat we want to do is to run the %or loop until we"$e accessed the entire array. That
re9uires one little alteration'
%or (i=4; i<my$rray+lengt9; i**)
6
alert(my$rray3i5);
7
To make life easier, 5a$a2cript *and most lan%ua%es that use arrays+ ha$e a property built in to all
arrays you create. *Actually, there are a bunch of different properties but we"re only %oin% to look at
this one ri%ht now+. This property, called lengt9, %i$es you the number of items in the array. 2o,
instead of sayin% i<5 we"ll 7ust say i<my$rray+lengt9 and the %or loop will run until it"s run out
of items in the array.
Did you sur$i$e all that# <f you did, that"s mainly what you need to know about %or loops. There are
few more e.amples in the $ideo up top, so be sure to check it out if you want to see a few other thin%s
you can do with them.
I! $tate(ents
<f statements are probably the easiest type of lo%ic statement to understand. They"re powerful, too, so it
can be easy to %et addicted to them. >o$ice coders tend to clin% to if statements because it seems that if
you ha$e enou%h of them, you can do 7ust about anythin%. That is true, if you don"t mind losin% your
mind in the process. You can write some fairly comple. code that operates on if statements, but you"d
need a lot of them and it will dri$e you craGy. 2o, althou%h you"re probably %oin% to lo$e them, don"t
o$eruse them. Too many ifs do not make for efficient, %ood code.
2o what is an if statement# <t"s basically a statement that says if the specified condition is true, then run
this block of code. <t can also be used to say, if the first condition isn"t met, do this instead. You can also
check if an alternate condition is met if the first one fails. For e.ample, if you wan to wash your do% if
your do% is blue, you can use an if statement to find out and wash the do% if it turns out to be blue.
;ere"s how that could look as a piece of code'
i% (myAog == "blue")
6
wa9Aog();
7
Like we"$e seen before, i% tells the computer that
we"re declarin% an if statement. <n parentheses, we"re
definin% the condition. You"ll see we ha$e a $ariable
called myDo%, which presumably contains a simple
piece of information' the color of your do%
represented as a strin%. <t could be :red: or :%reen: or
:blue:, but we don"t know yet. To find out, we"re
%oin% to ask if myDo% is e9ual to :blue: to find out if
it"s actually blue. To test for e9uality, we use @@. <f
you use a sin%le @ then you are settin% the $alue of a
$ariable. <f you use two @@ then you"re testin% to see
if one $ariable is e9ual to another, or 7ust e9ual to
some kind of data. <f the do% turns out to be blue *meanin% if the condition is met and myDo% is e9ual
to :blue:+, then the if statement will allow the code in curly braces IJ to be run. <n this e.ample, the
code inside the curly braces is wa9Aog();. !hile washDo%*+ is not a real function *not yet,
anyway+, if it were it would presumably %o forth and wash the blue out of your do%.
4kay, so how can we apply this in our code# !ell, the $ideo will walk you throu%h a more comple.
e.ample but we"re 7ust %oin% to test for someone"s name. Let"s say you included my name *Adam+ in
the array and you wanted to recei$e an alert only if my name comes up. !ell, we can can combine your
for loop and your if statement to do 7ust that'
%or (i=4; i<my$rray+lengt9; i**)
6
i% (my$rray3i5 == "$dam")
6
alert("; %ound " * my$rray3i5 * " in t9e array!");
7
7
Basically, we"$e 7ust put an if statement inside of the for loop, and our if statement is now askin% if any
position in the array is e9ual to Adam rather than askin% if a simple $ariable, like myDo%, is e9ual to
:blue:.
Cot all of that# Cood8 <f you made it throu%h this lesson it"ll be smooth-sailin% with the ne.t one. <f
you"re ready, mo$e on to lesson H where we"ll learn about functions and makin% a simple %uessin%
%ame.
Learn to Code Part IV:
)nderstanding Functions and
4a"ing a Guessing Ga(e
Link to YouTube ideo
<f you"$e made it this far in our pro%rammin% lessons, you"$e arri$ed at the reward. Today we"re
learnin% about functions and then we"re %oin% to make a $ery simple %uessin% %ame.
These lessons work best with the video, which you can see above, but we're also providing text for
reference below. Even if you do prefer to read, the videos will be more explicit and demonstrate how to
do everything we're discussing. f the text seems a bit too complicated, be sure to watch the video.
Today is our last-ish lesson *there will be an :epilo%ue: with a mini-lesson on best practices and
additional resources followin% this pone+, and we"re %oin% to co$er two thin%s' functions and makin% a
$ery simple %uessin% %ame. <f you made it throu%h Lesson ?, chances are you"ll find functions pretty
easy to learn. !e"re %oin% to tackle that first and then use that knowled%eBplus a little ;T1LBto put
the %ame to%ether.
%hat the F is a Function'
4h, come on, you already know all about functions. You"$e been usin% one this entire time' alert*+. A
function is basically a means of callin% a lar%e chunk of code with 7ust a tiny bit of te.t. Functions are
kind of like the te.t e.pansion of pro%rammin%. !hile you"$e used alert*+, that"s 7ust a built-in function
*of which there are many in 5a$a2cript and all pro%rammin% modern ob7ect-oriented pro%rammin%
lan%ua%es+. Today, we"re %oin% to create our own function that will e$entually help us make a %uessin%
%ame. First, let"s take a look at how a function is declared in your code'
%un!tion nameB%Cun!tion(variable)
6
7
This should look pretty familiar. Functions look a lot like for loops and if statements. Let"s break down
what we"re lookin% at. First, we start with the word %un!tion to tell the computer that we"re definin%
a function. >e.t we ha$e to name that function. <n this e.ample it"s titled nameB%Cun!tion but
you"d normally name it somethin% relati$e to what it does *like how alert*+ creates an alert dialo%ue bo.
when used+. After the name of the function are parentheses. You"re not re9uired to put anythin% inside
the parentheses, but if you need to %i$e the function some information *which is called passin% it
$ariablesKa $ariable+ you need to specify the name of the $ariables that you"ll be usin% inside of the
function. This mi%ht be a little confusin% ri%ht now, but we"re %oin% to look at it a bit more later so
don"t worry. Finally, we ha$e our curly braces at the end. ,$erythin% the function needs to do will %o
inside of these curly braces.
>ow that you know how a function is defined and what it does, let"s put it to use8
4a"ing a $i(le Guessing Ga(e in *a+a$crit
There are two parts to this process' the function and the interface *which is basically a form where the
user can enter a number+. First, we"ll start with the function.
4a"ing the Function That 7uns 8our Ga(e
To make the %ame, we"re %oin% to need to make a function that reacts to user input. Let"s put to%ether a
function that does that'
var "er%e!tNumber = @D;
%un!tion !9e!E$""le(num$""le)
6
i% (num$""le == "er%e!tNumber)
6
alert("=ou ate t9e "er%e!t number o% a""le!");
7
ele i% (num$""le # "er%e!tNumber)
6
alert("=ou ate way too many a""le+");
7
ele i% (num$""le < "er%e!tNumber)
6
alert("=ou didn:t eat enoug9 a""le+");
7
7
4kay, that"s a lot to look at so let"s break it down. First, < created a $ariable called "er%e!tNumber
and set it to @D. This is the number the user is %oin% to try to %uess in our %ame. You can set this
number to anythin% you want, and if you want a few bonus points you can try implementin% this
randFan%e*+ function to randomiGe the number each time the pa%e loadsBbut let"s do the basic stuff
first.
After the $ariable "er%e!tNumber is defined, we"re creatin% a function called !9e!E$""le and
passin% it a $ariable called num$""le. This means that when we call this function we"ll need to %i$e
it a number, which would look somethin% like checkApples*/+. That number is %oin% to come from the
user, howe$er, so we"re not %oin% to talk about that 7ust yet.
<nside the function is an if statement with three conditions. The first condition checks to see if
numApplesBthe number $ariable passed to the checkApples functionBis e9ual to perfect>umberB
the $ariable we set earlier *that"s the answer the user will be tryin% to %uess. <f that condition is met, the
user will %et an alert that con%ratulates them on choosin% the correct number. <f not, the second
condition will check to see if they %uessed too hi%h. <f they %uessed a number lar%er than
perfect>umber they"ll be alerted that they ate too many apples. Basically the same thin% happens with
the third condition, but if they %uessed too low of a number.
That"s all there is to the function, and it"s pretty simple. But how do we re9uest a number from the user#
That"s %oin% to re9uire combinin% a little 5a$a2cript with a little ;T1L.
4a"ing a )ser Inut For(
1akin% a form is somethin% you mi%ht"$e done before if you"$e e$er used ;T1L. <t"s pretty easy. First,
you"ll need to put this in the LbodyM of your ;T1L document'
<%orm#
<in"ut ty"e="teFt" name="num$""le" id="num$""le" 8#
<in"ut ty"e="Submit" name="Submit" 8#
<8%orm#
That will %et you a super simple form with a te.t bo. and a submit button, but it won"t do anythin%.
First, we need to add some stuff to the form ta% to connect the input to your !9e!E$""le()
function'
<%orm met9od="1BS&" name="a""leCorm" onSubmit="!9e!E$""le(do!ument+a""leCorm+num
$""le);"#
2o what did we 7ust add, e.actly# First, we told the form to use the &42T method. This isn"t terribly
important because it"ll work either way, but the &42T method is a bit cleaner for what you"re doin%
here. &42T won"t put all the $ariables submitted in a form into the DFL, but C,TByour other option
Bwill. 2econd, we named the form applesForm because we"re %oin% to need to refer to it by name
when specifyin% where the user input te.t bo. is in the document. Lastly, we ha$e somethin% called
onSubmit which lets us e.ecute some 5a$a2cript code when the submit button is pressed. <n most
forms there would also be a property called action, tellin% the form where to %o after submittin%, but we
7ust want to stay on the pa%e so we don"t need it. Cettin% back to on2ubmit, you can see we"$e basically
set it to the checkApples*+ function. <nstead of %i$in% checkApples*+ a number, howe$er, we"$e %i$en it
do!ument+a""leCorm+num$""le+value. This is how we"re referencin% the user input te.t
bo. in our form. !e"re doin% this by usin% the Document 4b7ect 1odel, or D41, in 5a$a2cript. Let"s
break this down'
docu(ent - Your ;T1L document.
alesFor( - The name of the form we created.
nu(&les - The name of the te.t field we created for user input, which is inside of the
applesForm.
+alue - !e don"t want the te.t field we created, but what"s inside of the te.t field. You need to
attach value to the end of a te.t field you can %et the $alue of it and not a reference to the te.t
field ob7ect that contains it.
4nce you"$e %ot all of this in your code, you"re done8 2a$e the pa%e, reload it in the browser, and try
%uessin% your number. Aim too hi%h, too low, and then %uess it correctly. You should find that you %et
the responses you defined in your code alerted to you each time you %uess. 2o, con%ratulations, you
7ust made your first %ame8
It's &l(ost Ti(e to $ay Goodbye
!ell that about does it for our basic codin% lessons. !e hope you"$e en7oyed them and feel ready to
approach more complicated stuff as you be%in your foray into the pro%rammin% world. By popular
demand, we"ll be doin% one more post tomorrow about a few pro%rammin% best practicesBmainly
commentin% your codeBas well as includin% additional resources to help you learn more about
e$erythin% we"$e discussed and where to %o ne.t.
Learn to Code 9ilogue:
Best Practices and &dditional 7esources
Link to YouTube ideo
6on%ratulations, you"$e learned the basics of pro%rammin%8 That"s wonderful, but you"d better not %o
out into the world and write crappy code. Before we set you free, here are some best practices and %ood
thin%s to keep in mind.
Best Practices
Co((ent 8our Code and Co((ent It %ell
You can comment your code in two ways' one way for sin%le-line comments and one way for multi-
line comments. 2in%le-line comments start with 88 in 5a$a2cript. 4ther lan%ua%es use other characters,
like the N si%n, so be sure to check before you start puttin% forward slashes e$erywhere. To make a
multi-line comment, you 7ust put your comment in between KO and OK. ;ere"s an e.ample of both'
88 Single-line !omment
8G Hulti-line !omment
$not9er line
Bne more! G8
You"ll mostly use sin%le-line comments for makin% actually comments about your code and use multi-
line comments to remo$e parts of your code without deletin% them. This makes it easier to isolate a
problem when you"re debu%%in%.
2o how do you write %ood comments# !ell, you"re probably %oin% to feel inclined in the be%innin% to
write comments that e.plain how e$erythin% works. <f that helps you remember, that"s not a bad thin%
to do in the beginning. For the most part, howe$er, you"re %oin% to be namin% your functions and
$ariables clearly and you won"t need to e.plain how somethin% works or what a particular function
does because that clarity already e.ists. !hat you want to e.plain in your comments is information the
code can"t already tell you' why you made the choices you made. Anythin% that will help another
pro%rammer *or yourself, when you look back at this code monthsKyears later+ better understand your
code is worth puttin% in a comment. <f it"s redundant information, it"s not helpful. <f it helps brin%
clarity to the code you"$e written, it is.
Don't )se the eval() Function
4h boy, the e$al*+ function isn"t the easiest thin% to e.plain. <f this e.planation doesn"t make enou%h
sense and the $ideo doesn"t %et the idea across either, 7ust remember not to use e$al*+ whene$er
possible. The main reason is that e$al*+ slows down your code. The other main reason is that you can
almost always find a better way to %et the 7ob done than to use e$al*+.
2o what does e$al*+ do# !ell, it"s short for e$aluate and it e$aluates a strin% as if it were a $ariable. 2o
let"s say you had a $ariable called numberB%$""le and wanted to alert it to a user. You could do it
like this'
alert(numberB%$""le);
!hat if you put number4fApples in 9uotes# !ell, the alert wouldn"t alert whate$er number you set
number4fApples to, but instead 7ust alert the te.t :number4fApples:. ,$al sol$es that problem'
alert(eval("numberB%$""le"));
!hy would you e$er use this# !ell, someday you"ll probably find a reason why e$al*+ will be useful to
you. Cenerally it"s because you don"t necessarily know the name of the $ariable, or the name of the
$ariable you need is contained in another $ariable. <t %ets complicated and we"re certainly not %oin% to
%et into it here, so 7ust remember' don't resort to using eval!" unless there is no other wayBand < can"t
think of a situation where you wouldn"t ha$e an alternati$e.
Create &rrays and 3b:ects Faster
!e didn"t really talk much about ob7ects but you should definitely remember arrays from Lesson ?.
!hen we created them earlier, we did it like this'
var my$rray = new $rray("item@", "itemD", "et!");
You don"t really need the new $rray statement, howe$er, as you can 7ust do it like this'
var my$rray = 3"item@", "itemD", "et!"5;
You also ha$e a similar shortcut with ob7ects, a type of $ariable we ha$en"t discussed yet. 4b7ects are
$ery similar to arrays in that they can hold more than one piece of data at a time, but they"re accessed a
little differently and you can easily name each item in your ob7ect. <t"s really easy to see the difference
when you look at the lon% way of creatin% an ob7ect'
var myBb<e!t = new Bb<e!t();
myBb<e!t+item4@ = "1onie";
myBb<e!t+item4D = "Ini!orn";
myBb<e!t+item4( = "Jainbow";
The lon% way works fine, but here"s an easier way to do it'
var myBb<e!t =
6
item4@: "1onie;
item4D: "Ini!orn";
item4(: "Jainbow";
7
These shortcuts make writin% your code a bit faster and make your code a lot easier to read.
)se 8our $e(icolons6
5a$a2cript does not always re9uires you to end a statement with a semicolon, but you should do it
anyway. !e discussed this a little bit in Lesson (, but it"s worth repeatin%. You"re almost %uaranteed to
run into problems if you"re careless about usin% your semicolons, so whene$er you need to end a
statement *a sentence of code+, don"t for%et to drop a ; at the end.
&dditional 7esources
>ow that you"$e learned the basics, hopefully you want to learn more and start makin% some awesome
pro%rams. ;ere are a few additional resources to help you learn more 5a$a2cript as well as some other
lan%ua%es.
D3 #3T )se %;$chools
!hen you search for help online, one of the first results is often !?2chools *which <"m e.plicitly not
linkin% to here+. The short $ersion is that it sucks. <t"s full of errors, it"s missin% information, and while
it"s not ())P useless it isn"t a %ood resource. A$oid it. For the lon% $ersion, $isit !?Fools, a site put
to%ether by the 7Query team *and some other helpers+.
General 7esources
1oGilla !eb De$elopment Fesources
6arl;&ro%rammin% Lessons are a %reat collection of pro%rammin% lessons posted to Feddit.
Lynda.com offers a lar%e selection of online education, but it"ll cost you. The lessons are
e.cellent, howe$er, and < feel it"s worth the cost. <t costs around R=/ *dependin% on the type of
account you %et+, so if you can fit a course into a month you really won"t be payin% that much in
the end.
1<T 4pen6ourse!are"s <ntroduction to 6omputer 2cience and &ro%rammin% is a %reat bi%
pro%rammin% learnin% resources complete with $ideo lessons.
*a+a$crit
<f you"re a Firefo. user, you need to ha$e Firebu%. 1ost other browsers ha$e built-in de$eloper
tools, but Firebu% Lite is a bookmarklet that will work in pretty much any modern browser.
5a$a2cript' The Definiti$e Cuide is a %reat book to read if you want a bible"s worth of
information.
Dou%las 6rockford"s :The 5a$a2cript &ro%rammin% Lan%ua%e: $ideos will teach you the basics
*a%ain+ and ad$anced stuff, too.
5a$a2cript, 5a$a2cript is a %reat blo% by An%us 6roll that"ll teach you a few thin%s with each
post.
Learn Ad$anced 5a$a2cript is an effort by 5ohn Fesi% to, well, teach you ad$anced 5a$a2cript.
!hen you"re ready to really step thin%s up, downloadin% and learnin% to use libraries like
7Query, Do7o, 1ooTools, and Yui will make your life much, much easier. !hen you %et to the
user interface stuff, check out 7Query for Desi%ners for some %reat tutorials.
PHP
The official &;& 1anual is how < learned &;&. < 7ust searched for functions, browsed around,
and learned by e.ample. &;& was also the first lan%ua%e < learned, so it"s not as if < knew what <
was doin%. The manual is $ery informati$e and has %reat e.amples. !hile <"d probably
recommend learnin% pro%rammin% basics before di$in% ri%ht in, you 7ust did in this series so
playin% around with &;& shouldn"t be too tou%h for you.
Send offers up &;& for the Absolute Be%inner. Send is a company, but also a powerful &;&
framework. <f you want to start from step Gero *which isn"t a bad idea+, check it out.
7uby<7ails
A%ile !eb De$elopment with Fails is how < learned Fuby and Fails. < can $ouch for it bein%
$ery %ood, althou%h technically < read the second edition.
Fuby4nFails.or%"s screencasts are another %reat way to learn.
&ction$crit ,Flash<Cross=Plat!or( &I7 &s-
%otoAndLearn is filled with e.cellent tutorials that teach you how to make really useful stuff in
Action2cript, whether you"re usin% Flash or Fle. to deploy to the desktop or web. 4ne of the
best ways to learn is by doin%, and %otoAndLearn offers plenty of opportunities to do 7ust that.
4obile & De+elo(ent
2tandford"s i&hone Application De$elopment is a course on iTunes D that you can download for
free. You"ll also find the class resources here.
The Android De$eloper site is a %reat resource *especially the %uide+ for learnin% how to
de$elop for the Android platform. <t"s a$ailable for free from Coo%le.
2pecial thanks to my friend 6olin 2no$er for his input. ;e currently works on 7Query and is much
smarter than me. Follow him on Twitter. Also, a special thanks to 6n,Y#8 for a few of the resources
listed here and makin% sure < had nothin% %ood to say about !?2chools.

You might also like