Currently I am doing this particular challenge : https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6
I am new to JS and all the new things I am learning are really interesting, but a bit overwhelming at the same time, especially all the different ways to make you code smaller and neater.
I have a doubt with this block of ES6 code, which was suggested to the students to use:
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
My question : can a function(or anything) exist inside an object if it is not assigned to a key/property? It certainly seems the case here. Also can I use this instead (getting a bit confusing remembering all the new stuff) :
const person = {
name: "Taylor",
sayHello : () => `Hello! My name is ${this.name}.`;
};
Any difference/ negatives to using this approach? it would be easier for me to remember, at least for the time being.
PS : One last question. In function expressions e.g. const x = () => {//body};
is x actually a variable/constant (depending upon the keyword ofc) that holds the function inside it, or is it the name of the function written in a more concise way?
Thanks
You are doing same things.The first with ES5, and second with ES6. The only difference is in the second example. âthisâ is undefined and you can change it with the current object - âpersonâ:
const person = {
name: "Taylor",
sayHello : () => `Hello! My name is ${person.name}.`;
};
ES6 is much better. The code is more elegance, readable and short.
Hiďź your first questionâs answer is yesďź but âcan a function(or anything) exist inside an object if it is not assigned to a key/propertyâ is error; as a object, object must has key & value;
Second question: cost => const ; x is variable/constant called âanonymous functionââ
have a good day.
âES6 is much better. The code is more elegance, readable and short.â
The alternative that I suggested (which you are referencing in your reply), it is ES6 also right? (arrow notation is ES6 as far as i know).
Or do you mean that code that I am finding confusing is much better than the alternative I suggested? I thought both are ES6.
But if you check the link that i posted, in the ES6 code that they suggest to use, there is no key/property for the function
The first object is a shorthand for:
const person = {
name: 'Taylor',
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
It does have a key (sayHello
). Itâs just hidden behind the syntactic sugar.
Note that the function here is not quite the same as the arrow function in your second object. Most notably in how they handle the binding for this
.
To expand on what @kevcomedia said, these two are not the same, and you canât use the arrow function one because it doesnât work the same way. Arrow functions have specific uses and this is not one of them.
You canât use arrow functions to write object methods that need to use the objectâs this
scope, because this
will not be the object itself, it will be the scope in which the object is defined. This may sound abstract, but itâs obvious when you run the code:
This works fine:
> const person = {
... name: "Taylor",
... sayHello() {
... return `Hello! My name is ${this.name}.`;
... },
... }
undefined
> person.sayHello()
'Hello! My name is Taylor.'
this
is the person
object, so this.name
is going to be âTaylorâ.
> const person = {
... name: "Taylor",
... sayHello : () => `Hello! My name is ${this.name}.`,
... }
undefined
> person.sayHello()
'Hello! My name is undefined.'
this
is outside the person
object, wherever person
gets called. this.name
doesnât exist there.
Guys I was watching this (excellent) series, and this reminded me of this question that I had. (Would recommend this series wholeheartedly)
link : xhttps://www.youtube.com/watch?v=GhbhD1HR5vk&list=PL0zVEGEvSaeHBZFy6Q8731rcwk0Gtuxub&index=1
@DanCouper @kevcomedia
like it shows in the first video, would this work, if I chose my arrow function approach to write the code?
> const person = {
... name: "Taylor",
... sayHello : () => `Hello! My name is ${this.name}.`,
... }
undefined
> person.sayHello.bind(person);
If so, that means the main difference between the two codes i shared, was that in my preferred code with the arrow function, the âthisâ keyword referred to the scope of where the function was CALLED, not where it was DEFINED (learned that from the video, it was a revelation). But if I chose to write the code the other way (the way that freecodecamp recommended, with the syntactic sugar), it somehow automatically applied the bind under the hood, or something similar.
So, am I getting this right?
PS : Do bear with me, this is getting a bit wordy I realise, but this is really helping me understand the concepts. Thanks for your time
Yep, youâre right with the called/defined. Arrow functions pass the this
scope straight through, they donât have one of their own. Normal functions do. That is why you get this behaviour. Again though, this is not the correct place to use arrow functions. They should not be used in this context: where they do not depend on this
, yes. Here, no, wrong tool.
The normal function doesnât do anything special, itâs just how functions work in JS, arrow functions are the exception.
And what youâre doing there, what bind
does, is wrap the arrow function in another function, thatâs how it works. But then what youâre doing is exactly the same as just defining the function as a normal function in the first place, except with extra unnecessary overhead: itâs pointless and convoluted.
1 Like
If you ever find yourself doubting just what your ES6 looks like in ES5, you can use the https://babeljs.io/ little code editor that shows the output on the right. The syntax youâre using is called method shorthand and it yields two possible results:
// For objects
const o = {
method() {
// method body
}
}
// yields...
var o = {
method: function() {
// method body
}
}
and
// For "classes"
class Foo {
// constructor and others
method() {
// method body
}
}
// yields tons and tons of code as the actual transpiled code
// but the core concept would be:
function Foo() {
// constructor and others
}
Foo.prototype.method = function() {
// method body
}
1 Like
I get it now. Not how âthisâ works in arrow functions (not fully at least), but the fact that there are instances where you avoid using them (like you said, situations where âthisâ keyword is involved, e.g. methods inside objects).
As for why, the basic gist of what I got is : because of something called âlexical scopingâ. Apparently, arrow functions do not have their own âthisâ, like you said @DanCouper, instead, when âthisâ is used inside arrow functions, it is the same as their PARENTâS this, i.e. it does not point to the scope of the function (which should be the object), but it points to the scope of the parent (here, parent = object, and parentâs scope = global).
This was a bit confusing, but Iâm glad I learned something. Thanks for all the help folks
1 Like