Jquery Fundamentals - JavaScript Basics
Jquery Fundamentals - JavaScript Basics
jQuery Fundamentals
Home
Contents
Feedback
JavaScript Basics
ADDITIONAL RESOURCES
MDN: JavaScript Chrome Developer Tools Overview Fixing these jQuery: A Guide to Debugging Chrome Developer Tools Cheat Sheet Chrome Dev Tools: 12 Tricks to Develop Quicker (video)
CSSconf.eu: Dedicated to CSS and designers, developers and engineers who build the worlds most engaging user interfaces. Sept. 13, Berlin.
jQuery is built on top of JavaScript, a rich and expressive language in its own right. This section covers the basic concepts of JavaScript, as well as some frequent pitfalls for people who have not used JavaScript before. While it will be of particular value to people with no programming experience, even people who have used other programming languages may benefit from learning about some of the peculiarities of JavaScript. Here's a simple JavaScript program that adds a message to the page:
1 2 3 4 5 6 7 8
jqfundamentals.com/chapter/javascript-basics
8/8/13
9 1 0 1 1 1 2 1 3 1 4
In the above example, we use a function called l o g. This is a helper function that is defined by the JavaScript that powers this site it is not a built-in JavaScript function. You can use l o g in the built-in editor for this site, but you'll need to use c o n s o l e . l o g in your normal code, and then view the output in your browser's console. You can try running this program by clicking the and it will copy the code to the built-in editor automatically. Once it's there, you can click the button to execute it; you can also make changes to it. Press the button to return to the original code. It's OK if you don't understand everything that's going on in this program; in the rest of this section, we'll talk about variables, functions, and several other building blocks of JavaScript.
1 2 3 4 5 6 7
/ /T h i si sas i n g l el i n ec o m m e n t v a rf o o ; / * T h i si sam u l t i l i n ec o m m e n t .I tc a ng oo n f o rs e v e r a ll i n e s ,l i k et h i s . * /
You'll also sometimes see multi-line comments used for inline comments:
1f u n c t i o nc o r n i f y (u n i c o r n s/ *i n t e g e r* / ,r a i n b o w s/ *i n t e g e r* /){ 2 3}
jqfundamentals.com/chapter/javascript-basics
2/17
8/8/13
1v a rm y N a m e=' R e b e c c a ' ;
Variable names can be just about anything, as long as they don't begin with a number and don't include a hyphen. You can define one variable per statement:
You can also define multiple variables in a single statement, by separating them with commas:
Once you have assigned a value to a variable, you can use that variable whenever you want to get access to the value you stored.
1l o g (m y N a m e) ;/ /l o g s' R e b e c c a '
Variables are a key ingredient in adhering to the Don't Repeat Yourself philosophy. If you need to use a value more than once, you probably want to store it in a variable. We'll talk more about variables in the next section, Functions.
Functions
Functions are a fundamental building block of JavaScript programs; they provide a way that we can put small pieces of functionality in a neatly-wrapped package. For example, consider a function that adds
jqfundamentals.com/chapter/javascript-basics 3/17
8/8/13
two numbers:
1f u n c t i o n ( a ,b ){ 2 r e t u r na+b ; 3}
This function takes two arguments , a and b. It adds them together, and returns the result. This is a valid bit of JavaScript, but as written, there's no way for us to call our function if we actually want to add two things. We can solve this by assigning our function to a variable:
1v a ra d d T w o N u m b e r s=f u n c t i o n ( a ,b ){ 2 r e t u r na+b ; 3} ;
What we've done here is take a function expression and assign it to a variable. Now that we've done this, we can call our function by using the name of the variable:
1l o g (a d d T w o N u m b e r s ( 1 ,1 )) ;/ /l o g s2
1f u n c t i o na d d T w o N u m b e r s ( a ,b ){ 2 r e t u r na+b ; 3}
This lets us call our function just like we did before, but this approach should be used with caution, as explained in this post. Bottom line: naming functions using the function declaration approach can have unexpected results if you don't fully understand a feature of JavaScript known as hoisting. The details of hoisting are beyond the scope of this guide, but for now we'll stick to assigning function expressions to variables.
8/8/13
What does it mean that a variable is only accessible inside of a function? Give the following code a try:
1 2 3 4 5 6
In the example above, if we'd tried to actually use f o o outside of the function rather than just checking its type our browser would have reported an error, and any code after the line where we used f o o would not run. The next example shows how we can have two variables with the same name, as long as each variable exists in a separate scope. In this example, we declare the variable f o o and assign it the value ' q u x '; then, inside a function, we declare another variable named f o o, and assign it the value
' b a r '. Notice how, outside of the function, the variable f o o does not change, even when we create
1 2 3 4 5 6 7 8
Despite the fact that both variables have the same name, JavaScript considers the two variables as completely separate entities. This is just one of many reasons that it's important to give your variables meaningful names. Variable scope is one of the fundamental concepts of JavaScript, and one of the concepts that people struggle with often. It's important to remember that: you should almost always declare variables with a v a r statement variables declared inside of a function using a v a r statement are not available outside of that function variables declared without a v a r statement are always global Beware that variables that are not declared with the v a r keyword are implicitly global! In the following
jqfundamentals.com/chapter/javascript-basics 5/17
8/8/13
example, the variable a is available outside the function because it wasn't declared with the v a r keyword this is generally undesirable.
1 2 3 4 5 6 7
f u n c t i o nt e s t ( ){ a=1 ; } t e s t ( ) ; l o g (a) ;/ /l o g s1
Objects
As it turns out, most everything we work with in JavaScript is an object in fact, there are only five kinds of values that are not objects: strings (text) booleans (true/false) numbers
u n d e f i n e d n u l l
These values are called primitives , but even some of these values can be treated as though they were objects more on that in a minute. But what's an object? Let's look at an example of a simple object:
The object we've created here has two properties : f i r s t N a m e and l a s t N a m e. We've created it using the "object literal syntax" that is, by putting a set of key-value pairs in { }. Note that, for each pair, there is a colon between the key and the value, and there is a comma between each pair. Note also that there is not a comma after the last key-value pair if you accidentally include a comma after the last pair, you will get errors in older browsers.
Accessing properties
We've stored our object in a variable named p e r s o n, which makes it easy to access its properties, using either dot notation or bracket notation.
jqfundamentals.com/chapter/javascript-basics
6/17
8/8/13
1 2 3 4 5 6 7
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' } ; l o g (' F i r s tn a m e :'+p e r s o n . f i r s t N a m e) ; / /d o tn o t a t i o n l o g (' L a s tn a m e :'+p e r s o n [' l a s t N a m e ']) ; / /b r a c k e tn o t a t i o n
You'll notice that with bracket notation, we used a quoted string for the property name we were after; with dot notation, we just used the literal property name, without quotes. Bracket notation is a useful approach if, say, the name of the property you're after is stored in a variable:
1 2 3 4 5 6 7 8
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' } ; v a rp r o p=' l a s t N a m e ' ; l o g (' L a s tn a m e :'+p e r s o n [p r o p]) ;
1 2 3 4 5 6 7 8 9 1 0
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' } ; p e r s o n . f i r s t N a m e=' B e n ' ; p e r s o n . l a s t N a m e=' A l m a n ' ; l o g (' F i r s tn a m e :'+p e r s o n . f i r s t N a m e) ; l o g (' L a s tn a m e :'+p e r s o n . l a s t N a m e) ;
This aspect of JavaScript is both blessing and curse. It means that objects are incredibly flexible, but it also means that there's no "privacy." Any code can easily overwrite the value of a property of any object to which it has access another reason why it's important to keep variables out of the global scope unless it's OK for other code to modify them.
Object methods
Methods of an object are just properties whose values are functions. Let's add a . g r e e t ( ) method to
jqfundamentals.com/chapter/javascript-basics 7/17
8/8/13
our p e r s o n object:
The . g r e e t ( ) method in the example above received a string, n a m e, as its argument. When we called the method, though, we simply passed in the value of the f i r s t N a m e property of the p e r s o n object. If we wanted a super-flexible . g r e e t ( ) method that could greet anyone, this might be what we want. But it probably makes more sense that the . g r e e t ( ) method will greet the particular person.
The meaning of
t h i s
Inside of a method indeed, inside of any function there is a special keyword available to us: t h i s. It refers to the object that is the context in which the function was called. When we call p e r s o n . g r e e t ( ), the context object is p e r s o n itself. This means that we can use t h i s to access a property of the p e r s o n object from directly within the . g r e e t ( ) method. The meaning of t h i s can be incredibly perplexing to new JavaScript developers, and you should take comfort in knowing that jQuery largely makes it so that you don't need to understand it for a while. However, no discussion of objects and methods is complete without h i s at least a little. In short, if this section is confusing, feel free to skip to talking about t Objects in jQuery, and come back to it when you're ready. Let's look at how we could use t h i s in our method.
jqfundamentals.com/chapter/javascript-basics
8/17
8/8/13
Not so confusing so far, right? The confusion arises because the meaning of t h i s can change as mentioned above, it depends on the context in which the function was called! Consider the following code:
1 2 3 4 5 6 7 8 9 1 0 1 1
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' , g r e e t:f u n c t i o n ( ){ l o g (' H i ,'+t h i s . f i r s t N a m e) ; } } ; v a rs a y I t=p e r s o n . g r e e t ;/ /s t o r et h em e t h o di nav a r i a b l e s a y I t ( ) ;/ /l o g s' H i ,u n d e f i n e d '-u h o h
When we store the . g r e e t ( ) method in a variable s a y I t and then call s a y I t ( ), the context object changes to the global w i n d o w object, not the p e r s o n object. Since the w i n d o w object doesn't have a property f i r s t N a m e, we get u n d e f i n e d when we try to access it. What's a developer to do? First, be aware that storing object methods in variables can have unintended consequences for the meaning of t h i s. Second, be aware that you can force the meaning of t h i s to be what you want it to be, using the . c a l l ( ) or . a p p l y ( ) method on the function itself.
1 2 3 4 5 6 7 8 9 1 0 1 1
Both . c a l l ( ) and the very similar . a p p l y ( ) method also let us pass arguments to the function we're invoking. Imagine if our greet method took some arguments; we could pass those arguments using . c a l l ( ) like this:
jqfundamentals.com/chapter/javascript-basics
9/17
8/8/13
1 2 3 4 5 6 7 8 9 1 0 1 1
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' , g r e e t:f u n c t i o n ( g r e e t i n g ,p u n c t u a t i o n ){ l o g (g r e e t i n g+' ,'+t h i s . f i r s t N a m e+p u n c t u a t i o n) ; } } ; v a rs a y I t=p e r s o n . g r e e t ; s a y I t . c a l l (p e r s o n ,' H e l l o ' ,' ! ! 1 ! ! 1 ') ;
We could do the same thing using . a p p l y ( ), but we'd pass the arguments within a single array instead of as separate arguments:
1 2 3 4 5 6 7 8 9 1 0 1 1
v a rp e r s o n={ f i r s t N a m e:' B o a z ' , l a s t N a m e:' S e n d e r ' , g r e e t:f u n c t i o n ( g r e e t i n g ,p u n c t u a t i o n ){ l o g (g r e e t i n g+' ,'+t h i s . f i r s t N a m e+p u n c t u a t i o n) ; } } ; v a rs a y I t=p e r s o n . g r e e t ; s a y I t . a p p l y (p e r s o n ,[' H e l l o ' ,' ! ! 1 ! ! 1 ']) ;
For more details about . c a l l ( ) and . a p p l y ( ), see the MDN documentation on . c a l l ( ) and . a p p l y ( ).
Objects in jQuery
We've barely scratched the surface of objects, but you now know the basics you'll need to know to work with objects as you learn jQuery. In basic jQuery, you'll mainly use objects to provide configuration options. For example, you can provide an object to change several CSS properties on an element at once:
8/8/13
As far as t h i s, jQuery tends to take control over its meaning. In the case of event handlers, t h i s will refer to the element to which you bound the handler; in the case of iterating over a set of elements in a selection, t h i s will refer to the current element in the iteration. You shouldn't need to worry about understanding t h i s too much during your initial learning it's just a good thing to keep in mind as your learning continues.
Further reading
The MDN JavaScript Guide goes into detail about topics such as object prototypes, constructor functions, and deleting object properties.
Arrays
Arrays are a type of object used to store lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays. The preferred way to create an array is to use the array literal notation:
You will sometimes see code that creates an array using the n e wA r r a y ( ' a ' ,' b ' ,' c ' ) construct. This is generally frowned upon among JavaScript developers; it provides no advantages over the literal construct, and has some disadvantages, such as the fact that n e w A r r a y ( 3 ) will create an array with three undefined elements, rather than the array [ 3 ]. You can access properties of arrays (sometimes called elements ) with the same bracket notation we used for objects. Each element is automatically given a name based on its position in the array. Be careful, though: the numbers start at zero! Lets look at an example array with three elements:
CAUTION ANTIPATTERN
When retrieving array elements, it's usually much more convenient to use numbers to specify the index of the element you're after:
8/8/13
We can determine how many items are in an array by accessing an array's l e n g t h property:
Since we know how to get the length of an array, and we know that an array's first item is at index 0, we can iterate over the items in an array using a f o r loop:
1 2 3 4 5 6 7 8 9 1 0
v a rm y A r r a y=[' a ' ,' b ' ,' c '] ; v a ri ; v a rl e n=m y A r r a y . l e n g t h ; / /w e ' l lu s et h ev a r i a b l eia so u ri n d e x ;i ts t a r t sa t0 , / /a n dw ei n c r e m e n ti tb y1( u s i n gi + + )u n t i lii sn ol o n g e r / /l e s st h a nt h el e n g t ho ft h ea r r a y f o r( i=0 ;i<l e n ;i=i+1 ){ l o g (' i t e ma ti n d e x'+i+'i s'+m y A r r a y [i]) ; }
There is a whole lot more that you can do with arrays; for a complete reference, see the Mozilla Developer Network's Array documentation.
1i f(1){
jqfundamentals.com/chapter/javascript-basics 12/17
8/8/13
2 / /t h i sc o d ew i l lr u n ! 3 l o g (' 1i st r u t h y ') ; 4}
As it turns out, most values in JavaScript are truthy in fact, there are only five values in JavaScript that are falsy:
u n d e f i n e d (the default value of declared variables that are not assigned a value) n u l l N a N ("not a number") 0 (the number zero) ' ' (an empty string)
When we want to test whether a value is "falsy," we can use the ! operator:
The value N a N is a special case. Values that are N a N will evaluate to false in a simple conditional expression:
1 2 3 4 5 6 7 8 9
jqfundamentals.com/chapter/javascript-basics
8/8/13
It's important to remember that all other values aside from the five values listed above are truthy. This includes empty arrays, empty objects, all non-empty strings (including the string ' 0 '), and all numbers other than 0. It is possible to write single-line i f and e l s e statements without using curly braces. This practice is discouraged, as it can make code difficult to read and maintain. It is mentioned here simply because you may encounter it in others' code.
Logical Operators
Logical operators allow you to evaluate operands using AND ( & &) and OR ( | |) operations.
1 2 3 4 5 6 7 8 9
In the case of the | | operator, the value returned is the first value that proves the statement truthy, or the last value. In the case of the & & operator, the value returned is the first value that proves the statement falsy, or the last value. You'll sometimes see logical operators used as a clever way to control code execution:
This style is elegant and pleasantly terse, but it can be difficult to read, especially for beginners. You should be aware of what it means if you come across it in code, but you may want to refrain from using this style at first, and use traditional i f and e l s e statements for clarity.
8/8/13
CAUTION ANTIPATTERN
1 2 3 4 5 6 7
However, the ternary operator provides a much more succinct way of conditionally setting the value of a variable:
The statement before the ? is evaluated for its truthiness. If it is truthy, the first value ( ' c l i e n t W i d t h ') is used as the value of the p r o p e r t y N a m e variable; otherwise, the second value ( ' c l i e n t H e i g h t ') is used.
JavaScript gotchas
In addition to variable scope and truthiness, there are many other gotchas in JavaScript. Let's take a look at a few of them.
Naming things
Valid names in JavaScript begin with a letter or certain symbols, followed by zero or more letters, digits, underscores, or symbols. Names may not begin with numbers, and may not include hyphens. Besides these rules, you can name your variables however you'd like! All of these names are valid:
a a 1 f o o _ b a r f o o B a r B a z $ f o o B a r _ f o o _ _ f o o _ _
There are some conventions that people use when naming things in JavaScript, but these are optional, and don't have any effect on how the code works:
jqfundamentals.com/chapter/javascript-basics 15/17
8/8/13
Names that begin with _ are usually "private" (more on this later). Names that begin with uppercase letters are usually "constructors," used to create new instances of objects (more on this later as well). In code that uses jQuery, names that begin with $ usually refer to jQuery objects.
Reserved words
JavaScript reserves certain words for its own use; you should avoid using these words for the names of things.
a b s t r a c tb o o l e a nb r e a kb y t ec a s ec a t c hc h a rc l a s sc o n s tc o n t i n u ed e b u g g e r d e f a u l td e l e t ed od o u b l ee l s ee n u me x p o r te x t e n d sf a l s ef i n a lf i n a l l yf l o a t f o rf u n c t i o ng o t oi fi m p l e m e n t si m p o r ti ni n s t a n c e o fi n ti n t e r f a c el o n g n a t i v en e wn u l lp a c k a g ep r i v a t ep r o t e c t e dp u b l i cr e t u r ns h o r ts t a t i cs u p e r s w i t c hs y n c h r o n i z e dt h i st h r o wt h r o w st r a n s i e n tt r u et r yt y p e o fv a r v o l a t i l ev o i dw h i l ew i t h
If you must use one of these names as the name of an object property, you should quote the property name:
1l o g (0 . 0 0 0 1+0 . 0 0 0 2) ;/ /0 . 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3
This won't come up often when working with jQuery, but it's an important issue to be aware of, especially if you're working with decimal numbers like currency. If you're doing mathematical operations that require precision, you should convert values to integers before working with them, and convert them back when you're done. JavaScript is a loosely-typed language. If you try to do mathematical operations using values that are not numbers, JavaScript will not throw errors, and the result may not be what you'd expect.
jqfundamentals.com/chapter/javascript-basics
16/17
8/8/13
1 2 3 4 5 6 7
l o g (' a '+2) ; l o g (' 4 '+3) ; l o g (' f i v e '-' 4 ') ; l o g (-' 1 ') ; l o g (1+t r u e) ; l o g (1= =t r u e) ; l o g (1= = =t r u e) ;
Further reading
We've only scratched the surface of JavaScript. The Mozilla Developer Network is an excellent resource for information about the JavaScript language, particularly their JavaScript Guide. Specifically, you'll do well to read the following articles: JavaScript Overview Values, variables, and literals Functions Immediately Invoked Function Expressions Arrays Previous: Home Next: jQuery Basics
jqfundamentals.com/chapter/javascript-basics
17/17