Functional Programming Hoisting

What is hoisting ?

The hoisting is, the browser takes all the declarations such as a,b,c it takes out of the code before showing anything in the browser. It takes these declarations and puts them on top of the website or top of the file that we have up here so I can access them at any point inside the code that I have here.

var a ="First";var b ="Second";var c ="Third";console.log(a + " " + b + " " + c)

Example

ar a ="First";var b ="Second";var c ="Third";console.log(d)  -> undefined
var d = "Fourth";

Example

var a ="First";var b ="Second";var c ="Third";var d = "Fourth"
console.log(d) -> Fourth
var a ="First";var b ="Second";var c ="Third";
console.log(d) -> Fourthvar d ; declared variable d below the console.log

Example name function(expression) Hoisting

function example(){var a = 10return a;}console.log(example()) ->

Example 2 name function(expression) Hoisting

function example(){var a = 10return a;}
  1. we should use anonymous function because name function always gets hoisted in the browser
  2. Hoisting is takes a lot of space in the browser and if we have alotof codes hoisting like above it gets slower to browser.

Anonymous Function Example

var a = function (){var a = 20return a;}console.log(a())  -> 20

What is the difference between to name function and anonymous function ?

Anonymous function which we just assign a variable to function and call it.

var a = function (){var a = 20return a;

According to MDM

function catName(name) {console.log("My cat's name is " + name);}catName("Tiger");The result of the code above is: "My cat's name is Tiger"
catName("Chloe");function catName(name) {console.log("My cat's name is " + name);}The result of the code above is: "My cat's name is Chloe"
console.log(num);  Returns undefined, as only declaration was hoisted, no initialization has happened at this stagevar num;  declarationnum = 6;  initialization

Only y is hoisted

x = 1; Initialize x, and if not already declared, declare it — but no hoisting as there is no var in the statement.

console.log(x + " " + y);  '1 undefined'
var y = 2; Declare and Initialize y

Example 2

No hoisting, but since initialization also causes declaration (if not already declared), variables are available.

a = 'Cran'; Initialize ab = 'berry'; Initialize bconsole.log(a + "" + b);  'Cranberry'
const a = compute(9,5 );function compute(x, y){return x + y;}console.log(a)=> 14Example 2console.log(doSomething)doSomething();
function doSomething(){console.log('Declare Something') function declaration}console.log(something);something();

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux