简体   繁体   中英

Does a statement with only a variable name do something in JavaScript?

In this example:

someVariable;

does the code do anything? More technically, is there some work associated with it from the point of view of a JS engine like V8?

I'm asking because I'm looking to temporarily suppress the "variable is declared but its value is never read" warning by TypeScript and I'm doing this:

function xyz(arg) {
  arg;
  // ...
}

Is there a better "no-op" construct in JavaScript?

One thing it does is it checks to see if the variable is defined, If it isn't, it'll throw an error.

If you're worried about side-effects, if you happen to be inside a with statement, it can invoke a getter and run code, but this is unlikely. If the variable name in question isn't local and happens to be a getter on window , it can also run code, eg

 Object.defineProperty(window, 'foo', { get() { console.log('getting'); }}); console.log('start'); foo; 

But this, too, is pretty unlikely.

If you're sure the variable referred to is a normal variable in scope, it won't do anything - it'll just be an unused expression.

Beside the checking of the exisiting of the variable, it perfoms an evaluation of the expression.

 var foo = { get bar() { console.log('get bar'); return 42; } }; foo.bar; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM