I saw JavaScript code which begins with with
. That's a bit confusing. What does it do and how can it be used correctly?
with (sObj) return options[selectedIndex].value;
Thus, with statement helps avoiding bugs and leaks by ensuring that a resource is properly released when the code using the resource is completely executed. The with statement is popularly used with file streams, as shown above and with Locks, sockets, subprocesses and telnets etc.
In javascript I have seen i++ used in many cases, and I understand that it adds one to the preceding value: for (var i=1; i<=10; i++) { console. log(i); } Run code snippet.
Variables declared with var are in the function scope. Variables declared as let are in the block scope. Variables declared as const are in the block scope. Look at the below code snippets to understand this.
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
It adds to the scope of the statements contained in the block:
return sObj.options[selectedIndex].value;
can become:
with (sObj)
return options[selectedIndex].value;
In your case, it doens't do a whole lot...but consider the following:
var a, x, y;
var r = 10;
a = Math.PI * r * r;
x = r * Math.cos(PI);
y = r * Math.sin(PI /2);
Becomes:
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
...saves a couple of keystrokes. The Mozilla documentation actually does a pretty good job of explaining things in a little more detail (along with pros and cons of using it):
with - Mozilla Developer Center
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With