๐ฆ JavaScript Strict Mode: The Strict School Principal ๐
Imagine your classroom is JavaScript. On normal days, students (your code) can sometimes be careless:
- They forget to put their names on assignments.
- They write on the desk.
- They break little rules and still get away with it.
But thenโฆ the strict principal walks in! ๐ค Suddenly, everyone must follow the rules exactly. No sloppiness allowed!
Thatโs what strict mode is in JavaScript.
๐ค What Is Strict Mode?
Strict mode is a way to tell JavaScript:
โHey! Be extra careful when running this code.โ
It helps catch mistakes, stop bad behavior, and make your code more secure and cleaner.
๐ง How to Turn on Strict Mode
All you need to do is add this at the top of your code:
"use strict";
Hereโs an example:
"use strict";
x = 10; // โ Error: x is not declared
Without "use strict";
, JavaScript would quietly let it slide.
With strict mode, it says: โNOPE! You must declare x
first with let
, const
, or var
.โ
๐ก๏ธ What Does Strict Mode Help With?
Here are some superpowers strict mode gives you:
1. โ No Using Undeclared Variables
"use strict";
myName = "Ekene"; // โ Error!
You must use let
, const
, or var
:
"use strict";
let myName = "Ekene"; // โ
Okay!
2. โ Stops You from Using Reserved Words
You canโt name a variable something like let
, class
, or interface
:
"use strict";
let let = 5; // โ Error!
Strict mode protects future JavaScript features.
3. โ No Duplicate Parameter Names
This would cause confusion:
"use strict";
function sayHi(name, name) {
console.log(name);
}
// โ Error!
4. ๐ Makes Your Code Safer and Cleaner
It helps you avoid sneaky bugs and makes your code easier to understand and fix.
๐งช Example Without and With Strict Mode
๐ด Without "use strict"
:
myAge = 13; // JavaScript just assumes it's a new variable
console.log(myAge);
๐ข With "use strict"
:
"use strict";
myAge = 13; // โ Error: You forgot to declare it
This helps catch mistakes early before they grow into hard-to-find bugs!
๐จ๐ฝโ๐ซ Why Should You Use It?
Strict mode is like having a strict but wise teacher. They might not let you bend the rules, but in the end, you learn better and become a pro faster!
Thatโs why experienced coders often say:
โStart every file with
"use strict";
โespecially when youโre still learning.โ
โ Review and Practice Questions
- What does
"use strict";
do in JavaScript? - Why is using undeclared variables a bad idea?
-
What will this code do?
"use strict"; score = 100;
- Write a correct version of the above code that works in strict mode.
- What happens if you try to use
let
as a variable name in strict mode?