Basics

JS Mistakes

Common JavaScript Mistakes

JavaScript mistakes include misusing var and ignoring strict mode.

Misusing 'var' Keyword

In JavaScript, the var keyword is used to declare variables. However, it can lead to unexpected behavior due to its function-scoping nature. This can introduce bugs that are hard to trace.

In the example above, x is accessible outside the if block because var is function-scoped. This behavior can lead to unexpected results if not handled carefully.

The Solution: Use 'let' and 'const'

To avoid the pitfalls of var, prefer using let and const for variable declarations. These keywords are block-scoped, meaning they are confined to the block in which they are declared.

In this revised example, using let ensures that x is only accessible within the if block, preventing accidental access outside its intended scope.

Ignoring Strict Mode

Strict mode is a way to opt into a restricted variant of JavaScript, which can help you write cleaner code and catch common mistakes early.

In strict mode, assigning a value to an undeclared variable, like x in the example, throws a ReferenceError. This encourages better coding practices and helps avoid bugs.

Enabling Strict Mode

To enable strict mode, simply add "use strict"; at the beginning of your JavaScript file or function. It's a good practice to use strict mode in all your scripts.