Javascript Assesment:
Best Practices

I’m working my way through Rebecca Murphey’s javascript assessment tests, so I thought I’d write a brief summary of the test problems and resolutions as I go through them.

Best Practices Test 1: You should avoid global variables.

So the number one reason to avoid global variables is because all of the javascript code shares a single global namespace and javascript has implied global variables, which means that any variable not explicitly declared in local scope are automatically added to the global namespace. Too many global variables could result in collisions between different scripts on the same page. One way to solve this problem is to use the “module pattern”, a design pattern where you wrap your code in a function that returns an object. To access the object’s functions from outside of itself, you just use Object.function_name().

Further reading:

The test looks to see if myObject is set on the window global object, because in browsers, all global variables are properties of the windows object. The test passes after changing “myObject” to “var myObject”, which changes myObject from a global variable to a local variable.

Best Practices Test 2: You should declare functions safely.

This test uses a conditional statement to declare functions. Declaring functions conditionally varies between different browsers; some will declare the first function, while some will declare the second. Instead, you can turn the function declarations into assignment expressions.

Change this:


 function(foo) { 
   if (foo) { 
     function getValue() { return 'a'; } 
   } else { 
     function getValue() { return 'b'; } 
   } 
   return getValue();
 };

to this:


function (foo) { 
  if (foo) { 
    getValue = function() { return "a"; } 
  } else { 
    getValue = function() { return "b"; } 
  } 
  return getValue(); }: 

Further Reading:

Best Practices Test 3: You should use parseInt correctly.

The parseInt() function takes a string argument and an optional radix argument. You always want to specify the radix because not all implementations will treat it the same without it.  To pass this test, you just need to include the radix.

Change this:


function(num) { 
   return parseInt(num); 
 }; 

To this:


function(num) {
  return parseInt(num, 10); 
}; 

Further Reading:

  • parseInt()” on the Mozilla Developers Network

Best Practices Test 4: You should understand strict comparison.

A strict comparison (===) is only true if the operands are the same Type, while abstract comparison (==) converts the operands to the same Type before making the comparison. To pass this test, you just need to strictly compare val1 to val2:


function (val1, val2) {
  return val1 === val2;
}

Further Reading: