1. Explain the difference between Object.freeze() vs const
const and Object.freeze are two completely different things.
const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value to the binding.
const person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
person = animal; // ERROR "person" is read-only
Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.
let person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
Object.freeze(person);
person.name = "Lima"; //TypeError: Cannot assign to read only property 'name' of object
console.log(person);
2. What is Currying ?
Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant. So how do you deal with something you'd naturally express as, say, f(x,y)? Well, you take that as equivalent to f(x)(y) - f(x), call it g, is a function, and you apply that function to y. In other words, you only have functions that take one argument - but some of those functions return other functions (which ALSO take one argument).
3. When should I use Arrow Functions in ES6?
I'm now using the following rule of thumb for functions in ES6 and beyond:
Use function in the global scope and for Object.prototype properties.
Use class for object constructors.
Use => everywhere else.
4. Why use arrow functions almost everywhere?
Scope safety: When arrow functions are used consistently, everything is guaranteed to use the same thisObject as the root. If even a single standard function callback is mixed in with a bunch of arrow functions there's a chance the scope will become messed up.
Compactness: Arrow functions are easier to read and write. (This may seem opinionated so I will give a few examples further on).
Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.
5. What is the difference between Anonymous and Named functions?
var foo = function() { // anonymous function assigned to variable foo
// ..
};
var x = function bar(){ // named function (bar) assigned to variable x
// ..
};
foo(); // actual function execution
x();
0 Comments