Intermediate JavaScript - Basic Functions

Question Click to View Answer

What does the following code print to the console?

function blabbermouth() { };
console.log(blabbermouth.name);
"blabbermouth"

Functions have a name property that returns the name of a function. JavaScript functions are objects and can have properties like any other object.

What does the following code print to the console?

var cat = function(x) {
  return x * 2;
}
console.log(cat.name);
""

The name property for anonymous functions returns an empty string.

What does the following code print to the console?

blah = function () {
  return lala;
  lala = "hi";
};
console.log(blah());

This raises a ReferenceError because the lala variable cannot be returned before it's defined.

What does the following code print to the console?

function foo () {
  return bar();
  function bar() {
    return "Poppin' bottles";
  }
}
console.log(foo());
"Poppin' bottles"

The bar() method is hoisted to the top of the foo() method, so it can be called before it's defined.

What does the following function print to the console?

function sum(a, b) {
  return a + b;
}
console.log(sum(1, 2, 3, 4));
3

When too many arguments are supplied to a function they are simply ignored. The sum() function only takes 2 arguments so the extra arguments (3 and 4) are ignored in this example.

What does the following function print to the console?

function a(x, y, z) {
  return z;
}
console.log(a("blah"));
undefined

When too few arguments are supplied to a function, JavaScript assigns the missing arguments to undefined.

What does the following code print to the console?

love_story = function(x, y) {
  console.log(arguments);
};
love_story("princess", "frog");
["princess", "frog"]

Arguments is an array-like object that corresponds with the parameters that are passed into a function.

What does the following code print to the console?

function sum() {
  result = 0;
  arguments.forEach(function (num) {
    result += num;
  });
  return result;
}
sum(1, 2, 3);

This code raises an error because arguments is an array-like object, but it's not actually an array, so we can't use the forEach() method. According to Douglas Crockford, having arguments as an array-like object and not an actual array is a design flaw in the language.

What does the following code print to the console?

function c(f) {
  return f();
}
function blub() {
  return "monsters";
}
c(blub);
"monsters"

The c() function takes a callback function as a parameter. blub is passed to c() as an argument and is invoked within the body of c().

Functions are "first class" in JavaScript because they can be passed as parameters and stored in data structures.

Sort the values in the following array in ascending report: [32, 1, 44, 9]

[32, 1, 44, 9].sort(function (x, y) {
  return x - y;
})

The sort() method takes an anonymous callback function as a parameter.