In this blog I will cover the things I learnt in Chapter 3 of the book - Eloquent JavaScript.
Table Of Contents
-
Chapter 3
- Basic understanding of Functions
-
Scopes
- ARROW FUNCTIONS
- CALL STACK
- OPTIONAL ARGUMENTS
- CLOSURE
- RECURSION
Chapter-3
BASIC UNDERSTADNING OF FUNCTIONS
Functions play a crucial role in programming. Advantages :
- Larger programs can be structured using functions.
- Names can be associated with subprograms.
- Different subprograms to perform different to execute different parts of code.
- Reduced repetition.
To begin with, functions are declared using a function keyword.
They may or may not take a parameter depending on the type of calculations they are going to be used for. The body of a function starts and ends with parentheses. Some functions have a return statement, some don't.
const square = function(x) { //function declaration
return x * x;
};
console.log(square(12));
//Result β 144
const createVoice = function() {
console.log("Hahahahaha!");
};
createVoice();
//Result β Hahahahaha!
SCOPES
In JavaScript there are two types of scope:
- Local scope -> These are the variables declared within a JavaScript function. Local variables have Function scope i.e they can only be accessed from within the function.
function myFunction() {
var carName = "Volvo";
}
- Global scope -> These are the variables declared outside a function. A global variable has global scope i.e all scripts and functions on a web page can access it.
var carName = "Volvo";
function myFunction() {
}
Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.
JavaScript can have nested scope as well. Blocks and functions
can be created inside other blocks and functions, producing multiple degrees of locality. All functions have access to the global scope. Nested functions have access to the scope "above" them.
const hummus = function(factor) {
const ingredient = function(amount, unit, name) {
let ingredientAmount = amount * factor;
if (ingredientAmount > 1) {
unit += "s";
}
console.log(`${ingredientAmount} ${unit} ${name}`);
};
ingredient(1, "can", "chickpeas");
ingredient(0.25, "cup", "tahini");
ingredient(0.25, "cup", "lemon juice");
ingredient(1, "clove", "garlic");
ingredient(2, "tablespoon", "olive oil");
ingredient(0.5, "teaspoon", "cumin");
};
//The code inside the ingredient function can see the factor binding
from the outer function. But its local bindings, such as unit
or ingredientAmount, are not visible in the
outer function.
In JS, the order of function declaration and function call does not matter. Function declarations are not part of the regular top-to-bottom flow of control. They are conceptually moved to the top of their scope and can be used by all the code in that scope.
console.log("The future says:", future());
function future() {
return "You'll never have flying cars";
}
// result -> The future says you'll Never have flying cars
ARROW FUNCTIONS
Arrow functions are just another way of writing the JS functions. Instead of using the keyword function, we use arrow to represent a function followed by the body of function.
var squareNumber = (x) => {
return x * x ;
}
(squareNumber(5)); //function call
//result -> 25
** In simple words, this input(parameters) give this result (body).**
CALL STACK
When the computer encounters a function call, it goes to that function and implement it. After the implementation, the computer returns back to the line from where function was called and implement the next line of code.
The computer is supposed to store the context from where it had to continue executing again. The place where the computer stores this context is the call stack. Every time a function is called, the current context is stored on top of this stack. When a function returns, it removes the top context from the stack and uses that context to continue execution.
OPTIONAL ARGUMENTS
We can pass more number of arguments to a function having comparatively less parameters. JavaScript will ignore the extra arguments. In the opposite situation, the un-assigned parameters will be assigned a value of undefined.
function square(x) { return x * x; }
console.log(square(4, true, "hedgehog"));
//Result β 16
CLOSURE
A closure is a function having access to the parent scope, even after the parent function has closed.
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
In this example, the binding 'myFunc' is a reference to the instance of the function displayName that is created when makeFunc is called. The instance of displayName maintains a reference to its lexical environment ( lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.), within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use, and "Mozilla" is passed to alert.
For more, refer this link
RECURSION
Recursion simply refers to a situation when the function calls itself repeatedly unless some boundary condition is not encountered. In JavaScript implementations, itβs about three times slower than the looping version. Running through
a simple loop is generally cheaper than calling a function multiple times.
function Factorial(n) {
if (n === 0) {
return 1;
}
else {
return n * Factorial( n - 1 );
}
}
Thankyou for reading!π
All feedbacks are welcome πββοΈ
Connect with me on :
Top comments (0)