Out with var

Learn why we should avoid using var to define variables in JavaScript.

All variables should be defined before their first use. If we forget to define a variable explicitly before assigning to it, we’ll accidentally define a global variable. The 'use strict'; directive saves us from that error. Prior to ES6, JavaScript required var to define variables. However, var is not the right choice, as you’ll see in this lesson.

Pitfalls of using var

var does two things poorly.

  • First, it does not prevent a variable from being redefined in a scope.
  • Second, it does not have block scope.

Let’s explore these two issues with examples.

Redefining

It’s poor programming practice to redefine a variable in the same scope since it often leads to errors in code.

Example

Here’s an example where a variable max is redefined.

Get hands-on with 1200+ tech skills courses.