VxMxPx
VxMxPx

Reputation: 335

Is it safe to declare a delete method in JavaScript

So the question is simply, if it's safe (wise) to declare method called "delete" in JavaScript. Example:

var request = {
    delete : function (url) {
        // Some code...
    }
}
request.delete('http://page.dev/users/1');

I've tested this in Firefox and it's functional, but just wondering if it could cause problems in some other browsers; or in general if is it a good practice.

Upvotes: 33

Views: 13075

Answers (6)

Erik Wendel
Erik Wendel

Reputation: 91

You should note that even using the bracket syntax for accessing properties isn't safe on all browsers.

Internet Explorer 7 and 8 will crash anyway.

Upvotes: 0

suff trek
suff trek

Reputation: 39777

I'd use different keyword as other suggested - you can use synonyms like remove or purge - you get the idea.

But more important - make sure you're doing server-side validation for legibility of the call. Otherwise anybody could construct a delete call using "http://page.dev/users/1"

Upvotes: 1

Dave
Dave

Reputation: 46259

You'll never have an issue if you use this['style'], but with this.style, you should avoid reserved words, which does includes delete. According to the spec, it's actually OK to use reserved words as property names, but I would avoid it anyway because there are some bad implementations around (also it just has a generally bad feel to use reserved words, whatever the context).

Upvotes: 10

bfavaretto
bfavaretto

Reputation: 71918

According to the language specification:

Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1).

This means you cannot use delete as a variable or function name, but you can use it as an object property name. This was not the case in the previous version of the specification, which is why most other answers are recommending you avoid using reserved words entirely. However, in ES5-compliant implementations, there should be no problem.

Upvotes: 15

xavierm02
xavierm02

Reputation: 8767

No it's not a good idea because delete is a keyword. In the newest versions, they restricted the places where it will cause problems but there still are some.

One way of avoiding any kind of problem would be to use:

var request = {
    "delete" : function (url) {
        // Some code...
    }
}
request["delete"]('http://page.dev/users/1');

But that's probably a bit less optimized and it's kind of ugly. I'd go with another name such as "remove".

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

delete is in the JavaScript reserved words list, use at your own peril.

delete object.property

delete object['property']

Upvotes: 2

Related Questions