Are "(Function ( ) { } ) ( )" and "(Function ( ) { } ( ) )" Functionally Equal in JavaScript

Are (function ( ) { } ) ( ) and (function ( ) { } ( ) ) functionally equal in JavaScript?

No; they are identical


However, if you add new beforehand and .something afterwards, they will be different.

Code 1

new (function() {
this.prop = 4;
}) ().prop;

This code creates a new instance of this function's class, then gets the prop property of the new instance.

It returns 4.

It's equivalent to

function MyClass() {
this.prop = 4;
}
new MyClass().prop;


Code 2

new ( function() {
return { Class: function() { } };
}() ).Class;

This code calls new on the Class property.

Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the new expression, and instead call the function normally, returning its return value.

The new expression parses up to the .Class and instantiates that. (the parentheses after new are optional)

It's equivalent to

var namespace = { Class: function() { } };

function getNamespace() { return namespace; }

new ( getNamespace() ).Class;
//Or,
new namespace.Class;

Without the parentheses around the call to getNamespace(), this would be parsed as (new getNamespace()).Class — it would call instantiate the getNamespace class and return the Class property of the new instance.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.

If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

// Example using a function expression
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: function() {
console.log('Inside `bar`:', this.foo);
},
};
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject

Is there a difference between (function() {...}()); and (function() {...})();?

There is no practical difference in those two forms, but from a grammatical point of view the difference between the two is that The Grouping Operator - the parentheses - will hold in the first example a CallExpression, that includes the FunctionExpression:


CallExpression
| |
FunctionExpression |
| |
V V
(function() { }());
^ ^
|--PrimaryExpression --|

In the second example, we have first a whole CallExpression, that holds the FunctionExpression:


PrimaryExpression
|
FunctionExpression
|
V
(function() { })();
^ ^
|-- CallExpression --|

Are these JS conditional statements functionally equivalent?

If expr is a boolean expression, as it is here, then there is no need to write

if (expr) return true;
else return false;

or to write

if (expr) x = true;
else x = false;

or to ever write

expr ? true : false

because being a boolean expression, expr can be returned, or assigned, directly:

return expr;

x = expr;

The tersest alternative is one you didn't give:

function isEntering() { return this.stage === 'entering'; }

JavaScript isset() equivalent

I generally use the typeof operator:

if (typeof obj.foo !== 'undefined') {
// your code here
}

It will return "undefined" either if the property doesn't exist or its value is undefined.

(See also: Difference between undefined and not being defined.)

There are other ways to figure out if a property exists on an object, like the hasOwnProperty method:

if (obj.hasOwnProperty('foo')) {
// your code here
}

And the in operator:

if ('foo' in obj) {
// your code here
}

The difference between the last two is that the hasOwnProperty method will check if the property exist physically on the object (the property is not inherited).

The in operator will check on all the properties reachable up in the prototype chain, e.g.:

var obj = { foo: 'bar'};

obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true

As you can see, hasOwnProperty returns false and the in operator returns true when checking the toString method, this method is defined up in the prototype chain, because obj inherits form Object.prototype.

When to use functional update form of useState() hook, eg. setX(x= x+1)

Use the function form when the setter may close over an old state value.

For example, if an async request is initiated, and you want to update state after that's done, the request that was made will have scope of the state as it was at the beginning of the request, which may not be the same as the most up-to-date render state.

You may also need to use the function form if the same state value was just updated, eg

setValue(value + 1);
// complicated logic here
if (someCondition) {
setValue(value => value + 1);
}

because the second call of setValue closes over an old value.

Different between (function(){})() and (function(){}()) , self invoking anonymous function

Technically the first defines an anonymous function, then calls it, the second defines an anonymous function which calls itself as it's defined. Realistically, they are identical.

What is the (function() { } )() construct in JavaScript?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).

Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.

Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
// do something with foo here foo
})('foo value')

Difference between (function(){})(); and function(){}();

Peter Michaux discusses the difference in An Important Pair of Parens.

Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises,

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

  • How does the "this" keyword work?

var x = function() vs. function x()  —  Function declaration syntax

  • var functionName = function() {} vs function functionName() {}

(function(){})()  —  IIFE (Immediately Invoked Function Expression)

  • What is the purpose?, How is it called?
  • Why does (function(){…})(); work but function(){…}(); doesn't?
  • (function(){…})(); vs (function(){…}());
  • shorter alternatives:
    • !function(){…}(); - What does the exclamation mark do before the function?
    • +function(){…}(); - JavaScript plus sign in front of function expression
    • !function(){ }() vs (function(){ })(), ! vs leading semicolon
  • (function(window, undefined){…}(window));

someFunction()()  —  Functions which return other functions

  • Two sets of parentheses after function call

=>  —  Equal sign, greater than: arrow function expression syntax

  • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

|>  —  Pipe, greater than: Pipeline operator

  • What does the "|>" operator do in JavaScript?

function*, yield, yield*  —  Star after function or yield: generator functions

  • What is "function*" in JavaScript?
  • What's the yield keyword in JavaScript?
  • Delegated yield (yield star, yield *) in generator functions

[], Array()  —  Square brackets: array notation

  • What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
  • What is array literal notation in javascript and when should you use it?

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value}  —  Curly brackets: object literal syntax (not to be confused with blocks)

  • What do curly braces in JavaScript mean?
  • Javascript object literal: what exactly is {a, b, c}?
  • What do square brackets around a property name in an object literal mean?
  • How does this object method definition work without the "function" keyword? (ES2015 Method definitions)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}`  —  Backticks, dollar sign with curly brackets: template literals

  • What does this `…${…}…` code from the node docs mean?
  • Usage of the backtick character (`) in JavaScript?
  • What is the purpose of template literals (backticks) following a function in ES6?

//  —  Slashes: regular expression literals

  • Meaning of javascript text between two slashes

$  —  Dollar sign in regex replace patterns: $$, $&, $`, $', $n

  • JavaScript replace() method dollar signs

()  —  Parentheses: grouping operator

  • MDN: Grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"]  —  Square brackets or dot: property accessors

  • JavaScript property access: dot notation vs. brackets?

?., ?.[], ?.()  —  Question mark, dot: optional chaining operator

  • Question mark after parameter
  • Null-safe property access (and conditional assignment) in ES6/2015
  • Optional Chaining in JavaScript
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

::  —  Double colon: bind operator

  • JavaScript double colon (bind operator)

new operator

  • What is the 'new' keyword in JavaScript?
  • What is "new.target"?

...iter  —  Three dots: spread syntax; rest parameters

  • (...rest) => {}  —  What is the meaning of “…args” (three dots) in a function definition?
  • fn(...args)  —  What is the meaning of “foo(…arg)” (three dots in a function call)?
  • [...iter]  —  javascript es6 array feature […data, 0] “spread operator”
  • {...props}  —  Javascript Property with three dots (…), What does the '…rest' stand for in this object destructuring?


Increment and decrement

++, --  —  Double plus or minus: pre- / post-increment / -decrement operators

  • ++someVariable vs someVariable++ in Javascript


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

  • What is the purpose of the delete operator in Javascript?

void operator

  • What does `void 0` mean?

+, -  —  Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

  • What does = +_ mean in JavaScript, Single plus operator in javascript
  • What's the significant use of unary plus and minus operators?
  • Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
  • Why does JavaScript handle the plus and minus operators between strings and numbers differently?

|, &, ^, ~  —  Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

  • What do these JavaScript bitwise operators do?
  • How to: The ~ operator?
  • Is there a & logical operator in Javascript
  • What does the "|" (single pipe) do in JavaScript?
  • What does the operator |= do in JavaScript?
  • What does the ^ (caret) symbol do in JavaScript?
  • Using bitwise OR 0 to floor a number, How does x|0 floor the number in JavaScript?
  • Why does ~1 equal -2?
  • What does ~~ ("double tilde") do in Javascript?
  • How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call? (also here and here)

%  —  Percent sign: remainder operator

  • What does % do in JavaScript?

&&, ||, !  —  Double ampersand, double pipe, exclamation point: logical operators

  • Logical operators in JavaScript — how do you use them?
  • Logical operator || in javascript, 0 stands for Boolean false?
  • What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?, JavaScript OR (||) variable assignment explanation, What does the construct x = x || y mean?
  • Javascript AND operator within assignment
  • What is "x && foo()"? (also here and here)
  • What is the !! (not not) operator in JavaScript?
  • What is an exclamation point in JavaScript?

??  —  Double question mark: nullish-coalescing operator

  • How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

**  —  Double star: power operator (exponentiation)

  • x ** 2 is equivalent to Math.pow(x, 2)
  • Is the double asterisk ** a valid JavaScript operator?
  • MDN documentation


Equality operators

==, ===  —  Equal signs: equality operators

  • Which equals operator (== vs ===) should be used in JavaScript comparisons?
  • How does JS type coercion work?
  • In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?
  • [] == ![] evaluates to true
  • Why does "undefined equals false" return false?
  • Why does !new Boolean(false) equals false in JavaScript?
  • Javascript 0 == '0'. Explain this example
  • Why false == "false" is false?

!=, !==  —  Exclamation point and equal signs: inequality operators

  • != vs. !==
  • What is the difference between != and !== operators in JavaScript?


Bit shift operators

<<, >>, >>>  —  Two or three angle brackets: bit shift operators

  • What do these JavaScript bitwise operators do?
  • Double more-than symbol in JavaScript
  • What is the JavaScript >>> operator and how do you use it?


Conditional operator

?:…  —  Question mark and colon: conditional (ternary) operator

  • Question mark and colon in JavaScript
  • Operator precedence with Javascript Ternary operator
  • How do you use the ? : (conditional) operator in JavaScript?


Assignment operators

=  —  Equal sign: assignment operator

  • What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

This symbol is also used for default parameters or default values in a destructuring assignment:

  • what does (state = {}) => state means
  • What does ({"key": "value"} = {}) syntax mean inside a JavaScript function

%=  —  Percent equals: remainder assignment

  • Having Confusion with Modulo operator

+=  —  Plus equals: addition assignment operator

  • How does += (plus equal) work?

&&=, ||=, ??=  —  Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

  • What purpose do &&=, ||= and ??= serve?
  • Replace a value if null or undefined in JavaScript
  • Set a variable if undefined
  • Ruby’s ||= (or equals) in JavaScript?
  • Original proposal
  • Specification

<<=, >>=, >>>=, &=, ^=, |= — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments

  • What do these JavaScript bitwise operators do?

Destructuring

  • of function parameters: Where can I get info on the object parameter syntax for JavaScript functions?
  • of arrays: Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?
  • of objects/imports: Javascript object bracket notation ({ Navigation } =) on left side of assign


Comma operator

,  —  Comma operator (not to be confused with the comma used in variable declarations)

  • What does a comma do in JavaScript expressions?
  • Comma operator returns first value instead of second in argument list?
  • When is the comma operator useful?


Control flow

{}  — Curly brackets: blocks (not to be confused with object literal syntax)

  • JavaScript curly braces with no function or json

Declarations

var, let, const  —  Declaring variables

  • What's the difference between using "let" and "var"?
  • Are there constants in JavaScript?
  • What is the temporal dead zone?
  • var a, b;  —  Comma used in variable declarations (not to be confused with the comma operator): JavaScript variable definition: Commas vs. Semicolons


Label

label:  —  Colon: labels

  • What does the JavaScript syntax foo: mean?
  • What does ':' (colon) do in JavaScript?


Other

123n  —  n after integer: BigInt

  • What does character 'n' after numeric literal mean in JavaScript?

#  —  Hash (number sign): Private methods or private fields

  • What does the # symbol do in JavaScript?

_  —  Underscore: separator in numeric literals

  • Javascript numeric separators?
  • Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?


Related Topics



Leave a reply



Submit