Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "with" do in JavaScript?

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;
like image 425
streetparade Avatar asked Mar 29 '10 13:03

streetparade


People also ask

What is the purpose of with statement?

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.

What is i ++ in JS?

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.

What is let const and VAR in JavaScript?

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.

Should you use let or VAR?

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.


1 Answers

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

like image 58
Justin Niessner Avatar answered Oct 18 '22 20:10

Justin Niessner