Chapter 2. Essentials Flashcards
Why should you write maintainable code?
You should work to lessen the reading and comprehension time of your code.
Work to enhance code portability.
What are some qualities of maintainable code?
- Readable
- Consistent
- Predictable
- Appears to be written by same person
- Is Documented
What’s the difference between a local and a global variable?
A global is declared outside of any funciton, or simply used without being declared.
A local variable is one declared inside a function.
Why should global variables be avoided?
- Potenital for collisions: globals share the same namespace.
- It’s too easy to use a variable without declaring it, therefore creating an implied global.
- Portability: your code could be used in another environment and overwrite some host object.
What happens to a and b if this chained assignment is inside of a function?
var a = b = 0;
Javascript is evaluated right to left.
var a = (b = 0);
“b” becomes an implied global since it’s not declared; it’s value is set to zero.
“a” is a local variable and it’s value is set to zero.
var global_day = new Date(2013, 04, 21); delete global_day;
What will the last line return?
False.
Globals created with the var keyword cannot be deleted. Implied globals are just properties of the global object, and can be deleted.
In the browser environment, which identifier do you use to access the global object?
window
Why should you declare all your variables at once at the top of a function?
- Less physical code
- Requires planning, minimizes globals
- Provides single place to check initial var assignments.
- Avoids logical errors due to hoisting.
What happens when you use a local variable inside a function before you declare it?
All declarations are “hoisted” to the top of the function, where they are assigned “undefined” until they are declared.
How can you optimize the common for loop?
for (var i = 0; i < my_array.length; i++ { //do something )
- Each time you access a collection, like an array of elements, you have to live query the DOM. You should cache the length.
- i ++ should be converted to ** i += 1** for legibility.
- Move var out to own line for declarations.
Name the three getElementsBy… DOM methods that return HTML Collections.
document.getElementsByName()
document.getElementsByClassName()
document.getElementsByTagName()
Name four HTML Collections found on the document object.
document.images
document.links
document.forms
document.forms[index].elements
What is the optimized for loop?
var i, myarray = []; for (i = myarray.length; i -= 1;) { //do stuff }
What is the optimized while loop?
var myarray = [], i = myarray.length; while (i -= 1) { //do stuff }
What general term is also known as using a for-in loop?
Enumeration occurs when you iterate over each part of an object.