Functions in JavaScript

Objectives

  • Describe (in English) a function.
  • Define (in JavaScript) a function.
  • Use function specific jargon
    • call or invoke a function
    • return a value from a function
    • pass parameters to a function
    • use the arguments keyword
  • Differentiate between named and anonymous functions
  • Define the scope of a function
    • Describe the difference between var and let

Functions

  • Fundamentally, functions are a way to reuse code.
     
  • Programmers use a series of functions to compose more complex programs.
     
  • Functions can accept input which are called arguments or parameters. Parameters are said to be passed to a function.
     
  • Functions can produce output, a function is said to return  this output.

 

Function Syntax

function [[name]]() {
    [[instructions (i.e., statements, expressions, values)]]
}

// A function definition
function greet() {
    console.log("Hello, World!"); 
}

// A function call, we use the functions name to call it
greet();

Functions have a header and a body

the keyword function, and the name are the header. Everything inside the curly braces is the body.

Return

function greet() {
    console.log("Hello, World!");
}

var greeting = greet(); // This line prints "Hello, World!"
console.log(greeting)   // What does this print?


// This function has a "return" statement, meaning it produces an output value
function greetWithReturn() {
    console.log("Hello, World!");
    return "You told me to return.";
}

var secondGreeting = greetWithReturn(); // This line still prints "Hello, World!"
console.log(secondGreeting);            // What will this print? 

Using the return keyword, we can have a function produce a value.

Return (More)

function greet() {
    return "You'll never reach the console.log() message.";
    console.log("Hello, World!");
}

// "You'll never reach the console.log() message."
greet();


function twoReturns() {
  return "I'm the only return that gets executed";
    return "You told me to return.";
    console.log("Hello, World!");
}

// "I'm the only return that gets executed";
twoReturns()

the return statement forces execution to go back to the caller

Parameters

// Syntax
function greet([[parameterOne]]) {
    return "Hello, " [[parameterOne]];
}

// Example
function greet(name) {
    console.log("Hello, " + name);
}

// Calling a function with a parameter
greet();             // Hello, undefined
greet("Tyler");        // Hello, Tyler
greet("Tyler", "Liz"); // What do you think?

// Destiny's Child rules
function sayMyName(myName, noOneIsAroundYou) {
    if(noOneIsAroundYou) {
        console.log("Baby, I love you.");
    }
    else {
        console.log(myName);
    }
}

sayMyName("Beyonce", false); // Beyonce
sayMyName("Beyonce", true);  // Baby, I love you.

The caller can pass zero or more paremters to a function

Parameters

// No named parameters.
function sumAllNumbers() {
    var sum = 0;
    for(var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }

    return sum
}

// This totally works.
sumAllNumbers(1,2,3,4,5,6,7,8,9,10); // 55

Functions can handle an unspecified number of parameters using the arguments keyword

Parameters

// No named parameters.
function sumAllNumbers() {
    var sum = 0;
    for(var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }

    return sum
}

// This totally works.
sumAllNumbers(1,2,3,4,5,6,7,8,9,10); // 55

arguments is always an array, and always available inside a function.

Quick Recap

  • Describe (in English) a function.
  • Define (in JavaScript) a function.
  • Use function specific jargon
    • call or invoke a function
    • return a value from a function
    • pass parameters to a function
    • use the arguments keyword
  • Differentiate between named and anonymous functions
  • Define the scope of a function
    • Describe the difference between var and let

Next Up

  • Describe (in English) a function.
  • Define (in JavaScript) a function.
  • Use function specific jargon
    • call or invoke a function
    • return a value from a function
    • pass parameters to a function
  • Differentiate between named and anonymous functions
  • Define the scope of a function
    • Describe the difference between var and let

Anonymous Functions

function namedFunction() {
    return "I have a name";
}

var anonymousFunction = function() {
    return "I am legion"
}

namedFunction();
anonymousFunction();

The text in between the keyword function and the parenthesis is the name of the function. Functions do not need names.

Anonymous Functions

function namedFunction() {
    return "I have a name";
}

var anonymousFunction = function() {
    return "I am legion"
}

namedFunction();
anonymousFunction();

Notice that I'm putting the anonymous function into a variable. If I didn't do this, I wouldn't be able to call that function later!

Anonymous Functions

function namedFunction() {
    return "I have a name";
}

var namedFuncInVar = namedFunction; // Is this crazy?

var anonymousFunction = function() {
    return "I am legion"
}

namedFunction();
namedFuncInVar();
anonymousFunction();

I can put a named function into a variable as well

Anonymous Functions

function namedFunction() {
    return "I have a name";
}

var namedFuncInVar = namedFunction; // Is this crazy?

var anonymousFunction = function() {
    return "I am legion"
}

namedFunction();
namedFuncInVar();
anonymousFunction();

Functions are just data. Like strings, numbers and objects, they can be stored into variables.

You will use this concept a lot in web development.

Function Scope

Functions always have a scope which is demarcated by it's curly braces.

function scopeExample(param) {
    var thing = "this is a value";
    console.log(param, thing);
}

scopeExample("this is a param");
console.log(param);
console.log(thing);

Variables are only available within their scope.

Function Scope

New to JavaScript 2015 is the concept of block scope.

 

Block scope has existed in other languages for a long time, but is only now implemented in JS.

 

To use block scope we have to use strict mode and the new JS2015 keyword let

Function Scope

"use strict"
function test() {
    if(true){
        let blockScope = 7;
        var functionScope = "word word";
    }
    console.log(functionScope); // prints hello world
    console.log(blockScope);    // thows an error
}

Block scope is the nearest enclosing curly brace block.

 

function scope is the nearest functions enclosing curly brace block.

Advanced: Hoisting

declaration() // works
function declaration() {
    // code
}
declaration() // works

expression() //doesn't work
var expression = function() {
    // code
};
expresion() //works

function scope works because of a JS concept called hoisting.

 

function definitions and variable declarations are hoisted.

 

// Function declaration hoisted first
function declaration() {
    // code
}

// variable declaration hoisted second
var expression;

// All other expressions appear
// in the order they were
declaration() // works
expression() //doesn't work
expression = function() {
    // code
};
expression() //works

Advanced: Hoisting

declaration() // works
function declaration() {
    // code
}
declaration() // works

expression() //doesn't work
var expression = function() {
    // code
};
expresion() //works

This is usually confusing to people learning JavaScript -- this is NOT something that is common in other programming languages.


We will revisit this topic next week in more detail.


// Function declaration hoisted first
function declaration() {
    // code
}

// variable declaration hoisted second
var expression;

// All other expressions appear
// in the order they were
declaration() // works
expression() //doesn't work
expression = function() {
    // code
};
expression() //works

Advanced: Hoisting

Questions?

Here is a little cheat sheet which has some advanced topics in it as well:

https://gist.github.com/teb311/88e7a4c0a1403a7fb296bb7eaf0b9804

Functions in Javascript

By Tyler Bettilyon

Functions in Javascript

  • 1,538