Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use the 'with' keyword in JavaScript?
The with keyword in JavaScript creates a shorthand for referencing an object's properties and methods. However, it's deprecated and not recommended in modern JavaScript due to performance and security issues.
Syntax
with (object) {
// properties used without the object name and dot
}
Basic Example
Here's how with works with a simple object:
<html>
<head>
<title>JavaScript with Statement</title>
</head>
<body>
<script>
var person = {
name: "John",
age: 30,
city: "New York"
};
// Using with statement
with (person) {
document.write("Name: " + name + "<br>");
document.write("Age: " + age + "<br>");
document.write("City: " + city + "<br>");
}
</script>
</body>
</html>
Name: John Age: 30 City: New York
Complex Example with Constructor
<html>
<head>
<title>with Statement Example</title>
<script>
// Define a function which will work as a method
function addPrice(amount) {
with (this) {
price = amount;
}
}
function book(title, author) {
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice;
}
</script>
</head>
<body>
<script>
var myBook = new book("Python", "Tutorialspoint");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Book title is : Python Book author is : Tutorialspoint Book price is : 100
Why with is Not Recommended
The with statement has several problems:
-
Performance issues: JavaScript engines cannot optimize code inside
withblocks - Ambiguity: Variable lookups become confusing and error-prone
-
Strict mode:
withis forbidden in strict mode
Modern Alternative
Instead of with, use destructuring assignment:
<html>
<head>
<title>Modern Alternative to with</title>
</head>
<body>
<script>
var person = {
name: "John",
age: 30,
city: "New York"
};
// Modern approach using destructuring
var {name, age, city} = person;
document.write("Name: " + name + "<br>");
document.write("Age: " + age + "<br>");
document.write("City: " + city + "<br>");
</script>
</body>
</html>
Name: John Age: 30 City: New York
Conclusion
While the with statement provides shorthand access to object properties, it's deprecated and should be avoided. Use destructuring assignment or explicit property access for cleaner, more maintainable code.
Advertisements
