Week 4 

Let,Const, and Var

Scope

let

// Scope with conditionals

var restaurant = 'Outback Steakhouse'

if (true) {
    var restaurant = 'Chipotle'
}

console.log(restaurant) // What is this?

// Scope with loops

var restaurants = ['Outback Steakhouse', 'Texas Roadhouse', 'Olive Garden']

var temp = ''
for (var i = 0, j = restaurants.length; i < j; i++) {
    var temp = ' ' + restaurants[i]
    restaurants += temp
}

console.log(temp) // What is this?
// Scope with functions

restaurants.push('Subway')
restaurant = ''

var temp = ''
restaurants.forEach(function(r) {
    var temp = ' ' + r
    restaurant += temp
})

console.log(temp) // What is this?

Functions create scope

Block statements do not

// Scope with conditionals

var restaurant = 'Outback Steakhouse'

if (true) {
    var restaurant = 'Chipotle'
}

console.log(restaurant) // What is this?

// Scope with immediately invoked function expression (IIFE)

var restaurant = 'Outback Steakhouse'

(function() {
    if (true) {
        var restaurant = 'Chipotle'
    }
})()

console.log(restaurant) // What is this?

var is a variable that accessible anywhere within a function

 

let is a variable that is only accessible inside { }

Arrow Functions

* Shorter Syntax *

// Function in ES5

let add = function(a, b) {
  let total = a + b;
  return total;
}
// Arrow Function

let add = (a, b) => {
  let total = a + b;
  return total;
}
// Function in ES5

let add = function(a, b) {
  return a + b; // Fits on one line
}
// Arrow Function
// If the code inside the function
// can fit on one line,
// and returns a value,
// you can use an even shorter syntax
let add = (a, b) => a + b;
// Function in ES5

let addOne = function(a) {
  return a + 1;
}
// Arrow Function
// If there is only one parameter,
// you do not have to include the ( )
let addOne = a => a + 1;

Week 4 Promineo Tech

By Jamal Taylor

Week 4 Promineo Tech

  • 185