Transcription of JavaScript Basics
1 JavaScript BasicsBased on jQuery Fundamentals by Rebecca Commons Attribution-Share Alike USContents1 JavaScript Basics3 Overview..4 Syntax Basics ..4 Operators..4 Basic Operators..4 Operations on Numbers & Strings..5 Logical Operators..5 Note..5 Comparison Operators..6 Conditional Code..6 Note..6 Truthy and Falsy Things..7 Conditional Variable Assignment with The Ternary Operator..7 Switch Statements..7 Loops..8 The for loop..8 The while loop..9 The do-while loop..9 Breaking and continuing..10 Reserved Words..10 Arrays..11 Objects..11 Functions..12 Using Functions..12 Self-Executing Anonymous Functions.
2 13 Functions as Arguments..13 Testing Type..13 Thethiskeyword..14 Note..15 Scope..16 Closures..1721 JavaScript BasicsHomeSmooth CoffeeScriptFormatsMarkdownPDFHTML31 JavaScript BasicsOverviewJavaScript is a rich and expressive language in its own right. This section covers the basic concepts ofJavaScript, as well as some frequent pitfalls for people who have not used JavaScript before. While itwill be of particular value to people with no programming experience,even people who have used otherprogramming languages may benefit from learning about some of the peculiarities of you re interested in learning more about the JavaScript language, I highly recommendJavaScript: TheGood Partsby Douglas BasicsUnderstanding statements, variable naming, whitespace, and other basic JavaScript simple variable declarationvarfoo= helloworld ;Whitespace has no meaning outside of quotation marksvarfoo= helloworld ;Parentheses indicate precedence2 * 3 + 5; //returns11.
3 Multiplicationhappensfirst2 * (3 + 5); //returns16;additionhappensfirstTabs enhance readability, but have no special meaningvarfoo=function() { ( hello );};OperatorsBasic OperatorsBasic operators allow you to manipulate hello ;varbar= world ; (foo+ +bar); // helloworld Multiplication and division2 * 3;2 / 3;Incrementing and decrementingvari= 1;varj= ++i; //pre-increment:jequals2;iequals2vark=i+ +; //post-increment:kequals2;iequals341 JavaScript BasicsOperations on Numbers & StringsIn JavaScript , numbers and strings will occasionally behave in ways you might not vs.
4 Concatenationvarfoo= 1;varbar= 2 ; (foo+bar); // a string to act as a numbervarfoo= 1;varbar= 2 ; (foo+Number(bar));The Number constructor,when called as a function (like above) will have the effect of casting its argumentinto a number. You could also use the unary plus operator, which does the same thing:Forcing a string to act as a number (using the unary-plus operator) (foo+ +bar);Logical OperatorsLogical operators allow you to evaluate a series of operands using AND and OR AND and OR operatorsvarfoo= 1;varbar= 0;varbaz= 2;foo||bar; //returns1,whichistruebar||foo.
5 //returns1,whichistruefoo //returns0,whichisfalsefoo //returns2,whichistruebaz //returns1,whichistrueThough it may not be clear from the example,the||operator returns the value of the first truthy operand,or,in cases where neither operand is truthy,it ll return the last of both operands. The&&operator returnsthe value of the first false operand, or the value of the last operand if both operands are sure to consultthe section called Truthy and Falsy Things for more details on which values evaluatetotrueand which evaluate ll sometimes see developers use these logical operators for flow control instead of usingifstate-ments.
6 For example://dosomethingwithfooiffooistruth yfoo&&doSomething(foo);//setbartobazifba zistruthy;//otherwise,setittothereturn// valueofcreateBar()varbar=baz||createBar( );51 JavaScript BasicsThis style is quite elegant and pleasantly terse; that said, it can be really hard to read, especially forbeginners. Ibring it up here so you ll recognize it in code you read,but Idon t recommend using it untilyou re extremely comfortable with what it means and how you can expect it to OperatorsComparison operators allow you to test whether values are equivalent or whether values are operatorsvarfoo= 1;varbar= 0;varbaz= 1 ;varbim= 2;foo==bar; //returnsfalsefoo!
7 =bar; //returnstruefoo==baz; //returnstrue;careful!foo===baz;//return sfalsefoo!==baz;//returnstruefoo===parse Int(baz); //returnstruefoo>bim; //returnsfalsebim>baz; //returnstruefoo<=baz; //returnstrueConditional CodeSometimes you only want to run a block of code under certain conditions. Flow control viaifandelseblocks lets you run code only under certain controlvarfoo=true;varbar=false;if(bar) { ( hello! );}if(bar) {//thiscodewon trun}else{if(foo) {//thiscodewillrun}else{//thiscodewouldr uniffooandbarwerebothfalse}}NoteWhile curly braces aren t strictly required around single-lineifstatements,using them consistently,evenwhen they aren t strictly required, makes for vastly more readable mindful not to define functions with the same name multiple times within separateif/elseblocks,as doing so may not have the expected JavaScript BasicsTruthy and Falsy ThingsIn order to use flow control successfully,it s important to understand which kinds of values are truthy and which kinds of values are falsy.
8 Sometimes, values that seem like they should evaluate one wayactually evaluate that evaluate totrue 0 ; anystring ;[]; //anemptyarray{}; //anemptyobject1; //anynon-zeronumberValues that evaluate tofalse0; ; //anemptystringNaN; // JavaScript s not-a-number variablenull;undefined; //becareful--undefinedcanberedefined!Con ditional Variable Assignment with The Ternary OperatorSometimes you want to set a variable to a value depending on some condition. You could use anif/elsestatement, but in many cases the ternary operator is more convenient. [Definition: Theternary operatortests a condition;if the condition is true,it returns a certain value,otherwise it returns a different value.]
9 ]The ternary operator//setfooto1ifbaristrue;//otherwi se,setfooto0varfoo=bar? 1 : 0;While the ternary operator can be used without assigning the return value to a variable,this is StatementsRather than using a series of if/else if/else blocks, sometimes it can be useful to use a switch statementinstead. [Definition:Switch statementslook at the value of a variable or expression, and run differentblocks of code depending on the value.]A switch statementswitch(foo) {case bar :alert( thevaluewasbar--yay! );break;case baz :alert( boobaz:( );break;default:alert( everythingelseisjustok );break;}71 JavaScript BasicsSwitch statements have somewhat fallen out of favor in JavaScript ,because often the same behavior canbe accomplished by creating an object that has more potential for reuse, testing, etc.)
10 For example:varstuffToDo= { bar :function() {alert( thevaluewasbar--yay! );}, baz :function() {alert( boobaz:( );}, default :function() {alert( everythingelseisjustok );}};if(stuffToDo[foo]) {stuffToDo[foo]();}else{stuffToDo[ default ]();}We ll look at objects in greater depth later in this let you run a block of code a certain number of try0 , try1 , .., try4 for(vari=0;i<5;i++) { ( try +i);}Note that inLoops even though we use the keyword var before the variable namei,this does not scope the variableito the loop block. We ll discuss scope in depth later in this for loopAforloop is made up of four statements and has the following structure:for([initialisation]; [conditional]; [iteration])[loopBody]Theinitialisations tatement is executed only once, before the loop starts.)