Learn JavaScript - Functions, Variable Scope

Question Click to View Answer

What does the following code evaluate to?

var first_name = function (name) {
  return name;
}
first_name("bob");
"bob"

The variable first_name is assigned to a function that does not have a name, also known as an anonymous function. The function takes a name as an argument and returns the same value. The line first_name("bob"); invokes the function, which means it causes the code block associated with the function to be executed.

What does the following code evaluate to?

function add(x, y) {
  return x + y;
}
add(2, 3);
5

add() is a named function (i.e. add() is not an anonymous function). add() takes two arguments and returns the sum of the two arguments.

Create an anonymous function and assign it to the variable full_name. The function should take two arguments, first_name and last_name, and return the two strings concatenated.

var full_name = function (first_name, last_name) {
  return(first_name + " " + last_name);
}

// Example of how to invoke the full_name() function
console.log(full_name("crazy", "cat"));

What does the following code print to the console?

function square (x) {
  return(x * x);
}
console.log(square(5));
25

What does the following code print to the console?

function square (x) { return(x * x) };
function cube (x) {
  return(x * square(x));
}
console.log(cube(2));
8

The square() function is called within the cube() function.

Invoke the my_fun() function.

function my_fun() { return "I am having fun" };
my_fun();

my_fun() does not take any arguments, so it can be invoked with the parenthesis and no contents. If my_fun; is written without the parenthesis, the function object is returned and the executable code associated with the function is not executed.

What does the following code print to the console?

var what = function () { return "HI!!!!" };
console.log(typeof(what));
function

functions are a special type of object that are associated with executable code. The typeof function returns the string "function", even though functions are a special type of object, because it is useful to differentiate between functions and "regular" objects. The next quiz will examine objects in detail.

What does the following code print to the console?

var max_value = function(array) {
  var result = array[0];
  for (var i = 0; i < array.length; i++) {
    if (array[i] > result) {
      result = array[i];
    };
  }
  return result;
}
console.log(max_value([1, 50, 2]));
50

What does the following code print to the console?

var arr = ["boy", 42, 23, function () { return "gotta catch 'em all, Pokemon!" }, 56];

console.log(arr[3]());
"gotta catch 'em all, Pokemon!"

Functions are values and can be treated like any other value in JavaScript. Functions can be assigned to variables, stored in arrays, etc. arr[3] fetches the function object from the array and arr3 invokes the function. When a function is invoked, the code block associated with the function is executed.

What is the code to invoke the following function?

function kesha() {
  return "Your love is my drug";
}
kesha();

JavaScript functions are invoked by appending () to the function name. Invoking a function means running the executable code associated with the function.

What does the following code print to the console?

var lambchop = function () {
  "This is the song that never ends";
}
console.log(lambchop());
undefined

This is a bit of a trick question. The lambchop() function does not have a return statement, so nothing is returned. When a function do not specify any return value, undefined is returned by default.

What does the following code print to the console?

function doctor_name (last_name) {
  return "Dr. " + last_name
}
console.log(doctor_name());
"Dr. undefined"

The doctor_name function takes an argument, but no argument was supplied when the function was invoked. When arguments are not supplied, the default value is undefined. When the "Dr. " string is concatenated with undefined, JavaScript converts undefined to a string (i.e. converts from undefined to "undefined") and then performs the concatenation.

Many programmers consider JavaScript's aggressive type conversion (i.e. converting undefined to a string rather than raising an error) an undesirable feature of the language.

What does the following code print to the console?

function dwelling(name) {
  if (typeof(name) != "string") {
    throw "ArgumentError"
  };
  return name + " cave";
}
console.log(dwelling(42));
"ArgumentError"

The dwelling() function takes an argument that must be a string. If the argument to the dwelling function is not a string, an "ArgumentError" is thrown. Type checking is common in JavaScript as the default language behavior is to perform aggressive type conversion, which can yield unexpected and undesirable results.

What does the following code print to the console?

function add(x, y) {
  return(x + y);
}
console.log(add(1, 2, 3, 4, 10, 20));
3

The add() function takes two arguments, but was supplied with 6 arguments when it was invoked. When functions are called with extra arguments, an error is not thrown and JavaScript simply ignores the extra arguments.

What does the following function return?

function args () {
  return arguments;
}
console.log(args(8, 7, 6, 5, 4));
[8, 7, 6, 5, 4]

arguments is a special keyword that represents all the arguments that are passed to a function. arguments is an object that is very similar to an array, but not the same as an array (this distinction is not important now, but useful for advanced JS programming).

What does the following code print to the console?

function lamp() {
  var my_special_variable = "I am special";
}
lamp();
console.log(my_special_variable);
ReferenceError: my_special_variable is not defined

This example throws an exception because my_special_variable is only accessible within the lamp() function. In other words, my_special_variable can be used anywhere inside the lamp() function, but cannot be used outside the lamp() function.

What does the following code print to the console?

function book() {
  good_book = "Slaughterhouse Five";
}
book();
console.log(good_book);
"Slaughterhouse Five"

The var keyword is not used when the good_book variable is defined, so the good_book variable has global scope (it can be used anywhere in the program). Global variables are evil so make sure to always use the var keyword when defining variables.

num = 23;
function evil () {
  num += 5;
}
evil();
console.log(num);
28

The evil() function modifies the global variable num. Global variables are sometimes unavoidable, but should be avoided whenever possible. In this example, it is almost certain that the global variable could be avoided.

Create a function called min_value() that accepts an array of numbers as an argument and returns the smallest value from the array.

function min_value(arr) {
  var result = arr[0];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] < result) { result = arr[i]; }
  }
  return result;
}

Invoke the song() function.

function song () {
  return "Mary had a little lamb";
}
song();

Functions are invoked by appending () to the function name. When functions are invoked (or "called"), the executable portion of the function in the code block is run.

Define a function called add_numbers() that adds two numbers and throws an error if the arguments supplied to the function are not numbers.

function add_numbers(a, b) {
  if (typeof a != "number" || typeof b != "number") { throw "ArgumentError"; }
  return a + b;
}

Invoke the bad_hairday() function in the following array.

arr = [0, "nice", function bad_hairday () { return "YOLO" }];
arr[2]();

The third element in the arr Array contains the bad_hairday() function and this function is invoked by appending () to the function object.

Define an anonymous function and assign it to the your_name variable. The function should return "Snoop Dogg".

var your_name = function () { return "Snoop Dogg" }

This function is called an "anonymous function" because it does not have a name. The function is assigned to the your_name variable and can be invoked with the your_name variable: your_name();

What does the following code print to the console?

var result;
if (undefined) {
  result = function () { return "blah blah blah"; }();
} else {
  result = function () { return "meow meow meow"; }();
}
console.log(result);
"meow meow meow"

The boolean condition in the if statement is falsey, so the code block associated with the else condition is executed. The else code block is dense as it defines and invokes a function on a single line. The else code block could also have been written in two lines to make the function invocation clearer:

result = function () { return "meow meow meow"; };
result = result();