Building a Blogging Site with React and PHP: A Step-by-Step Guide
Uncover the Hidden Powers of JavaScript
As developers, we often write similar types of code and follow a pattern that may be comfortable for us; sometimes, it creates a sense of boring coding life.
However, we know JavaScript is vast and has many advanced features; discovering and using it can transform our development work and make it a more exciting and fulfilling life.
In this guide, we will explore 25 advanced JavaScript features that will enrich our JavaScript knowledge.
JavaScript allows labeling loops and block statements, enabling precise control with break and continue.
outerLoop: for (let i = 0; i < 5; i++) {
innerLoop: for (let j = 0; j < 5; j++) {
if (i === 2 && j === 2) break outerLoop;
console.log(`i=${i}, j=${j}`);
}
}
The comma operator allows multiple expressions to be evaluated in a sequence, returning the last expression’s result.
let a = (1, 2, 3); // a = 3
Beyond creating strings, tagged templates can be used for DSLs (Domain Specific Languages), sanitizing user input, or localization.
function htmlEscape(strings, ...values) {
// Example implementation
}
Though not recommended, JavaScript allows function declarations inside blocks, which can lead to different behaviors in non-strict mode.
if (true) {
function test() {
return "Yes";
}
} else {
function test() {
return "No";
}
}
test(); // Behavior varies depending on the environment
The void operator evaluates any expression and then returns undefined, useful for hyperlinks with JavaScript.
void (0); // returns undefined
Bitwise operators, like | and &, can perform some math operations much faster, though at the cost of readability.
let floor = 5.95 | 0; // Fast way to do Math.floor(5.95)
The with statement extends the scope chain for a block, allowing you to write shorter code. However, it’s not recommended due to readability and performance concerns.
with (document.getElementById("myDiv").style) {
background = "black";
color = "white";
}
JavaScript tries to fix missing semicolons, but relying on it can lead to unexpected results.
let x = 1;
let y = 2;
[x, y] = [y, x]; // Without proper semicolons, this could fail
The Intl object provides tools for internationalization (i18n) using this we can handle date, time, number formatting, and language-sensitive string comparisons.
# Formatting Numbers
const formatter = new Intl.NumberFormat(
'en-US',
{
style: 'currency',
currency: 'USD'
}
);
console.log(formatter.format(123456.789)); // $123,456.79
# Formatting Dates
const dateFormatter = new Intl.DateTimeFormat(
'de-DE',
{
dateStyle: 'long'
}
);
console.log(
dateFormatter.format(new Date())
); // Example: 28. Dezember 2024
# Collator for String Comparisons
const collator = new Intl.Collator(
'en',
{
sensitivity: 'base'
}
);
console.log(
collator.compare('a', 'A')
); // 0 (treats them as equal)
instanceof checks the prototype chain, while typeof returns a string indicating the type of the unevaluated operand.
function Person(){}
let person = new Person();
console.log(person instanceof Person); // true
console.log(typeof person); // "object"
ES6 allows functions to be block-scoped, similar to let and const.
{
function test() {
return "block scoped";
}
}
console.log(typeof test);
// "function" in non-strict mode, "undefined" in strict mode
Use the debugger statement to pause execution and open the debugger.
function problematicFunction() {
debugger; // Execution pauses here if the developer tools are open
}
eval() for Dynamic Code Executioneval executes a string as JavaScript code but comes with significant security and performance implications.
eval("let a = 1; console.log(a);"); // 1
__proto__ PropertyWhile __proto__ is widely supported for setting an object’s prototype, it’s non-standard. Use Object.getPrototypeOf() and Object.setPrototypeOf() instead.
let obj = {};
obj.__proto__ = Array.prototype; // Not recommended
document.write() directly writes to the HTML document, but using it can have negative implications, especially for loading external scripts synchronously.
document.write("<h1>Hello World!</h1>");
JavaScript allows for chained assignments, which can assign a single value to multiple variables in one statement.
let a, b, c;
a = b = c = 5; // Sets all three variables to the value of 5
The in operator checks if a property exists within an object without accessing the property value.
const car = {
make: 'Toyota',
model: 'Corolla'
};
console.log('make' in car); // true
When assigning properties to an object, if the property name is the same as the variable name, you can use the shorthand.
const name = 'Alice';
const age = 25;
const person = { name, age };
You can combine default parameter values with destructuring in function parameters for more readable and flexible function definitions.
function createPerson({ name = 'Anonymous', age = 0 } = {}) {
console.log(`Name: ${name}, Age: ${age}`);
}
createPerson({ name: 'Alice' }); // Name: Alice, Age: 0
createPerson(); // Name: Anonymous, Age: 0
Array.fill() to Initialize ArraysQuickly initialize an array with a specific value using the fill() method.
const initialArray = new Array(5).fill(0); // Creates an array [0, 0, 0, 0, 0]
Array.includes() for Presence CheckEasily check for the presence of an element within an array with the includes() method, which is more readable than using indexOf().
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits.includes('banana')); // true
When destructuring an object, you can assign properties to variables with different names using aliases.
const obj = { x: 1, y: 2 };
const { x: newX, y: newY } = obj;
console.log(newX); // 1
Use ?? to provide default values only when dealing with null or undefined, not other falsy values like 0 or ''.
const count = 0;
console.log(count ?? 10);
// 0, because count is not null or undefined
Create functions with dynamic names using computed property names in object literals.
const dynamicName = 'func';
const obj = {
[dynamicName]() {
return 'Dynamic Function Name!';
}
};
console.log(obj.func());
// "Dynamic Function Name!"
Use the hash # prefix to define private fields in a class, which cannot be accessed from outside the class.
class Counter {
#count = 0; // Private class field
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
I hope you enjoy these 25 advanced JavaScript features. Let me know which one is new for you, and if you have any other questions, feel free to share them in the comments.
Letβs keep pushing the boundaries of what we can achieve with JavaScript, staying curious and open to the endless possibilities.
π» Level up with the latest tech trends, tutorials, and tips - Straight to your inbox β no fluff, just value!
Your email address will not be published. Required fields are marked *
Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!
Comments (2)