Functions



Course Link

1. Write Reusable JavaScript with Functions

function reusableFunction() {
  console.log("Hi World")
};
reusableFunction();

2. Scope

In JavaScript, scope refers to the visibility of variables.

  • Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.
  • It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.
var someVar = "Hat";
function myFun() {
    var someVar = "Head";
    return someVar;
} 

myFun() //return "Head"
  • Does var make a difference?

    • var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it’s in global scope - a global variable is declared.

    • x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn’t find x, only then does it creates x property on a global object (which is a top level object in a scope chain). Now, notice that it doesn’t declare a global variable, it creates a global property.

  • Why var matters?

    • If you’re in the global scope then there’s not much difference. Read Kangax’s answer for explanation

    • If you’re in a function then var will create a local variable, “no var” will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

// These are both globals
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}

3. Understanding Undefined Value returned from a Function

A function can include the return statement but it does not have to. In the case that the function doesn’t have a return statement, when you call it, the function processes the inner code but the returned value is undefined

var sum = 0;
function addSum(num) {
  sum = sum + num;
}
addSum(3); // sum will be modified but returned value is undefined
  • queue
function nextInLine(arr, item) {
 
  arr.push(item);

  var last_element = arr.shift();
  return last_element;
}

// Setup
var testArr = [1,2,3,4,5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));

4. Use Conditional Logic with If Statements

function trueOrFalse(wasThatTrue) {
  if (wasThatTrue) {
    return "Yes, that was true"
  }
  return "No, that was false"
}

5. Use Else If Statements

The function is executed from top to bottom so you will want to be careful of what statement comes first

// foo function
function foo(x) {
  if (x < 1) {
    return "Less than one";
  } else if (x < 2) {
    return "Less than two";
  } else {
    return "Greater than or equal to two";
  }
}

// 2 bar function
function bar(x) {
  if (x < 2) {
    return "Less than two";
  } else if (x < 1) {
    return "Less than one";
  } else {
    return "Greater than or equal to two";
  }
}

foo(0) // "Less than one"
bar(0) // "Less than two"

6. Comparison with Operators

  • Comparison with the Equality Operator
1   ==  1   // true
1   ==  2   // false
1   == '1'  // true
"3" ==  3   // true
  • Comparison with the Strict Equality Operator
3 ===  3   // true
3 === '3'  // false

typeof 3   // returns 'number'
typeof '3' // returns 'string'

Strict equality === is the counterpart to the equality operator ==. However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.

  • Comparison with the Inequality Operator
1 !=  2     // true
1 != "1"    // false
1 != '1'    // false
1 != true   // false
0 != false  // false
  • The inequality operator (!=) is the opposite of the equality operator.
  • It means “Not Equal” and returns false where equality would return true and vice versa.
  • Like the equality operator, the inequality operator will convert data types of values while comparing.
  • Comparison with the Strict Inequality Operator
3 !==  3   // false
3 !== '3'  // true
4 !==  3   // true

The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns false where strict equality would return true and vice versa. Strict inequality will not convert data types.

  • Comparison with the Greater Than Operator
5   >  3   // true
7   > '3'  // true
2   >  3   // false
'1' >  9   // false
  • Comparison with the Greater Than Or Equal To Operator
6   >=  6   // true
7   >= '3'  // true
2   >=  3   // false
'7' >=  9   // false
  • Comparisons with the Logical And Operator &&
if (num > 5 && num <8) {
    return "weekend";
}
return "work";
  • Comparisons with the Logical Or Operator ||
function testLogicalOr(val) {
  if (val > 20 || val <10) {
    return "Outside";
  }
  return "Inside";
}

testLogicalOr(15);

7. Selecting from Many Options with Switch Statements

  • If you have many options to choose from, use a switch statement.
  • A switch statement tests a value and can have many case statements which define various possible values.
  • Statements are executed from the first matched case value until a break is encountered.
  • Case values are tested with strict equality (===). The break tells JavaScript to stop executing statements.
  • If the break is omitted, the next statement will be executed.
switch(lowercaseLetter) {
  case "a":
    console.log("A");
    break;
  case "b":
    console.log("B");
    break;
}
  • Adding a Default Option in Switch Statements
  • In a switch statement you may not be able to specify all possible values as case statements.
  • Instead, you can add the default statement which will be executed if no matching case statements are found.
  • Think of it like the final else statement in an if/else chain.
switch (num) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
...
  default:
    defaultStatement;
    break;
}
  • Multiple Identical Options in Switch Statements
 function sequentialSizes(val) {
  var answer = "";
 
  switch(val) {
    case 1:
    case 2:
    case 3:
      answer = "Low";
      break;
    case 4:
    case 5:
    case 6:
      answer = "Mid";
      break;
    case 7:
    case 8:
    case 9:
      answer = "High";
      break;
  }

  • Replacing If Else Chains with Switch

If you have many options to choose from, a switch statement can be easier to write than many chained if/else if statements.

   function chainToSwitch(val) {
  var answer = "";
 
  switch (val) {
    case "bob":
      answer = "Marley";
      break;
    case 42:
      answer = "The Answer";
      break;
    case 1:
      answer = "There is no #1";
      break;
    case 99:
      answer = "Missed me by this much!";
      break;
    case 7:
      answer = "Ate Nine";
      break;
    
  }
  return answer
}
chainToSwitch(7);

8. Returning Boolean Values from Functions

function isLess(a, b) {
  return a  < b
}

isLess(10, 15);

9. Return Early Pattern for Functions

When a return statement is reached, the execution of the current function stops and control returns to the calling location.

function myFun() {
  console.log("Hello");
  return "World";
  console.log("byebye")
}
myFun();

\\ The above outputs "Hello" to the console, returns "World", but "byebye" is never output, because the function exits at the return statement

10. BlackJack Exercise

var count = 0;

function cc(card) {
  switch(card) {
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      count+=1;
      break;
    case 10:
    case "J":
    case "Q":
    case "K":
    case "A":
      count--;
      break;
  } 
  if (count > 0) {
      return count + " Bet";
    } else {
      return count + " Hold";
    }
}

cc(2); cc(3); cc(7); cc('K'); cc('A');

11. Go Golf Exercise

var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
 
  if (strokes == 1) {
    return "Hole-in-one!";
  } else if (strokes <= par -2) {
    return "Eagle";
  } else if (strokes == par -1){
    return "Birdie";
  } else if (strokes == par) {
    return "Par";
  } else if (strokes == par +1){
    return "Bogey";
  } else if (strokes == par +2){
    return "Double Bogey"
  } else {
    return "Go Home!"
  }
}

golfScore(5, 4);