Design Portfolio


JavaScript: Understanding the Weird Parts (Part 9)


  • whitespace - invisible characters that create literal space in your written code, carriage returns, tabs, spaces
    • Whitespace can be used liberally to clarify code in the form of comments.

Immediately Invoked Function Expressions (IIFEs)

var greeting = function(name) {
    console.log('Hello ' + name);
  • Using parenthesis invokes the function immediately after creating it (IIFE).
  • When the function is invoked, it returns a value that gets set to greeting.
console.log(greeting); // -> Hello undefined
  • Pass a parameter in the parenthesis of the function call to produce a result instead of undefined.
  • Turn a function statement into a function expression by enclosing it in parenthesis.
(function(name) {
    var greeting = 'Hello';
    console.log(greeting + ' ' + name);
}()); // IIFE
  • This is a popular style present in many frameworks today.

IIFEs and Safe Code

  • Variables created inside the IIFE do not touch the global execution context.
  • In source code, all the code is typically wrapped in an IIFE in order to ensure the code does not collide with other reusable pieces of code.

Understanding Closures

function greet(whatToSay) {
    return function (name) {
        console.log(whatToSay + ' ' + name);
greet('Hi')('Ella'); //->Hi Ella
var sayHi = greet('Hi');
sayHi('Ella'); //-> Hi Ella
  • After the greet function finishes executing it gets popped off (goes away) but the whatToSay = 'Hi' is still in memory, so the sayHi() function can go down the scope chain to find whatToSay = 'Hi'.
  • Closures are a feature of JavaScript that make sure a function has access to all the variables it needs.