2-3 Functions

This lab explains the basics of the JavaScript functions.

Functions

There are two ways to define functions: the function keyword and arrow functions. This lab covers the first. We use a function to group some statements that can be reused.

// draw a right angle triangle of height n
function draw (n) {
  let out = ""
  for (let y=0; y<n; y++) {
    let s = ""
    for (let i=0; i<n-y-1; i++) s += ". "
    for (let i=0; i<=y; i++) s += "* "
    out += s+"\n"
  }
  console.log(out)
}

draw(5) // call the function to draw a triangle of height 5
draw(10) // draw again

Functions can return values to the calling code with return. The return statement also ends the execution of the functions immediately.

// this function compares the two parameters a and b, and returns the bigger one
function bigger (a,b) {
  if (a>b) {
    return a
  } else {
    return b
  }
}
console.log('The bigger one is ', bigger(2,3))

// another way to write
function bigger2 (a,b) {
  if (a>b) { return a }
  return b
}

// yet another way to write
function bigger3 (a,b) { return a>b ? a : b }

The next example defines a function that finds the largest number in an array, assuming that the array has at least 1 element.

function max (num) {
  let x = num[0] // assume the 0th element is the largest
  // compare x with each remaining element
  for (let k=1; k<num.length; k++) {
    if (num[k]>x) x = num[k]
  }
  return x
}

max([2,3,5,8,7,1,4,6]) // return 8

Variable scope

In JavaScript, variables defined inside a function are called local variables. They are visible from the point of declaration up to the end of the function. When you call a function, all its local variables are created; when the function returns (stops execution), the local variables are destroyed.

function foo (param1, param2) {
  // 'a' cannot be used yet, but 'param1' can be used here
  // ...
  let a = 4;
  // ...
  // 'a' can be used till the end of the function
  console.log(a);
}

Technical note: Sometimes, a local variable may still exist after the function that defines it returns. This is the case if the variable falls into the closure of an inner function which is returned by the outer function. See online reference for more information.

Variables defined using let or const may further be restricted to a block scope. A block is a region of the function then is delimited by { }. This works similarly to Java’s scoping rules.

function bar () {
  for (let i=0; i<10; i++) { 
    /* 'i' can be used only within this block */ 
  }
  while (Math.random()<0.5) {
    let k;
    /* the scope of 'k' is this 'while' loop */
  }
}

On the other hand, variables defined outside any functions are global variables, and are visible in any functions. It is generally recommended to use global variables as little as possible.

Exercise

  1. Write a function sum(num) to calculate the sum of elements in an array num. Use the following code to test your function.

    let x = [1,2,3,4,5];
    let ans = sum(x);
    console.log('Correct? ', ans==15);
    
  2. Write a function odd(n) to generate an array of odd numbers less than or equal to n. Test your function with the following code.

    let a = odd(1);
    console.log(a); // should print [1]
    console.log(odd(9)); // should print [1,3,5,7,9]
    console.log(sum(odd(10*2-1))); // should print 100
    
  3. Write a function search(num, n) to search for an number n in the array num. Return the position of the element if it is found. If it is not found, return -1. Test your function with the following code.

    let x = [6, 8, 3, -2];
    console.log(search(x, 3)); // should print 2;
    console.log(search(x, 1)); // should print -1;
    

The sample answers are available at ex2-3q1.js, ex2-3q2.js and ex2-3q3.js respectively.