Progress pill
Intermediate JavaScript

Avoiding Bugs

  • Var and assignment without declaration
  • Weak type system
  • "use strict"
This chapter shows some of the most common pitfalls in JavaScript, and how to avoid them.

var and assignment without declaration

In older JavaScript code, variables were often declared using the var keyword. Unlike let and const, which you've already learned about, var might behave in confusing ways.
For example:
{ var message = "hello" } console.log(message)
You might expect message to only exist inside the block, but it doesn’t. var ignores block scope and it makes the variable available throughout the entire function or file.
This can lead to unexpected behavior, especially in larger programs. For this reason, modern JavaScript code should always use let or const instead of var.
Even worse, JavaScript lets you assign values to variables without declaring them at all:
function greet() { user = "Alice" } greet() console.log(user) // prints "Alice"
This creates a new global variable user without any declaration. This can happen silently and lead to bugs that are hard to track down, especially if it was just a typo. Always declare variables using let or const.

Weak type system

JavaScript is weakly typed, meaning it automatically converts values from one type to another if needed. This is called type coercion, and while it can be convenient, it often leads to confusing results.
For example:
console.log("5" + 1) // "51" console.log("5" - 1) // 4 console.log(true + 1) // 2 console.log(null + 1) // 1
In these examples, JavaScript tries to guess what you meant. Sometimes it turns strings into numbers, or booleans into numbers, or numbers into strings. This can make your code behave in unexpected ways.
Being aware of JavaScript's weak typing system is important. When things start acting strangely, it might be due to unexpected type coercion.

"use strict"

You can enable a stricter mode that turns some silent errors into real errors, and stops you from using some of the more dangerous features of the language.
To enable this stricter mode, add this line at the top of your file or function:
"use strict"
For example:
"use strict" name = "Alice" // ReferenceError: name is not defined
Without strict mode, JavaScript would silently create a global variable called name. But with strict mode, this becomes a real error, helping you catch bugs earlier.
Strict mode also disables some outdated features of JavaScript, and makes your code easier to optimize and maintain.