Var let & const

okay please tell me if my understanding of const, var & let is correct

  • const is a signal that the identifier won’t be reassigned.
  • let signals that the variable will be used only in the block it’s defined in,
  • var signals that the variable may or may not be reassigned, and the variable may or may not be used for an entire function.

so if my understanding is correct. I cant see why i will need to use var instead of let (unless i want to use a variable to be accessible in the entire program).
Am i correct?

2 Likes

I’m guessing you read that straight out of https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75 – and it’s pretty accurate.

var serves much the same use as let. One important distinction, though, is referred to as variable hoisting. With const and let, a variable isn’t available until the line in which it’s been defined. With var, even if I define my variables on the last line of my function, they are “hoisted” to the beginning of the function and available throughout. It is bad form, but it works.

More on variable hoisting: https://www.vojtechruzicka.com/javascript-hoisting-var-let-const-variables/

1 Like

Your understanding is not complete therefore not correct.

  1. const - constant cannot be changed through reassignment, var and let can.
    Be aware that if an object is assigned to const variable it is mutable !!! so the references inside the object can be reassigned, unless you going to freeze the object Object.freeze()
const number = 1;

try {
  number = 999;
} catch(err) {
  console.log(err);
  // expected output: TypeError: invalid assignment to const `number' 
  // Note - error messages will vary depending on browser
}

console.log(number);
// expected output: 1
  1. ‘let’ is the new ‘var’. Not really, is just different behaviour. Use var unless you need behaviour explained bellow.

When you declare let variables, those are not hoisted so they have to be declared before they are used.

let statement declares a block scope local variable, optionally initializing it to a value.

you can create scope in a block statement this way

{ 
  let scopeInThisBlock = 22;
} 

not able with var.

Now let’s see var and let in action.

//x declared and assigned in global scope
let x = 1;

if (x === 1) {
  let x = 2;
  
 //let is creating in this block scope, a new variable x !!!!!!!!!!!!! the block scope has been created thanks to let 

  alert(x);
  // expected output: 2
}

alert(x);
// expected output: 1

Now with var:

var x1 = 1;

if (x === 1) {
   // var is going to override the global x1 to value of 2, no scope here !!!!!!!!!
  var x1 = 2;
   
  alert(x1);
  // expected output: 2
}

alert(x1);
// expected output: 2

Probably I am going to add a full article about this and other details on my blog.

2 Likes

There are vanishingly few situations where you might use var, you are correct that let can be used anywhere you might use var. var is problematic, that’s why let and const exist. You can generally use const almost everywhere with most styles of JS programming

2 Likes

Ok, how do you code for Ie10 or versions of ie11 and old safari with let, when let is not supported? There are a lot of situations where you have to use var for the sake of compatibility. Use let if you have to.

If you want to get a really good understanding you can read this.

You Don’t Know JS: Scope & Closures

2 Likes

In ideal situation you don’t want client to reed your ‘raw’ code. There are a lot of tools that will prevent you from doing this as it’s considered a bad practice (i.e. babel compiler, webpack and tons of frameworks), so I wouldn’t be so worried about compatibility in this case. There are very healthy notion of immutable variables and const is 100% right way of doing JS. Only use let if there is no way of using const and forget about var as it’s obsolete.

You transpile with Babel, and with Babel you set the minimum required support. In most cases it’s a non-issue: if you’re manually writing code for earlier browsers that have no support, without any kind of build process then 🤷, I would hope you would be very aware of the issues — support for IE10 stopped 2 years ago, you need to have a good reason for supporting it. For IE11, you can’t use const in for…of loops (for (const x of xs)), most other things are fine.

There is no issue using var, but let and const are designed to obselete it, and Babel is ubiquitous.

2 Likes

There seems different opinions and I guess it deepends what sort of work you do. It is funny that you brought up babel but when you work on a huge project like I do you don’t want to wait for gulp to transform your let to evey minor change, you want to drbug in the browser console and then you learn to appreciate the old “var” for browser that don’t support “let”.

There seems different opinions and I guess it deepends what sort of work you do. It is funny that you brought up babel but when you work on a huge project like I do you don’t want to wait for gulp to transform your let to evey minor change, you want to drbug in the browser console and then you learn to appreciate the old “var” for browser that don’t support “let”.

Well, yes, if you’re on a huge project that has browser lock-in, and you don’t want rebuild times, then yes, possibly. But even then, unless your sole target is very old browsers (if it’s an app built solely for old versions of IE say), you shouldn’t really have to transpile in development, transpile for staging to test very old browsers, because the debug tools in IE are horrific.

1 Like

That’s pretty much it.

When you declare a let variable on line 551 and you reference it in a function on line 221 and you don’t understand what is happening go and read what you wrote above :)))

Why in the world would I want to declare a variable on line 551 and reference it on line 221?
Not a single time had I a problem with that sort of thing once I gained a good understanding of scope, closures and writing modular code.

1 Like

Well, as I said previously, depends on the project you working on. If you work with a team of 10 or more developers in a project devoped over 5 years for example and some one was doing this kind of stuff mentioned on the last comment you will face the situation. It is not uncommon. Let’s agree to disagree and let the developer to choose “when to use what” and that implicitly means that var has his place and is not going to pe obsolete or deprecated soon or ever.

That seems like an old project, maybe you and your team are not willing to heavily rewrite it just to drop using “var”. Fair enough.

Screencapping that particular answer is a wee bit disengenuous given its age and the other answers. The reason for it being slower when that answer was written (which is no longer really an issue) is the entire reason for it existing in the first place.

But I get where you’re coming from, I’ve worked on much older codebases in large teams, it’s fair enough what your saying, but ime it tends to not be a massive issue in practice: just being able to use modules outweighs almost any downside to the tooling process.

var is never going to be deprecated, you can’t generally deprecate anything on the web platform, but let and const have fundamentally better properties though, and prevent loads of mistakes, and can obselete it :woman_shrugging:

4 Likes

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

example below:

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

While I don’t typically use var in production, I’ve found that a good use case for it is quickly testing functions.

Typically, I write functions using the arrow syntax like this:

const sayHello = name => {
    return `hello ${name}`;
}

When testing/debugging functions in the console, using const can be annoying since you will have to either refresh the page or change the name of the function every time you change the function you are trying to debug (can’t redeclare let or const).

To avoid this I like to use var in the place of const while debugging, then once I am finished and the function appears to be working correctly I’ll switch it back to const.

1 Like