JavaScript from Start and Scratch!(No Long Theories)

sakshi jain
30 min readAug 29, 2020

Hey! I am too a big fan of JS . I do tried a lot of ways to learn JS though the things got into head but did not got its permanent storage!

Then I tried to take over the power of Learn and Write , where whatever I learnt till now or is learning about JS right now , I will pen it down according to the way I grasped it.

I want to thank Sir Hitesh Choudhary (LCO ) for his amazing sessions on Modern JS .

I hope this article can somewhere contribute here and there in the process of your learnings!

Let us learn like two friends are sitting over a coffee and gossiping about JS:-)

JS Engines:~

JS is just like C++,Java and Python . It needs some tools to convert this JS code into machine understandable code. so JS comes up with the compiler that can convert your JS code into executable code.

It is an actual myth that JS runs in browser , but there exists a compiler as well that does a lot of intermediate work before placing the code in an executable format in browser just like any other programming language. V8 and SpiderMonkey are one of the JS Engines. NodeJS is one such implementaion of JSEngines that converts StandAlone JS code. There is no need to attach JS into HTML and hit reload each time..

Which Version of JS to Use?

The JavaScript world can be a confusing world. We talk about ECMAScript, JavaScript, ES5, and ES2015 (which is the same as ES6 by the way).

Things were pretty same , changing colors and some DOM stuff till ES5 . tables got turned when ES6 comes into picture.

ECMAScript is a language specification, and Javascript implements this specification. Now there isn’t really a naming convention when it comes to ECMAScript versions. So ES10 is also called ECMAScript2019 and ES2019.

Furthermore, the last really big change to the language was with ES6 which came out in 2015 so it is sometimes also referred to as ES2015

Variables and Datatypes :~

In JS : var,let and const reserves memory space, where every keyword has its own uniqueness and space.

JavaScript provides set of data types to hold data such as String values, Decimal values and Boolean values. The data types depend on the values which are hold by the variable.

Number , string and Boolean are the fundamental data types . There are some other data types such as undefined.

JavaScript variables are containers which hold some values or information. JavaScript variables are case-sensitive. Variables are declared by using “var” keyword.

Note : The typeof operator returns a string indicating the type of the unevaluated operand.

Coercion and Falsy Values in JS:

These gibberish words got much hype more than they deserve . But they are clean and clear to understand.

Some of the falsy values are :

  • false
  • 0 (zero)
  • “” (empty string)
  • null
  • undefined
  • NaN (Not A Number)
  1. Undefined: var user; user is an undefined variable where you just tried to use a user but forgot to fill any value.
  2. Null : null means empty or non-existent value which must be assigned.

Same we can do with other falsy values , they does not give anything as output when defined in any condition or if-else.

Until now we git that fact : null and undefined are poles apart from each other . But they do share some similarities in between them. Thus, it makes sense that null does not strictly equal undefined.(null !== undefined)

Surprise : null loosely equals undefined.(null == undefined)

How ? What!? In JavaScript, a double equals tests for loose equality and preforms type coercion. This means we compare two values after converting them to a common type. I know JS assumes too much :-(

JS is assuming two equals sign , it brings them to common data type i.e. they both are falsy values. For strict checking use === sign.

Also With default parameters, undefined will use the default while null does not.

Functions in JS

Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition. Simply , a block of code separated out for reuse.

function showMessage()

{

alert( ‘Hello everyone!’ );

}

Now , in midst of basic Functions theory that you might have done tons and tons of time in other programming languages , JS allows to store function inside a variable and use it . This does not change anything in the working of Functions. It is just a mere part of Functional Programming in JS which is in trend now.

Context in JS:~(BEHIND THE SCENES OF JS)

If you are or want to be a JavaScript developer, then you must know how the JavaScript programs are executed internally.

How the code in JS behaves? we always somewhere thinks about it and how things is executing.

Result is code in NodeJS is different from code in browser.

For example:

You must be wondering, its output to be an error !? Like function is called before it is declared and defined . It is wrong..

Yes, it is , but it is not in case of Js . It prints the mesaage ‘hello’. So how come JS knew that there is a function existing named sayHello() at the time of calling. Because top to bottom approach is followed as a thumb rule.

This all is a result of Global Context of JS . A global object in JS do all wonders. JS has a bigger context in which everything resides and that is window in browser.

In browser : for say there is var name =”abc” and it stands true when we say (name===window.name), because global context is existing in browser. But if we try to run the same code in nodejs engine , it shows up an error that window is not defined , because global context is missing in NODEJS. Global context here differs a little bit (browser vs nodejs).

But still there is always a global context , not called window here. But the context do exists in NODEJS.

The work of it is , whenever a function or anything is registered in nodejs , it is wrapped up and put it inside global context.

That is why above function sayHello() does not give error because of the global context!

Contexts are called with different names in different engines . like in node, we don’t call it with name window . but in browser it is called with name window!

Code Hoisting in JS :~

Context….? It answers weirdness of JS and helps in an optimized debugging.

There are two types of contexts available to us : Global and Executing Context.

As soon as the jobs of these execution context completes, they go over!

This Execution Context is not about just one or two lines of code you want to execute , it comes up with whole a lot of features like Variable Object , Scope and this keyword(JS favorite:-))

Execution Context has two rules to follow:-

  1. Function Declarations are scanned and made available : We saw how function is called before declaring and definitions , because of global context , because the entire code is scanned and ,made function available to us after calling.
  2. Variable Declarations are scanned and made undefined : Declaring a whole lot of variables and we not just use all variables at same time. You sometimes want to fill variables at later time. And thus when we console , it gives output Undefined.

We know global context makes this code work . But console gives the error: that bigTipper is not a function!?

To understand it , remember the two thumb rules : Function declarations are scanned and made available but variable declarations scanned are made undefined and so is var bigTipper here , behind the scenes , it is undefined and is sent wrapped up to the function bigTipper() using global context.

This is where Code Hoisting comes into picture :

And solution is :

To prove Rule number 2 :

This gives us an output : undefined according to rule no 2. Remember undefined and error are two different things. Just.

This means global context has not even collected the information and you are just trying to use it! Why? This code gives answer to all of your confusions.

Literal Definition Of Hoisting: -

when JavaScript compiles all of your code, all variable declarations using var are lifted to the top of their functional or to the top of their global scope regardless of where the actual declaration has been made. This is what we mean by “hoisting” . ‘Hoisting’ doesn’t literally happen in your code, but is rather something JavaScript compiler reads through your code.

When we think of “hoisting” we can visually imagine that whatever is being hoisted is being moved to the top, but in theory, no code is literally moving around.

Functions declarations are also hoisted, but these go to the very top, so will sit above all of the variable declarations. Just like SJ sayName()

A key thing to note is that the only thing that gets moved to the top is the variable declarations , not the actual value given to the variable.

The concept of hoisting is simply a process of the JavaScript compiler reading variables , functions , first in order to create space in memory for them.

Scope Chain in JS:~

Consider a Scenario:

Blue guy at very center got candy , he can eat its own candy. But in some case if he does not have his own candy , he can ask orange guy for candy and if orange guy does not have , he can ask from purple guy as well.

But according to the society , But if blue guy got his candy , he can eat his own. But if orange guy as his own candy , he can eat but if he does not have he cannot ask from blue guy but can ask from purple guy.

And Similarly purple guy cannot ask for candy from any orange or blue guy.

Now notice here , blue guy (line no 114) can ask for candy(name variable) from big guy(line no 110) , who will give him same candy(name) that he is having. Simple!

Now both guys got their own separate candies (name) and will eat their own candies only.

In world of JS We think { } is a scope or an empty scope but truly it is not considered as scope. It is but not truly.

The only true scope in JS is function abc () { ……} .

I hope Scope Chaining is as easy as good!

This in JS:~ ( JS LOVES IT)

Objects are the basic building blocks in JavaScript. There’s one special object available in JavaScript, the this object. You can see the value of this at every line of JavaScript execution. The value of this is decided based on how the code is being executed.

console.log(this) gives access to global context! How?

In NodeJs it gives us an output of empty scope. But in the browser it gives us an access to global context which is a window object.

console.log(this) inside a function gives a lot of description about Object. But in browser it gives same window object always.

The window object is the global object in the case of the browser. And in a NodeJS environment, a special object called global will be the value of this.

Arrays IN JS:~

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.

Var fruits = new Array(‘Mango’,’Apple’,’Orange’);

var array = [1, 2, 3]

Arrays can be anything — numbers, strings, functions even other arrays and within the arrays you can mix different type of data freely.

var number = [1, 2, 3, 4, 5]
var strings = ['name', 'place', 'food' ]
var functions = [ function x(){...}, finction y(){...} ]
var mix = [ 12, 'niceplace', function xy(){...} ]

Call Back and Arrow Functions in JS:~

These are 3 ways to write any simple code. First two ones are known . But the last one with an arrow )=> is called as arrow function and it makes our life much easier. “return keyword is requires with arrow function”

Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope.

Arrow functions are anonymous and change the way this binds in functions.

Arrow functions make our code more concise, and simplify function scoping and the this keyword. They are one-line mini functions.

Similarly we have something as CallBacks!

function print(callback) {  
callback();
}

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

A callback is nothing but a simple function which does not have a name .

JavaScript runs code sequentially in top-down order. But sometimes there are some cases that code do not run sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

const message = function() {  
console.log("This message is shown after 3 seconds");
}

setTimeout(message, 3000);

A built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds).

message function is being called after something happened (after 3 seconds passed), but not before. So the message function is an example of a callback function.

We can also write the same callback function as an ES6 arrow function.

If you do not use return keyword , remove {} braces as well . And this makes it a one line code function.

Fill, Filter , Slice and Splice :JS Array Jargon's:

These notes will help you understand these helpful methods!

Objects in JS:~

Objects are nothing but collection of different types of data. An unordered collection of data.

var user =

{

first :’sakshi’,

last :’jain’,

role:’WebDev’,

login:32

googleSignedIn :true

}

console.log(user.first)

console.log(user[“last”]

Objects and Methods:

ForEach vs ForIN Loop World:~

You’ve probably used a for loop before. It’s the most basic of loops in JavaScript and is quite versatile.

forEach is an Array method that we can use to execute a function on each element in an array. It can only be used on Arrays, Maps, and Sets.

When using forEach, we simply have to specify a callback function. This callback will be executed on each element in the array.

const arr = ['cat', 'dog', 'fish'];arr.forEach(element => {
console.log(element);
});

But

for...in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.

const obj = {
a: 1,
b: 2,
c: 3,
d: 4
}

for (let elem in obj) {
console.log( obj[elem] ) // accessing value from object
}

Here comes This Again:-(

This do creates confusion that what it is actually containing : Window object or the object user has defined! … Please answer?

Answer is : For all regular function calls , this points to window object.

So console.log(this) is getting output equal to entire object a reference back. because this holds here entirety of object . In browser this points and outputs window object always.

user.getCourseCount() does not look like regular function call , regular function is like sayHello(). Here user.getCourseCount() is called throug an object.

First we get entire object and then we get hello and then we get global object again! But in browser : line 201 gives window object and others are same .

This will give you back an object if that was an object call not regular function call.

DOM , Its Properties and Event Listeners:~

Understand the concepts behind it via this medium article

New Keyword in JS:

__proto__ has a world of properties inside it. They all are part of functional objects , (f) keyword is standing above them.

To create object every time, we are assigning all properties ourselves!

We need to create a prototype , for every type of object created every time .

Now this is a functional way of defining objects! Other than what we discussed above.

New keyword is tiny tiny ..

It is responsible for using the syntax we discussed above. Secondly , it invokes constructor and creating a unique instance every time . It also takes care of this keyword. Here this points to window object at the output of undefined with no use of new keyword but with the use of new keyword , this shifts the pointing from global object to inside object user.

What the heck is __proto__:~

__proto__ is an object in every class instance that points to the prototype it was created from.

__proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new.

From above examples ,we now the user object has an access of __proto__

So without touching the actual prototype , we are actually injecting some of new properties into the User object with the new keyword responsiblity.

If whole code is loaded onto browser __proto__ got this property getfname().

Object Chain in JS:~

If we twitch any of the thing in User Object for say , fname as fnamee then the output will get fname as undefined.

__proto__ has some has OwnProperty() function inbuilty. We can use it solve this potential issue we discussed.

eg : Before calling sakshi.getfname() we can check if(sakshi.hasOwnProperty(‘fname’) .. callup sakshi.getfname().And this makes the code look more crisp and robust with no blunt maybes and undefined. So these properties in __proto__ exist for your effextiveness and prevention of clueless errors.

Additional DOCS about Objects:

You can create objects using Objects.assign() or Object.create().

And in __proto__ on browser you get a lot of other methods inside it to use.

Self Executing Anonymous Function (IIFE):~

An Immediately Invoked Function Expression is a good way at protecting the scope of your function and the variables within it.

Self executing means no one should call it and anonymous means , it should not have its name.

Generally we execute functions like:

But another way were function calls itself immediately after its declaration .it does not wait for anybody to call it.

IIFEE

But they have a very limited scope of working!!!!!!!

Lexical scoping JS:~

It is a classical way of writing JS

Once the context is over , no one knows value of firstName and last line will show error. But closures has an answer for it!

Closures ( JS Hard Mountain To Climb):~

Coding in JavaScript without an understanding of closures is like trying to speak English without an understanding of grammar rules — you might be able to get your ideas across, but probably a bit awkwardly.

Closures are in JavaScript is majorly used for object data privacy, in event handlers and callback functions.

A closure is an amazing combination of function bundled together with references into its lexical environment. A closure gives you access to an outer function’s scope from an inner function.

To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

This is a every simple JS program , where initially execution context of init() loads in browser , on top of which execution context of sayName() gets loaded. Once the execution context of sayName() get its work done , it woos off and then init() does it work and get woo off as well.

So what is in behind the scene : init() gets mounted up on browser for its execution , then on top of it sayName() gets mounted up. but sayName() does not go fully away because of its reference passed here. thats why init() does not go fully away early.

Total removal of init() and sayName() is not possible because of reference.

To execute this function:

init() is executing , but its execution context is still not over and thus not making sayName() get its execution path and desired result as well.

so the new thing to understand is this value is technically sayName() behind the scenes and when you do value(); it will return the execution context of sayName() and print the desired output.

Another example :-)

This is all about closures ! I hope now this concept has become a piece of cake for you!

Bind() is borrowing a method!?WhAT…:-~

we all know this stuff now , where this points to current global context , pointing all values inside function. Some properties are attached to entire oject and some are inside object __proto__ like bind , call or ToString()

What if we create another object john and try to access the function defibed inside object sam. Can we do that ?

Error:

FOR such cases , we need bind() which binds the object and gives you a reference.

sam.getInfo.bind(john)()…bind always returns reference back and run that reference.

sam.getInfo.bind(john)() wants getInfo() method of sam object to start pointing to john object .

__proto__ brings a lot of methods like call() as well.. call () does not return the reference back, so need of closures existshere.

Like : sam.getInfo.call(john)… all similar to bind()

Scope problem in JS:~

It is somewhere a big issue in JS.

console.log(name);

var name = ‘priya’;

output :undefined

console.log(name);

let name = ’priya’;

output : error

if(true)

{ var name =’jain’;

console.log(name);

}

output:jain

if(true)

{
var name =’jain’;

}

console.log(‘name’);

output : jain

// this should not happen , output should not be printed once you are out of scope

Solution : Replace var with let

if(true)

{

let lname = ‘jain’

}

console.log(lname);

output :error (let does not allow you to go out of scope)

Double Shots in JS:~

const google = ‘google’;

const fb = null;

if(fb)

//when null is placed here , it is not considered as false but falsy values.

//remember we dicussed earlier coercion and falsy values.

//but sometimes we need false values not falsy values.

{

console.log(‘I execute block’);

}

In that case we either do if(!fb) but this thing reverses logic or we come up with something called double shots.

!! known as doube shots is good for reliability and performance

Maps in JS:~

It works almost like objects but truely are not objects.

Map is list of items where each item is stored as a key,value pair. Sounds familiar to Object?

Unlike object, map is used to store the key and value of any type. It can be number, String, Boolean… Map can use both Objects and primitive types as keys. The key,value pairs in Map maintains the insertion order, whereas Object don’t.

Remember Maps are iterable by-default, whereas Objects are not. Which you will see in below example:

As maps are iterable by default!!

Surprise is even if you make your iterable forEach to traverse key values, it will output value pair only. Maybe Modern JS assumes that , value is the only thing for which key is used for further access and manipulations.

And this is how map exists in JS with other methods like map.delete(‘key’) and others as well.

How to Pick Data — Destructuring of Data?

“Whatever data type is on the right hand side , should have a kind of similar data type left hand side”

Confusing? Yes , will get it in a while. Just sit in.

Seeing this example , we are very much familiar with this code and how you can access values out of it.

The new thing we can use as well is:

This is a short hand notation. But not common to work with destructuring of data on arrays.

People generally work on destructuring of data on objects.

Both looks same but are not same actually. Here the code above explained as some error, did you find it?

Remember destructuring needs data types of both left and right hand side similiar but also these names declared in var should also match with names declared in object .

for example : const {….} has coursecount but object details has different name for it i.e. courseTaken . And these two names do not match .

And we got the error undefined , because values did not match. Thus keep that check while coding and destructuring. In case of arrays it is not hard case requirement to match the names even but in case of objects it is important to keep the names same.

Spread and Rest Operators :~

Anything followed by three dots … may be

…args

…1

…sakshi

is called Spread operator as well as this is your Rest Operator as well.

What ? Whats the difference then??

Depending on cases and scenariois , they either change into Rest Operator or Spread Operator.

Use Cases:

Consider this example:~

max() method can take as many list of values as it can to search out maximum value in behind the scenes of JS.

See this example , here using Object.assign() it is giving us a mix up of all object values but the most important thumb rule is first argument in Object.assign() must be an empty object {}

After seeing this example , the first challenge we got is :

When your function expects individual values but your values comes up as a pack or bunch(array,objects). In that case :

using … operator (spread or rest that we will decide) is the best option.

The way we used three dots …here is called as spread operator! Spread operator takes the group and spreads it into multiple values.

The spread operator “spreads” the values in an iterable (arrays, strings) across zero or more arguments or elements.

With this now have an easier way to combine two arrays: the spread operator.

Now comes the entry of Rest Operator:

Rest Operator is used when we have a function that need multiples arguments or a function that needs to pass any number of arguments. The rest parameter gives us an easier and cleaner way of working with an indefinite number of parameters.

args in Rest Operator convert individual values into an array!

Yes, both Spread and Rest are almost Like reverse of each other.

Another variation we could have in it is:

We can have first two values to be treated as individual arguments and rest to be as args ! How ? Lets check

The first value is giving multiplication of 2 arguments where as rest are treated as args to produce sum of them. A beautiful Modern ES6 Approach.

JAVASCRIPT sort() needs consistency!?

JavaScript has a sort() method that you can use on arrays, but the results are almost always weird and don’t return what you initially expect.

If you have the following [9, 8, 12, 1, 33, 21] array, using sort() on it will return [1, 12, 21, 33, 8, 9].

Wait what? It is not supposed to do this!

Because JS sort() method converts each item in the array into strings and constructs the sequence by comparing each array item based on the UTF-16 code values when there is no callback specified.

Oh god ! What UTF is gonna do with such simple sort() method?

When sort()is used, it automatically calls the String() cast method on every array element by default and turns everything into a string. It’s easier to sort when things are the same type.

That is why you are essentially sorting against whatever order the characters are in . That is why 33 came before 8 in the sorted array above. As the character 3 appears before 8

With this explanation Javascript sort() method got misunderstood actually!

Notice ,sort() also takes a callback function that allows you to decide how things will appear. The call back is more a comparison function that helps your JavaScript code determine the correct order of things in the manner you want.

So when you’re working with numbers and using the callback function, the String() cast is not placed on the array items. This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback.

This is the most awaited call back function when used with sort() does not cast everything into its equivalent string pattern.

So when you want to sort an array of numbers, you can do so by doing something like this: arrayNameHere.sort(sortNumbers);.

Classes and Module Exports World:~

Simply , Classes are almost like a blueprint , where you defined how things should look like. And then we can just create and use objects from them.

Classes alone does not work, we need to create objects to make them work. And classes also comes up with a method “constructor” . If you do not create this in your class, class by default creates its “empty constructor”.

Here , this.name is the property of class User where name is the argument or parameter passed into the constructor.

It is not necessary to declare things you passed into the constructor generally. You can straight away declare using constructor.

Either you can instantiate object in the same pace where class is created or you can separate class from other things as well using

module.exports = User;

Using this at the end of class , you can access User class anywhere from any file.

This is all about classes in JS. Pretty Easy.

Getters and Setters: JS Props:~

Getters is something which helps you to grab some of the information from the class which is private. So that every one can have access to the class via objects directly.

Where setters can be used to manipulate the values of objects and variables we declared. Also it is not compulsary to declare getters and setters with a prefix of get or set. Though it becomes a mindset to do like this.

In getters we just return the variable , we don’t expect any parameters. And setters we expect parameters to set whch is privae in class.

So # does the work .

Like seeing the bove class if we modify : #courseList =[] , then you have to refer throughout the class with a prefix of #

What change does it give to us ? So now when you access it through a method : rock.getCourseList() , it is able to get that but rock.courseList gives an output undefined.

It looks just like a normal property but behind the scenes we can have extra logic (or checks) to be run just before or after the assignment.

Inheritance in JS , Okay!

JavaScript does not have classes like other languages. It uses the concept of prototypes and prototype chaining for inheritance.

With the continuation of User class we add:

We got all info but name and email is undefined , which needs a fix , by adding constructor in derived class subAdmin()

But the issue we got above is not so small. Where the heck is privacy now? Any object from login() should be able to access certain methods , for say i don’t want one method may be login() defined in User class to be shared.

Then just put a keyword static before the function name , as static refers to private property which is not shareable.

But if I define login() in both User and subAdmin() class without any static keyword , now subadmin class has created its object jerry where jerry.login() is called , whose login jerry is able to access? Think……..

If for some reason there is a method in User class and you want to overwrite method , you are absolutely allowed to do that and JS is smart enough, if you are using the same name but writing something different , then you want to invoke the method of that class whose object is created . That Simple.

Event Loop — JS is looping?

Being a user , how the web page should ideally be loaded? The most common answer is very instantly as much as it can. The core default functionality of JS is more at front end.

See this visual graphic where there is a queue full of messages , messages consisting of your console.log or variable declarations or function calls which are either passed onto stack or heap for further execution.

But the question who the man is behind maintaining this queue and sending data all forward? It is event loop (the loop which looks for an event ..dah) for sure.

This is your event loop. Yes as simple as this . It is responsible for as soon as the message comes , process it instant soon.

It is the secret behind JavaScript’s asynchronous programming. Remember JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading.

But what is this Synchronous/Asynchronous?

const uno = ()=>

{

console.log(“one”);

}

const dos =async ()=>

{

setTimeout(()=>

{

console.log(‘wohoo’);

},3000);

console.log(‘I am two’);

}

const tres = ()=>

{

console.log(“three”);

}

uno();

tres();

dos();

Output:

Here Big picture of “wohho” loaded after 3 seconds , until that everything gets loaded. That is what JS loves.

This is what synchronous do , it allows anyone to execute in the house if one thing is taking time to load, it wont block others . Taking any order of calling functions!

This is actually a classic way of how JS executes. Here nobody is blocking code or resource , called as no-blocking I/O till “wohho” guy executes.

And asynchronous is opposite of this completely. On a more real terms , if this “wohoo” guy is some information to be loaded from database , how could you load some other things , if in case they could be a follow up after loaded , that is where asynchronous term takes place , more into the back end.

So we need to learn a way for that.

JavaScript is Promising something?

Some weird terms ? Promise, Reject ,Resolve , Async and Await!

This must be felt like simple code with three basic functions where dos() has some timeout() function associated to it. And when you would call them , comsole gives the output of all.

But there is some inner problem associated with it , the setTimeout() was used to stop the making of any other function call when dos() is running , may be to get something from database or to fetch any API

Don’t you think, we can write this code much better.

Now the output got some turn into it. You can see dos() is not able to print its output and hence we get undefined in the variable holding it for sure.

Why? Can we do something to fix it?

If we change something in function dos()

The output we get is an undefined promise which is yet to be fulfilled.

What the heck is this, with just one word async??

So a lot of times we either make a web request or API request , these requests to database or AWS or something cannot just happen instantly . A local storage or a simple variable cannot be used to fetch in or get response of your request.

We of course need something in an asynchronous manner . And promise is helping us to promise us either it will fulfill to get something from our web request or it won’t. Two binary states either 0 or 1.

So Promise is an event that might be get fulfilled in future or not . But it will always return back you the response of its successful completion or not.

Add async key word before the function to start handling it in more asynchronous way. But this wont do anything. We also need to handle the calling of it well.

While handling the calling of it , we need to make the function holding the calling of it asynchronous as well with an addition of await keyword at the function call of dos()

await will warn everyone to do not interfere anything in between the execution of this function until it is fully completed.

And yeah we got our output ,where when you will run it yourself , output displayed by dos() will show after 3s followed by tres()

Resolve and Reject are two states of promises , where we discussed resolve to handle something with full responsibility but reject is used with full precautions , because it raises an error ,and if not handled well , will crash the system/program.

Want to Handle API in JS ?

With core JS?

To brush up , Promises owns two states : Resolve and Reject.

Any promise that is going to handle fulfill , a list of then methods can be chained on. And if the promise is rejected , we need to handle it with error handling methods.

Chuck Norris — API ?

We have to work on it on browser or some window console as Nodejs environment wont be able to help us here , as we need to request something from web and get in back some response as well.

Fetch is used to request any API url (chuck Norris joke cdn) with a follow up of then to get back response as well. But this when console is nit very good undertstand-able code.

Here we will get some response in JSON format. But…

And finally to get the particular joke only , which is our goal :

So console all of them in browser console , and check the difference and evolution between them by yourself!

sakshi jain

Coding empowers magic to my thought with a wing of programming!