Brackets in ES6 JavaScript - javascript

I'm desperate for someone to give me just some concise information about when I should use which brackets where and why in JS ES6. I know the basics but when we start talking about arrow syntax I just lose it and then can't see why we're wrapping braces in brackets etc... I feel like in order to truly understand why we lay things out the way we do I need to first understand what all of the use cases are for both {} and ().
For example. I'm really struggling to work out syntax like this:
const func = (obj) => {
console.log(obj.a)
}
func({a: "blue"})
It's the func({a: "blue"}) part I'm struggling with here.
Here's another example:
makeSound({
a: "bark",
b: 2,
c: "hiss"
})
function makeSound(options)
console.log("the" + options.a + "was a " + options.c)
I don't know what to make of this. What are we doing at the top with makeSound? I can see we're making an object but then why aren't we just declaring it as a variable with standard let makeSound = {}. What are we actually doing here? Is makeSound nothing untill we make it into a function further down the code?

It's the func({a: "blue"}) part I'm struggling with here.
{a: "blue"} is an object literal. The resulting object is passed as an argument to func(...).
I can see we're making an object but then why aren't we just declaring it as a variable with standard let makeSound = {}.
Because it is only needed once.
let details = {
a: "bark",
b: 2,
c: "hiss"
};
makeSound(details);
… would give the same result, but now you've got a details variable you don't need any more.
Is makeSound nothing untill we make it into a function further down the code?
function declarations are hoisted so it is a function even though the declaration appears later on.

I understand your confusion as there are quite a lot of curly braces indeed!
First, objects.
You define an object using brackets like this.
const obj = { a: 1 };
But you can also define an object inline, directly in a function argument list, using an object literal like this:
myFunc({ a: 1 }); // same as myFunc(obj);
Then you have arrow functions.
Their bodies is defined using curly braces too, just as regular functions, in which case you have to use the return keyword if you want to return a value from your function:
const myFunc = (arg) => { return 'hello ' + arg; }
However, arrow function also support implicit return, if you omit the curly braces, the return value will be implicit:
const myFunc = (arg) => 'hello ' + arg;
Now, you can also use the curly braces for desctructuring assignment.
For example:
const { a } = { a: 1 };
Here the desctructuring happens to the left of = and it allows you to extract properties from objects and assign them to variables.
You can also use object destructuring in function arguments, to access specific properties, like so:
const myFunc = ({ name }) => 'Hello ' + name;
This is equivalent to:
const myFunc = (person) => 'Hello ' + person.name;
And you could call this function with an object literal like this:
myFunc({ name: 'Jo' });

const func = (obj) => {
console.log(obj.a)
}
(obj) is basically saying func function takes obj as an argument.
You can also write it as such if you are passing only one argument;
const func = obj => {
console.log(obj.a)
}
What the parenthesis does basically giving you the ability to add multiple arguments. So like below;
const func = (obj1, obj2) => {
console.log(obj1.a, obj2.a)
}
func({a: "blue"})
Next func({a: "blue"})
Basically here you are calling func function with an object as an argument as a short hand.
So you can call it also like this
const argument = {a: "blue"}
func(argument)
Also you might see a lot of this kind of code
const func = (obj1, obj2) => console.log(obj1.a, obj2.a)
See there aren't anymore the curly braces around the console.log(). You can omit curly braces when you have only one line in the function. When you have multiple lines you will need to use curly braces to wrap the function body like so
func = (obj) => {
if (obj.a === "blue") {
return true
}
return false
}

Related

Weird behavior when using curly brackets in arrow function expressions with Fetch API [duplicate]

I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses?
For example:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
vs.
const handleBar = (e) => {
e.preventDefault();
dispatch('logout');
};
The parenthesis are returning a single value, the curly braces are executing multiple lines of code.
Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."
Here are some more examples that all do the same thing:
const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
"hello " + who + "!"
);
const d = (who) => (
"hello "
+ who
+ "!"
);
const e = (who) => {
return "hello " + who + "!";
};
You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:
const x = () => {} // Does nothing
const y = () => ({}) // returns an object
One can also use curly braces to prevent a single line arrow function from returning a value -- or to make it obvious to the next developer that a single line arrow function shouldn't, in this case, be returning anything.
For example:
const myFunc = (stuff) => { someArray.push(stuff) }
const otherFunc = (stuff) => someArray.push(stuff)
console.log(myFunc()) // --> logs undefined
console.log(otherFunc()) // --> logs result of push which is new array length
Parenthesis are used in an arrow function to return an object.
() => ({ name: 'YourName' }) // This will return an object
That is equivalent to
() => {
return { name : 'YourName' }
}
Actually in a briefcase when somebody uses braces in an arrow function declaration, it is equal to below:
const arrow = number => number + 1;
|||
const arrow = (number) => number + 1;
|||
const arrow = (number) => ( number + 1 );
|||
const arrow = (number) => { return number + 1 };
Parenthesis has an implicit return statement while curly braces you need an explicit return statement
If you use curly braces after the arrow to define the function body, you have to use the 'return' keyword to return something.
For example:
const myFun1 = (x) => {
return x;
}; // It will return x
const myFun2 = (x) => {
x;
}; // It will return nothing
If you use the parenthesis, you don't need to mention the 'return' keyword.
For example:
const myFunc1 = (x) => x; // It will return x
const myFunc2 = (x) => (x); // It will also return x
In your first example, the right-hand side of the arrow function shows a single expression that is enclosed by a grouping operator:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
A similar comparable case would be the following:
const foo = (params) => (<span><p>Content</p></span>);
A distinction, in the above cases using single expressions, is that the right-hand side is the returned value of the function.
On the other hand, if you use curly braces, JavaScript will understand that as a statement:
const foo = (params) => {} // this is not an object being returned, it's just an empty statement
Therefore, using statement is a good start for you to have code in it, multiple lines, and it will require the use of "return" if the function is intended to return value:
const foo = (params) => {
let value = 1;
return value;
}
In case you wanted to return an empty object in the shortest form:
const foo = (params) => ({})
See tests
To answer a duplicate post(question posted here), just for reference for others:
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body
Also note:
If you are returning an object literal as the result from a fat arrow function, then you must enclose the object in parentheses, e.g., myFunc = () => ({ data: "hello"}). You will receive an error if you omit the parentheses because the build tools will assume that the curly braces of the object literal are the start and end of a function body.
Every function has 2 aspects.
First of them is that each one, not just the arrow functions, has an execution context (a block scope) in which the variables are created and used.
In other words, inside the curly braces { ... } of the function, what is declared and assigned there, stays there and is not visible to the outside functions / or variables.
For example, when writing something as
let x = 100;
function doSomething() {
let x = 50;
console.log(x);
}
doSomething(); // 50
console.log(x); // 100
both values are displayed in console (instead of 'x from outside just being replaced by x from inside the function').
You see that despite of let not usually allowing other variable x to be declared again (with the same name x), in this case, because the second x is declared and initialized inside the { ... }, it does not alter the outside one, which also happens because after the function doSomething is called, the x from inside of it is created, assigned, printed in console and then destroyed (deleted from the memory). So that process happens every time we call that function by running doSomething() .
So this is the first aspect to take into consideration when understanding the functions: they execute then forget the values created by the code inside their curly braces.
Because of it, it's easier to understand their second aspect -- as functions cannot just work isolated from the others, they need to also send data to the others, so they have some 'reporting aspect' used to externalize some part of the results computed inside their curly braces, which is exactly why the return statement exists.
Return exists in each function, even in the console.log or alert(), even in doSomething(), but in these cases where we didn't explicitly set something for it, it is always 'return undefined'.
Therefore it isn't necessary to write it, but instead know that where you don't return something specific, the function itself will do it for you by returning undefined.
When you write (or use) a function meant just to execute something, it will also return undefined. Always.
You can check that thing with every function which (apparently) has no declared return:
let x = alert(100);
console.log(x); // undefined
let y = doSomething(); // console prints 50
console.log(y); // 50, then undefined --- 2 lines
console.log(alert('Hello')); // undefined
console.log(console.log('Okay')); // Okay , then undefined
Why is that?
Because alert() which is a method of global object window (in browser) (so it is actually window.alert() ) and also console.log() (which is the same with window.console.log() , too), execute something (printing in an alert box or in the console whatever is in between the () AND THEN return undefined).
Now, coming back to the arrow functions, they are not just some new way of notation for writing the functions but they also have some specific features.
First, if you only have a parameter between the () in an arrow function, you can write it without the parentheses.
Second, if inside the curly braces there's a single statement, you can omit as well the curly braces.
Third one, if the single statement is a return statement, you can omit the word return.
Somehow, using these we could transform many usual functions into arrow functions if needed:
function doSomething() {let x = 50; console.log(x);} // as function declaration
let doSomething = function() {let x = 50; console.log(x);}; // as function expression, which is an anonymous function assigned to the variable 'doSomething'
let doSomething = () => {let x = 50; console.log(x);}; // as arrow function
// let's transform it further
let doSomething = () => {console.log(50)}; //
// that is equivalent to ---- let doSomething = () => {console.log(50); return undefined};
// or even to ---- let doSomething = () => {return ( console.log(50) ) };
// because anyways, *console.log* has *return undefined* in it, as explained above
//which is the same as ---- let doSomething = () => {return console.log(50) };
// let's now apply the rules 2 and 3 from above, one by one:
let doSomething = () => return console.log(50);
let doSomething = () => console.log(50);
// Obviously, this just shows how we could rewrite many usual functions (functions declarations) into arrow functions
// we can do that safely if we don't have any **this** involved in the functions, of course
// also, from all lines of code above only one must remain, for example the last one.
// the last one, despite only having ---- console.log(50) --- as the execution aspect, it also ---- returns undefined ---- as well
// obviously ---- console.log( typeof doSomething ); // function
// while ---- console.log( typeof doSomething() ); // undefined
If an arrow function has 2 or more parameters, we cannot omit the parentheses around them:
function sum(a, b) {let total = a + b; return total}
let sum = function(a, b) {let total = a + b; return total};
// or
let sum = (a, b) => {let total = a + b; return total};
// or
let sum = (a, b) => {return a + b};
// or
let sum = (a, b) => a + b;
For simple operations as above, the fat arrow sign '=>' can be "read" as is transformed into, in other words, a and b is (are) transformed into a + b.
Opposite to that, there are also functions that validate some data (for example checking the data type, etc), like this one
let isNumber = x => typeof x === "number";
// or
let isNumber = (x) => {return (typeof x === "number")};
// obviously,
isNumber("Hello, John!"); // false
Those DON'T transform the data, and thus the arrow sign can be read something more as with the condition that, or similar.
In other words, a function like
let double = x => x * 2 // 'double' is a function that transforms x into x*2
is not the same as a checking one (mostly used in filters, sort, and other kind of validating functions, usually as callback function, etc)
let isArray = arr => Array.isArray(arr) // that last one already returns boolean by itself, no need to write return (Array.isArray() etc)
Last thing to know about return is that when you write code in multiple lines, the ASI (Automatic Semicolon Insertion) will insert a ';' after return if you mistakenly press enter after writing the return word, which will break the code, therefore instead of
return
a+b;
your code will behave as
return;
a+b;
so you better write the code with parentheses as here:
return (
a + b
);
as explained in MDN website here, too.

JavaScript. What is the difference between const addName = name => ({firstnmae : name}) and addName2 = (name) => { {firstname : name }}

i am currently learning JavaScript and I have trouble to understand the difference between those 2 functions. I thought they would be equal, but they act completly different.
Function 1 :
const function1 = name => ({username: name}) // this is returning a object, even tho there is no
// return
Function 2 : `
const function2 = (name) => { {username : name }} // this is returning nothing as expected
The second function is interesting. The second function doesn't create an object. It is a function with a block {} and a labeled statement. You can verify it by adding another property to the object literal and it will throw an error:
const function2 = (name) => { { username: name, firstname: name } }
It is interpreted like this and this is an invalid label:
const function2 = (name) => {
{
username: name,
firstname: name
}
}
The first is already explained in many SO questions. It is an arrow function which implicitly returns an object
When should I use return in es6 Arrow Functions?
ECMAScript 6 arrow function that returns an object
A one liner arrow function will return the resulting value.
for instance:
const add = (a, b) => a + b;
Whereas a multiline arrow function (or one defined using { & } will not return a value:
const add = (a, b) => {
a + b;
};
in order for the above to return a value you will need the return keyword:
const add = (a, b) => {
return a + b;
};
The Confusing Part
Your case is a bit confusing because you're dealing with an object literal:
{ username: name }
this syntax represents an "object". Objects in javascript are similar to associative arrays in other languages - that is, they are like arrays with strings as indices. A common example you'll see is something like:
const person = { name: 'Joseph', age: 33 }
// output the name:
console.log(person.name);
// output the age:
console.log(person.age);
So by wrapping your object literal in parens in your fist example you maintain it as a one line arrow function and your object literal is returned. The second example is really a multiline definition, which will again... have no return value.
The difference is that one will not have a return statement while the other one has a short form for the return statement that can be used in arrow function to return objects without exiplicity return statement.
// invalid syntax
const foo = () => {returns: 'object'}
// valid syntax
const foo = () => ({returns: 'object'})
// long form would look like
const foo = () => {
return {returns: 'object'}
}
The problem is that when you write foo = () => {returns: 'object'}, how does the engine know you want to return an object and not open a function body when it sees the {} curly brackets?
To let the engine know it is supposed to be an object that should be returned, you can wrap it in parents.
Both the functions are arrow functions.
Function 1 is an implicit return arrow function, so even though explicit return is not used the object {username: name} will be returned.
Function 1
const function1 = name => ({username: name})
When using implicit return arrow functions and also an object to be returned, then it should be wrapped in (). If we don't wrap it in either {...} or (...), then it'll be an invalid syntax
//Invalid syntax --> Will throw an error. Hence it should be wrapper with `()`
const function1 = name => {username: name}
But where as in Function 2 the function definition is wrapped in { ... }. Since there is no return statement in the function, nothing will be returned.
Function 2
const function2 = (name) => { {username : name }}

Why the () in this.state when using the current state as a parameter

I am reading about Reactjs, and one thing that I don't understand in the following syntax (taken from here)
this.setState(state => ({showWarning: !state.showWarning}))
is the () around the object. I understand that we use () for JSX, but the object {showWarning: !state.showWarning} is a JS object. Also I found this notation when using Redux as in
const mapStateToProps = state => ({...})
Why do we do that in React?
It's not specific to react. Arrow functions have a shorthand which allows you to skip the explicit return if you only have one statement. So a function like this:
const example = (val) => {
return 'foo'
}
can be shortened to this:
const example = (val) => 'foo';
But note that the way you do this is by leaving out the curly brackets of the function body. If you try to return an object, you're going to be sticking in curly brackets, so javascript thinks "ah, this is the function body", when really you want the brackets to mean an object literal. To clear up the ambiguity, you need to wrap the object in parentheses, so there's no possible way it could be interpreted as a function body.
const example2 = (val) => {
return { foo: 'bar' }
}
// can't become this:
//const example2 = (val) => {
// foo: 'bar' // this is not a key/value pair of an object! This is a labeled statement
//}
// so instead it becomes this:
const example2 = (val) => ({
foo: 'bar',
});
It's not exclusive to React.
When using Arrow functions, the expression to the right of the arrow is returned. But in the case of objects, the interpreter would interpret the braces as a multi-line function.
The parenthesis are there to denote that an object is to be returned as opposed to a function block declaration.
Quoted from the Syntax section of MDN:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})
{showWarning: !state.showWarning} is definitely a valid javascript object but not everywhere it will work as an object because {} is also used for code block. If you return any object implicitly from an arrow function without () javascript will consider it a code block rather than an object
() is just used to make engine think that we are try to use an expression here not a code block which is statement
This is ES6 syntax for running a function that returns an object.
Because Javascript functions can create a new block by wrapping curly braces around, there is some ambiguity as to whether you are about to create this new block or if you're trying to return an object using implict return. So by wrapping the object in () you tell JS that you are trying to return the object inside implictly.
It just keeps the code lean and is more modern so that's why people use it.
Examples:
const ex1 = () => 1 // returns 1, no ambiguity
const ex2 = () => {return 1} // same as above, but with explicit return
const ex3 = () => {a: 1} // error! thinks it's a new block, not an object
const ex4 = () => ({a: 1}) // returns {a: 1} because wrapped in ()

What is the difference between let foo = ({bar() {}}) and let foo = {bar() {}}?

I am trying to figure out what is the difference between;
let foo = ({ bar() {} });
and
let foo = { bar() {} };
I am not clear why code uses surrounding parentheses
const actions = ({
setCounter ({ commit }, obj) {
commit(MAIN_SET_COUNTER, obj)
}
})
What I tried;
I assumed as IFEE but I could not understand how does it work
I assumed as a shorthand of function declaration
The two first examples you show are semantically identical. In both cases, foo is assigned an object literal with a Method definition. The braces don't make a difference. As comments suggest, var foo = 1; is identical to var foo = (1);. In the third example, they are also not necessary. Note, that they also are not a mistake.
There are examples, where such braces make a difference, but they are not the ones you show. Some that come to mind:
Returning an object from an arrow function, shorthand version: let foo = () => ({});, differentiates from an empty code block.
Differentiating a code block from a stand-alone object, e.g. in the console: {} + []; vs ({}) + [];
IIFE, turning a function declaration statement into an expression: (function f(){})();, whereas function f(){}(); would result in an error.

function declare as a arrow function, later want to rebind with other object? [duplicate]

I've been experimenting with ES6 for a while now, and I've just come to a slight problem.
I really like using arrow functions, and whenever I can, I use them.
However, it would appear that you can't bind them!
Here is the function:
var f = () => console.log(this);
Here is the object I want to bind the function to:
var o = {'a': 42};
And here is how I would bind f to o:
var fBound = f.bind(o);
And then I can just call fBound:
fBound();
Which will output this (the o object):
{'a': 42}
Cool! Lovely! Except that it doesn't work. Instead of outputting the o object, it outputs the window object.
So I'd like to know: can you bind arrow functions? (And if so, how?)
I've tested the code above in Google Chrome 48 and Firefox 43, and the result is the same.
You cannot rebind this in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function.
From the ECMAScript 2015 Spec:
Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.
To be complete, you can re-bind arrow functions, you just can't change the meaning of this.
bind still has value for function arguments:
((a, b, c) => {
console.info(a, b, c) // 1, 2, 3
}).bind(undefined, 1, 2, 3)()
Try it here:
http://jsbin.com/motihanopi/edit?js,console
From the MDN:
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.
This means you cannot bind a value to this like you want.
description: Stijn de Witt
You cannot use bind to change the value of this inside an arrow function. However, you can create a new regular function that does the same thing as the old arrow function and then use call or bind to re-bind this as usual.
We use an eval call here to recreate the arrow function you pass in as a normal function and then use call to invoke it with a different this:
code: me
const func = v => console.log(this);
const obj = {value: 10};
function arrowBindOld(context, fn) {
let arrowFn;
(function() {
arrowFn = eval(fn.toString());
arrowFn();
}).call(context);
}
arrowBindOld(obj, func);
update
const f = v => console.log(this, v);
const o = {value: 10};
/* new */
function arrowBind(context, fn) {
const arrowFnString = fn.toString();
return (function() {
return eval(arrowFnString);
}).call(context);
}
const fBound = arrowBind(o, f);
fBound(10);
/* use prototype */
Function.prototype.arrowBind = function(context) {
const arrowFnString = this.toString();
return (function() {
return eval(arrowFnString);
}).call(context);
}
const fBoundProto = f.arrowBind(o);
fBoundProto(20);
For years, js developers struggled with context binding, asked why this changed in javascript, so much confusion over the years due to context binding and the difference between the meaning of this in javascript and this in most of the other OOP languages.
All this leads me to ask, why, why! why would you wan't to rebind an arrow function! Those where created specially to solve all this issues and confusions and avoid having to use bind or call or whatever other way to preserve the scope of the function.
TL;DR
No, you cannot rebind arrow functions.
Short, You CANNOT bind arrow functions, but read on:
Imagine you have this arrow function below which prints this on the console:
const myFunc = ()=> console.log(this);
So the quick fix for this would be using normal function, so just change it to:
function myFunc() {console.log(this)};
Then you can bind it to any lexical environment using bind or call or apply:
const bindedFunc = myFunc.bind(this);
and call it in case of bind.
bindedFunc();
There are also ways to using eval() to do it, which strongly not recommended.
Do ES6 Arrow Functions Really Solve “this” In JavaScript
The above link explains that arrow functions this doesn't change with bind, call, apply functions.
It is explained with a very nice example.
run this in node v4 to see the "expected" behavior,
this.test = "attached to the module";
var foo = { test: "attached to an object" };
foo.method = function(name, cb){
// bind the value of "this" on the method
// to try and force it to be what you want
this[name] = cb.bind(this); };
foo.method("bar", () => { console.log(this.test); });
foo.bar();
I think this is better solution
var f = (vm=this) => console.log(vm);
I asked the same question a couple days ago.
You cannot bind a value since the this is already bound.
Binding different this scope to ES6 => function operator
Maybe this example help to you :
let bob = {
_name: "Bob",
_friends: ["stackoverflow"],
printFriends:(x)=> {
x._friends.forEach((f)=> {
console.log(x._name + " knows " + f);
});
}
}
bob.printFriends = (bob.printFriends).bind(null,bob);
bob.printFriends();
Well it's meant to be impossible to bind an object to an arrow function, never say never; I figured a hack that just might work.
function arrowToRegularFn(callback) {
let _callback = callback
const stringifiedCallback = callback.toString()
const isArrowFn = !stringifiedCallback.trim().startsWith("function")
if (isArrowFn) {
const isParamsInParantheses = stringifiedCallback.trim().startsWith("(")
const [fnParams, ...fnBody] = stringifiedCallback.split("=>")
_callback = eval("(function" + (!isParamsInParantheses ? "(" : "") + fnParams + (!isParamsInParantheses ? ")" : "") + "{" + fnBody.join("=>") + "})")
}
return _callback
}
// test cases
// our object to bind
const quiver = { score: 0 }
let arrow, regular;
// test - 1
arrow = () => this.score++
regular = arrowToRegularFn(arrow).bind(quiver)
regular()
console.log(quiver.score) // 1
// test - 2
arrow = (x, y) => this.score = x + y
regular = arrowToRegularFn(arrow).bind(quiver)
regular(1, 2)
console.log(quiver.score) // 3
// test - 3
arrow = (x, y) => { this.score = x + y }
regular = arrowToRegularFn(arrow).bind(quiver)
regular(3, 4)
console.log(quiver.score) // 7
// test - 4
arrow = function(x, y) { this.score = x + y }
regular = arrowToRegularFn(arrow).bind(quiver)
regular(5, 6)
console.log(quiver.score) // 11
Normal bind:
tag.on("Initialized", function(tag) {
nodeValueChanged(tag, currentNode)
}.bind(currentNode))
Arrow function bind:
tag.on("Initialized", (tag => { nodeValueChanged(tag, currentNode) }).bind(currentNode))
Arrow functions always have this based on its closest non-arrow function irrespective of where it is called. If there is no non-arrow parent it always refers to the global object.
While you are calling the arrow function using call/bind/apply it's doesn't point to the object which you are passing.
var obj = {a:1};
var add=(b)=>{
return this.a + b;
// basically here this.a will be undefined as it's trying to find in one level up which is parents of this function that is window.
}
add.call(obj,2);
So that's why passing object doesn't work in arrow function.

Categories

Resources