Functions and Scope

Review

  • Use conditionals to control program flow
  • Differentiate between true, false, 'truth-y', and 'false-y'
  • Use Boolean logic (!, &&, ||) to combine and manipulate conditionals

Objectives

  • Describe how parameters and arguments relate to functions
  • Create and call a function that accepts parameters to solve a problem
  • Define and call functions defined in terms of other functions
  • Return a value from a function using the return keyword
  • Define and call functions with argument-dependent return values
  • Determine the scope of local and global variables
  • Create a program that hoists variables

Introduction to Functions

A function is a reusable statement, or a group of reusable statements.


Functions enable the software developer to segment large, unwieldy applications into smaller, more manageable pieces.

DRY

Don't Repeat Yourself

Function Declaration

function declarations

function expressions

function speak (words) {
  console.log(words);
}
var speak = function (words) {
  console.log(words);
}

function declarations

function expressions

// can be run anytime
speak('hello, world!')

function speak(words) {
  console.log(words)
}

// DOES NOT RESULT IN ERROR
// MUST be declared BEFORE 
// you run the function
speak('hello, world!')

var speak = function (words) {
  console.log(words)
}

// RESULTS IN ERROR:
// TypeError: undefined
// is not a function

Function Declaration Syntax

  • A name
  • An optional list of parameters (i.e., the names of arguments to be "passed" into the function, or information the function will use); this is defined by the parenthesis before the opening curly brace
  • Statements inside the function (the code executed every time the function is called)
  • Calling, or invoking, a function executes the code defined inside this function.
  • But defining and calling a function is different. A function will not be called when it's defined.
  • You call a function by using parenthesis after the function's name ()
function hello () {
  console.log("hello there!")
}

hello();

=> hello there!

Parameters

// Bad idea...
function helloBlanch () {
  console.log('hello, Blanch');
}

function helloRose () {
  console.log('hello, Rose')
}
function sayHello (name) {
  console.log('Hello ' + name);
}

sayHello('Blanch');
=> 'Hello Blanch'

sayHello('Rose');
=> 'Hello Rose

Parameters allow us to write functions that can act on different inputs

// Parameter
function doSomething (parameter) {
  // does something
}

// Argument
doSomething(argument)

Parameters refer to variables defined in the function's declaration;

arguments refer to the actual values passed into the function when the function is called. For example:

function sum(x, y, z) {
  console.log(x + y + z)
}

sum(1, 2, 3);
=> 6

sum(7, 8, 9);
=> 24

Rolling Dice Lab

Create a page that displays a random update of two dice every time the user hits the "Roll Dice" button

Steps

  • Pseudo Code the exercise
  • Read about Accessing and modifying the DOM with JS
    • Document.getElementById
  • Start building functions!

The Return Statement

Sometimes we want to update a variable or even call another function. This requires a return statement.

 

When we return something, it ends the function's execution and "spits out" what we are returning. 

We can store the return statement in a variable:

function sum (x, y) {
  return x + y;
}

var z = sum(3, 4);
=> 7

Or pass it to another function:

function sum (x, y) {
  return x + y;
}

function double (z) {
  return z * 2;
}

var num = sum(3, 4)
=> 7
var numDbl = double(num);
=> 14

// This can also be written:
var num = double(sum(3,4));
=> 14

Return statements will completely stop a function's execution. Any statements following the return statement will not be called:

  return words;

  // The following statements 
  // will not run:
  var x = 1;
  var y = 2;
  console.log(x + y)
}

Introduction to Scope

Scope is the set of variables you have access to.

 

JavaScript reads from top to bottom. Sometimes, however, we declare variables inside functions (just like arguments), which aren't accessible in other parts of our code.

 

This is the concept of scope.

 

 

Global Scope

Access something from ANYWHERE in the program

Local Scope

Conversely, if a variable is declared inside a function, it is referred to as LOCAL, and has a local scope.

A variable with local scope cannot be referenced outside of that function.

var a = "this is the global scope";
function myFunction() {
  var b = "this variable is defined in the local scope";
}
myFunction();
console.log(b);
// Global Scope
var a = "Hello";

// This function is defined in the global scope
function sayHello(name) {
    return a + " " + name;
}

sayHello("JavaScript");
=> "Hello JavaScript";

Nested Scope

When a function is defined inside another function, it is possible to access variables defined in the parent from the child:

 

var a = 1;

function getScore () {
  var b = 2,
  c = 3;

  function add() {
  return a + b + c;
  }

  return add();
}

getScore();
=> 6

Conclusion

  • Summarize the difference between global and local scope.
  • Explain how you define and call functions using arguments
Made with Slides.com