BlogPost_205
I’m just gonna do the questions.
- Can you offer a use case for the new arrow
=>
function syntax?
There is a great article about this here https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6
The gist of it is that you should use function(){} when in the global scope and using Object.prototype properties, Class when using constructors, and arrow functions everywhere else. The arrow bind the this keyword differently than function() functions. Ontop of that, there was a good point made about how when the arrow function is used in this way, it is easier for another developer to identify the use cases for function().
2. Explain the differences on the usage of foo
between function foo() {}
and const foo = function() {}
This seems obvious to me now, but I will leave it here.
3.What advantage is there for using the arrow syntax for a method in a constructor?
let obj = {
myVar: 'foo',
myFunc: function() {
console.log(this.myVar)
setTimeout(function() {
console.log(this.myVar)
}, 1000)
}
}obj.myFunc() // foo ... then... undefined
Constructors use the keyword “this” frequently to build their properties of an object. When using this with a regular function, the scope of “this” can get a little foggy. in the first example,
myFunc: function() {
console.log(this.myVar)
foo is properly logged, while in the second example, you get undefined, because the scope of this is now attatched to the setTimeout function.
While this isn’t a constructor example, it makes sense why you would want to make sure you don’t lose your scope of “this” while building a new object in a constructor.
3. Can you give an example for destructuring an object or an array?
Create an array
let myArr = [10,20]
Then you destructure it
const [a,b] = myArr
console.log(b)
// logs 20
4. Explain Closure in your own words. How do you think you can use it? Don’t forget to read more blogs and videos about this subject.
I looked into this, and it seems a little over my head for now. I should put some research into it later, as during my two weeks off school, I will be reading through and answering these all over again.