1. How can you create a function in JavaScript?
A function can be created in two ways;
- By creating a binding with the keyword const, where the value is a function with set parameters in brackets followed by the function body with statement(s) to be executed.
//Here we see the makeNoise function has no parameters.
const makeNoise = function() {
//The function requires no extra input, and once called will console.log Pling!
console.log("Pling!");
};
//When the function is called, brackets must be included regardless of parameters being present or not. .
makeNoise();
// â Pling!
- By beginning an expression with the keyword function, followed by the name of the function, parameters and the function body. This is a more succint approach and is called function declaration, which allow users to define the function later in the block as they get hoisted to the top of the scope.
function coolName () {
return("Cool stuff printed to console as a string, sweet.")
};
coolName();
//âCool stuff printed to console as a string, sweet.
2. What is the difference between var and let in terms of scope?
The keyword let (and const) create local bindings, which can only be referred to or called on within the âscopeâ or range of the block in the function they are declared/defined in. (Local scope/Block scope)
They keyword var has a global scope, meaning that if it is declared inside a function, it can be referenced throughout the entire function, not only itâs origin block, and if it is declared outside a function it can be referenced throughout the whole code environment.
let x = 10;
if (true) {
let y = 20;
var z = 30;
console.log(x+y+z);
}
console.log(x);
//returns 10 as it was defined with let outside the function and each scope can 'look out' to neighboring scopes.
console.log(y);
// returns undefined as y is defined with let, within the if block of the function, and so it's scope or range is limited to that block only.
console.log(z);
//returns 30, as although it is declared within a block, var has larger scope and allows it to be referenced throughout the function.
3. What is a pure function?
A pure function is a value producing function which does not invoke any side effects, nor does it rely on the side effects of other pieces of code.