promise
promise
It works seamlessly alongside HTML and CSS, complementing CSS in formatting HTML
elements while providing user interaction, a capability that CSS alone lacks.
What is Promise
Promise: an object that may or may not contain some value at some point in the future.
A promise is just some set of code that says you are waiting for some action to be taken and
then once that action is complete you will get some result. Sometimes, though, a promise
will be unfulfilled and you will not get the result you expect and instead will receive a
failure/error.
Parameters
The promise constructor takes only one argument which is a callback function
The callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything
went well then call resolve.
If desired operations do not go well then call reject.
promise.then(function () {
console.log('Success, You are a GEEK');
}).catch(function () {
console.log('Some error has occurred');
});
}
Example Two
promise.then(function (successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function (errorMessage) {
console.log(errorMessage);
});
Example Three
let promise = new Promise(function (resolve, reject) {
reject('Promise Rejected')
})
promise.then(function (successMessage) {
console.log(successMessage);
}, function (errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
Example Four
promise.then(function (successMessage) {
console.log(successMessage);
})
.catch(function (errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
To understand the closures, you need to know how the lexical scoping works first.
Lexical scoping
Lexical scoping defines the scope of a variable by the position of that variable declared in
the source code. For example:
Example
let name = 'John';
function greeting() {
let message = 'Hi';
console.log(message + ' '+ name);
}
In this example:
The variable name is a global variable. It is accessible from anywhere including within
the greeting() function.
The variable message is a local variable that is accessible only within
the greeting() function.
If you try to access the message variable outside the greeting() function, you will get an
error.
So the JavaScript engine uses the scope to manage the variable accessibility.
According to lexical scoping, the scopes can be nested and the inner function can access the
variables declared in its outer scope. For example:
Example
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message);
}
sayHi();
}
greeting();
The greeting() function creates a local variable named message and a function
named sayHi().
The sayHi() is the inner function that is available only within the body of
the greeting() function.
The sayHi() function can access the variables of the outer function such as
the message variable of the greeting() function.
Inside the greeting() function, we call the sayHi() function to display the message Hi
Example
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message);
}
return sayHi;
}
let hi = greeting();
hi(); // still can access the message variable
Now, instead of executing the sayHi() function inside the greeting() function,
the greeting() function returns the sayHi() function object.
Note that functions are the first-class citizens in JavaScript, therefore, you can return a
function from another function.
Outside of the greeting() function, we assigned the hi variable the value returned by
the greeting() function, which is a reference of the sayHi() function.
Then we executed the sayHi() function using the reference of that function: hi(). If you run
the code, you will get the same effect as the one above.
However, the interesting point here is that, normally, a local variable only exists during the
execution of the function.
It means that when the greeting() function has completed executing, the message variable is
no longer accessible.
In this case, we execute the hi() function that references the sayHi() function,
the message variable still exists.
The magic of this is closure. In other words, the sayHi() function is a closure.
A closure is a function that preserves the outer scope in its inner scope.
Example
function grandParent() {
var house = "GreenHouse";
function parent() {
return child;
}
return parent;
}
var P= grandParent();
//var H=P()
//H()
What is function hoisting in JavaScript?
JavaScript has a feature that allows function and variables to be hoisted – this is useful for
many developers. Hoisting is a JavaScript mechanism where variables and function
declarations are moved to the top of their scope before code execution.
Variable Hoisting
Variables are not hoisted as they cannot be used before their declaration. As shown by the
code below, the variable x was used before it was declared. At this point, the variable x does
not exist. Therefore, an error is thrown when you try to access the value of a variable that
doesn’t exist. The value returned by x is undefined, as illustrated by the output:
Example
console.log(x);
console.log(x);
Function hoisting
Hoisted functions can be used before their declaration. As you can see, the JavaScript
interpreter allows you to use the function before the point at which it was declared in the
source code. This is extremely useful as the function can be called before defining it. One
can then define the function anywhere in the program code. As can be seen from the code
below, the Func_Hoisted() function is called before it is declared. Function declarations can
be hoisted.
Example
Func_Hoisted();
function Func_Hoisted() {
console.log("This function is hoisted!");
}
// function expresssion
var b = function () {
console.log("This declaration makes function not hoisted!");
}
let & var
The var variables belong to the global scope when you define them outside a function. For
example:
var counter;
In this example, the counter is a global variable. It means that the counter variable is
accessible by any functions.
When you declare a variable inside a function using the var keyword, the scope of the
variable is local. For example:
function increase() {
var counter = 10;
}
// cannot access the counter variable
In this example, the counter variable is local to the increase() function. It cannot be
accessible outside of the function.
The following example displays four numbers from 0 to 4 inside the loop and the number 5
outside the loop.
for (var i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
Since this example uses the let keyword, the variable i is blocked scope. It means that the
variable i only exists and can be accessible inside the for loop block.
In JavaScript, a block is delimited by a pair of curly braces {} like in
the if...else and for statements:
if(condition) {
// inside a block
}
for(...) {
// inside a block
}
#2: Creating global properties
The global var variables are added to the global object as properties. The global object
is window on the web browser and global on Node.js:
var counter = 0;
console.log(window.counter); //
However, the let variables are not added to the global object:
let counter = 0;
console.log(window.counter);
#3: Redeclaration
The var keyword allows you to redeclare a variable without any issue:
var counter = 10;
var counter;
console.log(counter); // )
However, if you redeclare a variable with the let keyword, you will get an error:
let counter = 10;
let counter; //
What is a Function?
Functions are one of the building blocks of JavaScript. A function in JavaScript is just like a
procedure—a set of statements that perform a task or calculate a value. Still, to qualify as a
function, a procedure should take certain inputs and return some output where there is
some apparent relationship between the input and output. If you want to use a function,
you have to define it somewhere in the scope from which you want to call it.
Normal Function
To create a normal function, we use the "function" keyword followed by an assigned name.
Then we create an area where user input will determine outcomes. And the output will be
based on sets of instructions provided within brackets.
As we can see, this is an example of normal function. And this function accepts two values
and prints their sum:
//an addition function written in javascript
function addition(x, y) {
return x + y;
}
We can call this function by its name:
let answer = addition(9, 18);
console.log(answer); // Output: 27
Arrow Function
Arrow functions use the "fat arrow" syntax (=>). Arrow functions offer a more concise way of
constructing functions. Arrow functions were introduced with ES6, and they provide a
simpler way of writing functions.
The arrow function expression is an alternative to the normal function. With some
differences and limitations in usage:
Arrow functions don't have their bindings to arguments, this, or super, and we
cannot use them as methods(member).
Arrow functions cannot be used as constructors. Calling them with new throws a
TypeError. They also don't have access to the new.target keyword.
Arrow functions cannot use yield within their body and cannot be created as
generator functions.
The below function is similar to the previous function, written as an arrow function:
const addition = (x, y) => x + y; //written in javascript.
A key aspect of arrow functions is their concise and streamlined syntax. With parentheses
containing the arguments, a fat arrow (=>), then a function body, it's easy to see how simple
they can be. For this example, the function body contains just one expression returning a
sum of two parameters. As a result, both curly braces and the return keyword will not be
needed.
To call this function, you would use the same syntax as before:
let answer = addition(9, 18);
console.log(answer); // Output: 27
Having examined the syntax of both function types, We will now dive into the divergences
between them.
Differences Between Normal Function and Arrow Function
Aspect Arrow functions Normal functions
Anonymous Yes No
Syntax Shorter Longer
Handling multiple
Difficult Better
expressions
Refers to the object it belongs to
"this" keyword behavior Inherits from a broader scope.
("this").
Not suitable for use as a
Constructor functionality Suitable for use as a constructor.
constructor.
To learn about these differences in detail, read the following.
Arrow functions are anonymous:
Arrow functions are unnamed. It means that they do not have a name and cannot have
designated identifiers. Instead, they can be linked with variables or transferred as an
argument for another function.
The arrow function can also be assigned to a variable via the code given below:
const addition = (x, y) => x + y; //written in javascript
In the above example, the variable name (addition) is used to refer to the function.