Bugs

JavaScript Hoisting: How var Causes Unexpected Behavior

Hoisting moves var declarations to the top of their scope. Variables can be accessed before assignment, returning undefined instead of throwing an error.


❌ Hoisting Bug with var

console.log(username);  // undefined, not an error!
var username = 'Alice';

function createUser() {
  var role = 'user';
  if (true) {
    var role = 'admin';  // Same variable — overwrites outer role!
  }
  return role;  // 'admin', not 'user'
}

✅ Fixed with let and const

// Accessing before declaration throws ReferenceError:
const username = 'Alice';

function createUser() {
  let role = 'user';
  if (true) {
    let role = 'admin';  // New block-scoped variable
  }
  return role;  // 'user' as intended
}
💡

Pro tip: Never use var in modern JavaScript. Use const by default and let only when the variable needs to be reassigned. Enable ESLint's no-var rule.

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Closure BugsJavascript Equality Operator BugsJavascript This Context Bugs