Why is “this” in an anonymous function undefined when using strict?

It’s because, until ECMAscript 262 edition 5, there was a big confusion if people who where using the constructor pattern, forgot to use the new keyword. If you forgot to use new when calling a constructor function in ES3, this referenced the global object (window in a browser) and you would clobber the global object … Read more

Why use named function expressions?

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. The variable you’re assigning it to has a name, but the function does not. (Update: That was true through ES5. As of ES2015 [aka ES6], often a function created with an anonymous expression gets a true name [but … Read more

Is it valid to define functions in JSON results?

No. JSON is purely meant to be a data description language. As noted on http://www.json.org, it is a “lightweight data-interchange format.” – not a programming language. Per http://en.wikipedia.org/wiki/JSON, the “basic types” supported are: Number (integer, real, or floating point) String (double-quoted Unicode with backslash escaping) Boolean (true and false) Array (an ordered sequence of values, … Read more

Location of parenthesis for auto-executing anonymous JavaScript functions?

They’re virtually the same. The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined. The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined. I don’t think there’s a “right” … Read more

Why do arrow functions not have the arguments array? [duplicate]

Arrow functions don’t have this since the arguments array-like object was a workaround to begin with, which ES6 has solved with a rest parameter: var bar = (…arguments) => console.log(arguments); arguments is by no means reserved here but just chosen. You can call it whatever you’d like and it can be combined with normal parameters: … Read more

removeEventListener on anonymous functions in JavaScript

if you are inside the actual function, you can use arguments.callee as a reference to the function. as in: button.addEventListener(‘click’, function() { ///this will execute only once alert(‘only once!’); this.removeEventListener(‘click’, arguments.callee); }); EDIT: This will not work if you are working in strict mode (“use strict”;)