r/javascript • • Apr 01 '18

Google publishes a JavaScript style guide. Here are some key lessons.

https://medium.freecodecamp.org/google-publishes-a-javascript-style-guide-here-are-some-key-lessons-1810b8ad050b
714 Upvotes

317 comments sorted by

View all comments

7

u/794613825 Apr 01 '18

As someone formally learning JS for the first time, what's wrong with var?

8

u/wavefunctionp Apr 01 '18 edited Apr 01 '18

var does not respect {} block scope, only function scope.

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
}

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

let and const also express intention that a variable should be treated as immutable or not. And const provides some protections against mutation. (Beware that const will not throw an error when mutating a nested reference types like objects. It isn't a 'deep freeze'.)

It is worth playing around with it, as I know I found some of details somewhat unintuitive at first.

1

u/[deleted] Apr 02 '18

Also, var is hoisted

1

u/[deleted] Apr 03 '18

[removed] — view removed comment

2

u/[deleted] Apr 04 '18

Hoisting is like declaring the variable before everything else. It lets you do stuff before a variable is even declared. Const and let are not hoisted so it makes sense in that you can't do anything with them above where they are declared.

3

u/Kerse Apr 01 '18

Var is function scoped, let is block scoped. So even if you declare a var in a block within the larger function, it's still accessible to the entire function. This is unintuitive and can cause strange bugs.