What is the difference between let and var when declaring variables in javascript?

Both let and var create mutable (re-assignable) variables in JavaScript. Both follow the same initalisation pattern as well:var a = 123;let a = 123;The difference between let and var comes down to something called scope.A variable declared using the var syntax will be availible for the entire local scope function it's declared in.A variable that is declared using the let syntax, will only be availible for the scope in which it is declaredHere are some examples:function aFunction() { var globalA = 123; let globalB = 123; for(let i = 0; i < 10; i++) { let x = i; console.log(x) // 0 to 10 } console.log(x) // undefined <- Outside of the scope of this variable for(var j = 0; j < 10; j++) { console.log(j); // 0 to 10 } console.log(j) // 10}

LB
Answered by Luke B. Javascript tutor

1050 Views

See similar Javascript Mentoring tutors

Related Javascript Mentoring answers

All answers ▸

I've just heard about objects. How do I use them and do they work with Arrays?


How would you change the background colour of a div with the id "colourme" to purple?


Suppose that you have a <p> element with an id of 'id1'. Use javascript to set the inner html of this element to 'hello!'


What is the importance of javascript in the web?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences