Functions

 

 

Lonce Wyse

Communication & New Media

lonce.wyse@cnm.nus.sg

 Functions

input

("arguments")

process

 

return

 

 Defining Functions

input

("arguments")

process

 

return

 

function ( arg ) {
        // any number of statements
	return arg/2;
}

 

(note pattern!)

var halve = function ( arg ) {
	return arg/2;
}
x = halve(256);

Define & Name

Use

(note pattern!)

 Naming Functions

 Using named functions

var cook = function(stuff, temperature, minutes){
        var timer = 0;
        while (timer < minutes) {
            stuff = stuff + heat;
            timer = timer+1;
        }
	return stuff;
}
var cake = cook(batter, 200, 30);

 Define

 Use

var timer=0;
var foo = function(arg){
      {
        var done = false;
        console.log('done is ' + done);
      }
    console.log('done is ' + done);
    console.log('timer is ' + timer);
  }
console.log('done is ' + done);

 SCOPE

Variables declared with var have "function scope"

Even buried in a block, vars can be seen throughout the whole function. 

var timer=0;
var foo = function(arg){
      {
        let done = false;
        console.log('done is ' + done);
      }
    console.log('done is ' + done);
    console.log('timer is ' + timer);
  }
console.log('done is ' + done);

 SCOPE

Variables declared with let and const have "block scope"

Buried in a block, lets and consts can ONLY be seen within the block they are defined in.

002.003 Functions

By lonce

002.003 Functions

Introduction to Functions in JavaScript

  • 486