While diving into JavaScript today, I explored two important topics — Strict Mode and some handy String Methods.These concepts may seem simple, but they help in writing cleaner, more predictable code.
Let’s break them down with examples:
JavaScript Strict Mode
Non-Strict Mode
In regular JavaScript (non-strict mode), you can accidentally create a global variable by assigning a value without declaring it. Like this:
i = 10;
console.log(i); // 10
Here, JavaScript silently creates a global variable i
, which can be dangerous and lead to bugs that are hard to trace.
Strict Mode
Strict mode helps catch such mistakes. By adding "use strict"
at the top of your file or function, JavaScript becomes less forgiving:
"use strict";
i = 10; // ReferenceError: i is not defined
console.log(i);
Since i
wasn’t declared using let
, const
, or var
, it throws an error. This encourages better coding practices and avoids unexpected global variables.
JavaScript String Methods
Here are some essential string methods that help manipulate text in JavaScript:
toLowerCase()
Converts a string to lowercase.
let text = "HELLO WORLD";
console.log(text.toLowerCase()); // hello world
trim()
Removes whitespace from both ends of a string.
let text = " hello world ";
console.log(text.trim()); // "hello world"
trimStart()
Removes whitespace only from the beginning of the string.
let text = " hello world ";
console.log(text.trimStart()); // "hello world "
trimEnd()
Removes whitespace only from the end of the string.
let text = " hello world ";
console.log(text.trimEnd()); // " hello world"
padStart()
Pads a string from the start until it reaches the desired length.
let text = "5";
console.log(text.padStart(5, "0")); // "00005"
Useful when formatting numbers like adding leading zeros.
padEnd()
Pads a string from the end until it reaches the desired length.
let text = "5";
console.log(text.padEnd(5, "0")); // "50000"
Great for aligning text output or formatting display values.
Top comments (0)