Q1)
- SIMPLE DEFINITION; Its instructions that are formed in a coding format which provide us with a specific outcome.
This outcome is achieved by adding inputs to these instructions.
HOW TO CREATE A FUNCTION;
-
You need to start an expression with the keyword ‘function’
-
the keyword ‘function’ would then have an input which you would need to give (also called ‘Parameter’)
FOR EXAMPLE; function(a) - ‘a’ would be the input i.e. the Parameter
You can have more than 1 parameter or no parameter.
e.g. function(a,b) or function()
-
You would also need to give the function a name i.e. define the function
e.g. const ‘name’ = function(x)
- Then, must add a ‘body’ i.e. has the statements which are executed when the function is set.
e.g.
const ‘name’ = function(x) {
return x + x;
};
let x = 2
console.log(name(2));
// 4 = answer
The body i.e. the code inside the block brackets, would be ‘return x+x’.
Q2)
Scope basically means where variables are available for use. var
declarations are globally scoped or function/locally scoped.
The scope is global when a var
variable is declared (i.e. shown) outside a function. This means that any variable that is declared with var
outside a function block (i.e. outside of {} ) is available for use in the whole window.
var
is function scoped when it is declared (i.e. shown) within a function. This means that it is available and can be accessed only within that function.
Example;
var greeter = "hey hi";
function newFunction() {
var hello = "hello";
}
- Here,
greeter
is globally scoped because it exists outside a function while hello
is function scoped. So we cannot access the variable hello
outside of a function. So if we do this:
var tester = "hey hi";
function newFunction() {
var hello = "hello";
}
console.log(hello); // error: hello is not defined
We’ll get an error which is as a result of hello
not being available outside the function.
Let is block scoped
A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.
So a variable declared in a block with let
is only available for use within that block.
Example;
let greeting = "say Hi";
let times = 4;
if (times > 3) {
let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
We see that using hello
outside its block (the curly braces where it was defined) returns an error. This is because let
variables are block scoped .
Q3)
A pure function is a function which:
- Given the same input, will always return the same output.
- Produces no side effects.
So, console.log( double(5) );
is the same as console.log(10);
This is true because double()
is a pure function, but if double()
had side-effects, such as saving the value to disk or logging to the console, you couldn’t simply replace double(5)
with 10 without changing the meaning.