spirosgyros.net

Understanding the Avoidance of the 'with' Statement in JavaScript

Written on

Chapter 1: The 'with' Statement Explained

In the realm of JavaScript, a widely accepted principle among developers is to "stay away from the 'with' statement." While this advice is sound, the reasoning behind it isn't always clear. Understanding why it's best to avoid this statement can deepen your grasp of JavaScript and enhance your coding skills.

The primary purpose of the 'with' statement was to reduce repetitive object property calls. For example:

foo.bar.baz.x = 1;

foo.bar.baz.y = 2;

foo.bar.baz.z = 3;

with (foo.bar.baz) {

x = 1;

y = 2;

z = 3;

}

However, this can be simply accomplished through variable assignment:

var p = foo.bar.baz;

p.x = 1;

p.y = 2;

p.z = 3;

This demonstrates that the 'with' statement is often unnecessary. Nowadays, its use is rare, and in strict mode, it leads to errors:

function foo() {

'use strict';

with ({}) {}

}

Thus, the 'with' statement has largely fallen out of favor.

Section 1.1: Insights from Literature

To provide a comprehensive overview, let's examine some notable JavaScript literature that addresses the 'with' statement. My collection includes several books, and I'll highlight a few that specifically discuss this topic:

  1. "JavaScript: The Definitive Guide" (5th Edition, David Flanagan, P109):

    The 'with' statement is described as a means to modify the scope chain temporarily, but its use complicates optimization and can lead to unexpected behavior.

  2. "JavaScript Advanced Programming" (3rd Edition, Nicholas C. Zakas, P60):

    The author explains that while the 'with' statement can set the scope to a particular object, its performance drawbacks and debugging challenges make it inadvisable for larger applications.

  3. "JavaScript: The Good Parts" (Revised Edition, Douglas Crockford, P110):

    Crockford categorizes the 'with' statement as a detrimental feature, emphasizing its unpredictable nature and potential to hinder performance.

  4. "Understanding ECMAScript 6" (Axel Rauschmayer, P153):

    This book provides an extensive examination of the reasons for deprecating the 'with' statement, combining various insights to present a clear argument against its usage.

Subsection 1.1.1: Performance Concerns

Performance issues related to JavaScript's 'with' statement

Performance Issues

The 'with' statement is often criticized for its impact on performance. While many reference materials mention these concerns, they seldom provide examples. You can easily test the performance difference with the following code snippets:

var a = { a: { a: 1 } };

function useWith() {

with (a.a) {

for (var i = 0; i < 1000000; i++) {

a = i;

}

}

}

var b = { b: { b: 1 } };

function noWith() {

for (var i = 0; i < 1000000; i++) {

b.b.b = i;

}

}

var t1 = new Date().getTime();

useWith();

alert(new Date().getTime() - t1);

var t2 = new Date().getTime();

noWith();

alert(new Date().getTime() - t2);

Although the performance difference might seem minor, the unpredictability of the 'with' statement is a more significant concern.

Section 1.2: The Unpredictability Factor

The unpredictability introduced by the 'with' statement is a crucial reason for its avoidance. It disrupts lexical scope by inserting objects into the scope chain, creating confusing code behavior. For instance:

function foo(a) {

with (a) {

console.log(a);

}

}

foo("sword");

foo({});

foo({ a: "sword" });

While the first two calls are straightforward, passing an object with a property 'a' can lead to unexpected results. This unpredictability can escalate with multiple parameters, complicating code readability and maintenance.

Moreover, variables declared within a 'with' statement do not belong to the specified object:

var a = {};

with (a) {

x = 'sword';

var y = 'wang';

}

console.log(a.x);

console.log(a.y);

console.log(window.x);

console.log(window.y);

This behavior can lead to confusion regarding the scope and context of variables.

Chapter 2: Conclusion

The first video titled "Exercises: Conditional Statements - Javascript In Depth - YouTube" offers practical exercises focused on conditional statements in JavaScript, providing insights on how to effectively use them without the complications of the 'with' statement.

The second video, "Conditional Statements - Javascript In Depth - YouTube," delves deeper into conditional logic, reinforcing best practices in JavaScript programming.

In summary, the 'with' statement, despite its initial intentions, introduces significant complications in coding. The performance drawbacks and unpredictability it brings are strong reasons to avoid its use in JavaScript development. Understanding these issues will not only enhance your coding practices but also contribute to writing cleaner, more efficient code.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Are Fridays on the Decline? Insights into Modern Work Culture

An exploration of the evolving work landscape and Fridays' role in it, highlighting trends and personal reflections on work-life balance.

# Embracing Fear: A Path to Self-Discovery and Growth

Discover how embracing fear can lead to self-discovery, healing, and a more fulfilling life.

Embracing Emotional Availability: Healing from Parental Absence

Explore the impact of emotionally unavailable parents on adult relationships and discover pathways to healing and self-acceptance.