JavaScript Flashcards

1
Q

What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?

A

The purpose of wrapping is to a namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the difference between .call and .apply?

A

The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between function scope and block scope in JavaScript?

A

In JavaScript, variables are scoped to either a function or a block. Function scope means that a variable declared inside a function is only accessible within that function and any nested functions. Block scope means that a variable declared inside a block (e.g. within a loop or an if statement) is only accessible within that block.

The main difference between function scope and block scope is the level at which the variable is accessible. In function scope, a variable is accessible throughout the entire function, including any nested functions. In block scope, a variable is only accessible within the block in which it is declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can you give an example of a curry function and why this syntax offers an advantage?

A

Sure, here’s an example of a curried function in JavaScript:

function add(x) {
return function(y) {
return x + y;
}
}

const add5 = add(5);
console.log(add5(3)); // Output: 8

In this example, the add function takes a single argument x, and returns a new function that takes a second argument y and returns the sum of x and y. The add5 constant is assigned the result of calling add with an argument of 5, which returns a new function that adds 5 to its argument. When we call add5 with an argument of 3, we get the expected result of 8.

One advantage of using a curried function is that it allows us to partially apply arguments and create new functions on the fly. In the example above, we create a new function add5 by partially applying the add function with an argument of 5. We can then reuse this function multiple times with different arguments, without having to redefine the function each time. This can be especially useful when working with functions that take multiple arguments, as it allows us to break them down into smaller, more manageable functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly