JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Getting to Know the Difference Between the let and var Keywords

October 3, 2016 by Krishna Srinivasan Leave a Comment

The Difference Between the let and var Keywords
Photo credit to Stack Overflow

Essentially, the keywords let and var serve the same purpose as each other in JavaScript, but they are used in different contexts. When used outside of a function block, the var and let keywords are actually exactly the same. It’s when they are used within a function that they differ from each other. The var keyword declares a variable for an entire function, meaning it’s available for use and visible throughout the entire function. Let is only scoped to the nearest function block, rather than the whole function. This means that when you declare a variable using let within a function, it’s only available within the block (the function block is typically defined by the curly braces: {}) that it has been declared within.

function letVsVar() {
    //pizza is not available up here
    for( let pizza = 0; pizza < 3; pizza++ ) {
        //pizza is only available within this function (inside of the () and {})
    }
    //pizza is not available down here
}

The above examples show exactly where the let variable can be accessed within the function. Below, we’ve replaced let with var, so you can see how it is visible and available throughout the scope of the entire function, not just within the block.

function letVsVar() {
    //pizza works up here
    for( var pizza = 0; pizza < 3; pizza++ ) {
        //pizza is available here, there, and everywhere within this function
    }
    Console.log(pizza)
    // because pizza is available down here as well
}

Filed Under: JavaScript Tagged With: let, var

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved