Statement:
Most JavaScript programs contain JavaScript statements .The statements are executed, one by one in the same order as they are written. Example:
JavaScript Variable:
Variable(Binding) means anything that can vary. JavaScript includes variables which hold the data value and it can be changed anytime. Example:
Conditional Execution:
In JavaScript conditional execution is created with the if keyword. In simple case, we want some code to be executed if, and only if ,a certain condition holds.
JavaScript includes three forms of if condition:
- if condition,
- if else condition and
- else if condition.
If condition:
Syntax:
Example:
if else condition:
Syntax:
Example:
else if condition:
Syntax:
Example:
While Loop:
Syntax:
Example:
Do while loop:
Syntax:
Example:
For Loop:
Syntax:
Example:
Switch:
Syntax:
Example:
ECMAScript Modules:
JavaScript standard from 2015 introduces its own, different module system. It is usually called ES modules, where ES stands for ECMAScript. ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.
ES Modules Syntax: The syntax to export and import. An HTML page can add a module by using a <script> tag with the special type=”module” or nomodule attribute:
Export:
The export statement is used when creating JavaScript modules to export functions, objects, class or primitive values from the module so they can be used by other programs with the import statement. Many way use export. Example:
Exporting individual features: Every functions, objects, class before use export.
Example:
Export Default : There are two different types of export, named and default. We can have multiple named exports per module but only one default export per file. Each type corresponds to one of the above syntax:
Example:
Export list: we can put export separately. Here we first declare, and then export.
Example:
Renaming Exports: We can also use as to export under different names(change name).
Example:
Import:
Import – The static import statement is used to import bindings which are exported by another module. Imported modules are in strict mode whether we declare them as such or not. Many way use import. Example:
Importing Named: We can have multiple named exports per module. Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.
Example:
Importing Default: We can have only one default export per module. A default export can be imported with any name.
Example:
Importing Default and Named: We can have only one default export per module. A default export can be imported with any name.
Example:
Importing All: Import all of a module’s exports as a module object.
Example:
‘Async & Await’ is the process that works to use “promise” in a more comfortable way. The advantage of “async & await ” is that it is easy to understand and use.
Async Function: Async function starts with async keyword.
Await: The keyword await makes JavaScript wait until that promise settles and returns its result.Let’s see an example how we can use async & await. Here is an array of customer object.
Now we will create a method to get the customer firstname using forEach loop. There is a function setTimeout() which is used to show time delay as a symbol of asynchronization.
Here is another function that create customer and push to the array. The function works as a promise.
Now what will happen for the following code?
That’s the output. The third customer is’nt in the customer as it way delayed 2000 ms.
Here we can solve this by async & await. We will make the getCustomer() function wait until createCustomer() has done it’s work.
Then everything works fine.
That’s how async & await works. Happy Coding!!!!
Asynchronous Programming
What is Asynchronous?
In general, asynchronous comes from Greek asyn-, meaning “not with,” and chronos, meaning “time” is an adjective describing objects or events that are not coordinated in time.
In computer programs, asynchronous operation means that a process operates independently of other processes, whereas synchronous operation means that the process runs only as a result of some other process being completed or handing off operation.
In a synchronous way the first operation is start first and complete its execution then the next operation is start after complete the first one. Next operation is blocked by the previous operation until complete it. But in asynchronous programming one task never wait for another task for execute. The task execute first which completed first. It never block one task input or output for another task.
JavaScript is an asynchronous programming language and java is a synchronous language.
Example 1: Synchronous programming java
In this example after execute first line it will wait for 5 sec, then second and third line will be executed. Also wait 4 second after third line and execute fourth and fifth line.
Example 2: Asynchronous programming JavaScript.
In this example using JavaScript no line wait for another line. Here second line does not wait for first line and forth line does not wait after third line. These all lines are execute at run time. No line blocked another line. That is non-blocking of asynchronous programming.
There are different way to implement Asynchronous in JavaScript.
- Callback function
- Promise
- Generators
- Async & Await
I will describe here about Callback function and Promise.
Callback function:
Callback function is a function that return or use another function as it’s parameter.
Callback is an easier way to describe asynchronous programming.
Example:
In this example setTimeout function uses another function to display second line. And this timeout function set 5 sec waiting time for second line and 4 sec for fourth line.
But in execution third and fifth line does not wait for second and fourth line. They are executed after first line. Then fourth line is executed before second line because second line needs more time.
Here second line need 5 sec . But it can’t block the execution of another line after it. So this is an non-blocking process and this process is defined by asynchronous.
Promise:
Promise is a build in object in JavaScript(ES6).
Promises are the way to deal with asynchronous programming without writing too many callback in function.
It is begin difficult to maintain the program when the chain of callback functions is so long to implement lots of asynchronous task. To solve this problem we can use promise. It is a clean way to implement asynchronous programming in JavaScript.
Promises give us a way to handle asynchronous processing in a synchronous way. They represent a value that we can handle at some point in the future. And, better than callbacks here, Promises give us guarantees about that future value, specifically:
- The promise is immutable: No other registered handlers of that value can change it.
- We are guaranteed to receive the value, regardless of when we register a handler for it, even if it’s already resolved.
For example:
Creating promise:
To create an object we can use class in ES6. We can also use a constructor with it. Constructor is used to give property values in object creation time. To deal with promise there are two methods. Then() and catch(). That works as chain
In this way a promise has three steps.
1.Pending: until a Promise is fulfilled it is in pending state
- Fulfillment: when the first handler is called the Promise is considered fulfilled with the value passed to that handler.
- Rejected: if the second handler is called, the Promise is considered rejected with the value passed to that handler.
The standard way to create a promise is to use new Promise construction with accept a handler that is given two function as parameter. The first handler is resolve and another is reject.
Example:
The then() method takes a function that will be passed the resolved value of the Promise when it is fulfilled. And the catch() method takes a single handler to be called when a promise is rejected.
Md. Hamidur Rahaman
What is ASP.NET SignalR:
ASP.NET SignalR is a library for ASP.NET developers to add real-time web functionality to their applications. Real-time web functionality is the ability to have server-side code push content to the connected clients as it happens, in real-time.
SignalR takes advantage of several transports, automatically selecting the best available transport given the client’s and server’s best available transport. SignalR takes advantage of WebSocket, an HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it’s available, and gracefully fall back to other techniques and technologies when it isn’t, while the application code remains the same.
SignalR also provides a simple, high-level API for doing server-to-client RPC (call JavaScript functions in a client’s browser from server-side .NET code) in an ASP.NET application, as well as adding useful hooks for connection management, such as connect/disconnect events, grouping connections, authorization.
How to use ASP.NET SignalR In your Project:
Step 01: Create ASP.NET MVC Project First from Visual Studio.
Step 02: SignalR Developed with JQuery, so at first we need to add the latest JQuery in our project
Step 03: After installing JQuery, we need to add SignalR Library in our Project.
Note: After Install SignalR we will see those packages in out reference
And also see those js files in the scripts section.
Step 04: Update Startup.cs Class
Step 05: Create HUB For Client-Server-Client Connection
Step 06: Update Customer Hub
In this Section we create a Method called CustomerBroadcast, we can create this by any name as we need, and we create an object of HubContext so that we can find all active clients from here and notify them data as well as when we need.
The last line of this method is very important, context.Clients.All.xxxx this (xxxx) this is the method that we will create in our front side and trigger from here when needed, but this method should be started with camel case.
Step 07: Create Customer Model
Step 08: Add Db Context to Communicate with Database by Entity Framework, Add migration and Update Database as well
Step 09: Now we will create an Action (Insert) in Home Controller and Hub Method When Need to Broadcast to Clients. It could be Create/ update/ delete/ etc. and when this method is called, this will automatically invoke client-side function by Running SignalR Hub.js.
Step 10: Create View for Insert Action
Step 11: Create Index View for See Details, add SignalR js Reference from Scripts folder, then add Virtual path for hub connection, and then add our Customer.js File (we will add bellow)
Step 12: Create a new js file for client update.
Note: When our Server side Method (ProjectHub.CustomerBroadcast()) is call from anywhere in our server side,
Then this con.client.getUpdatedData function also called from client side automatically, and we will get updated data.
Update Customer.js File like bellow.
That’s it, now run the application and Go to Insert page, fill up the form and submit.
in Index page, firstly hub.start function will call and we will see the data, but when any server-side data updates, all clients also updated as expected.
Final Output:
For testing, we have opened two browsers, one for insert and another one for See the Customer List. So when we Fill up the insert form and submit the form, all clients will receive those data that server pushed, and updates table by JQuery. so No need to refresh or make another server request, this is the beauty of ASP.NET SignalR. 🙂
Source GitLab: https://gitlab.com/Sraban75/signalrefcf.git
—————————— The End——————————
Closure:
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables. Whenever a function is called, a new scope is created for that call. The local variable declared inside the function belongs to that scope; they can only be accessed from that function.
Example:
function add(n) {
var b = n;
function result(m) {
var a = m;
return a+b;
}
return result;
}
var x=add(2);
console.log(x(3));
Output: 5
Here we have two functions.
- add() creates a local variable called b and returns the result() function.
- The result() function is an inner function that is defined inside add() and is only available within the body of the add() function. Note that the result() function has local variable a.
However, since inner functions have access to the variables of outer functions, result() can access the variable b declared in the parent function, add(). If result() were to have its own b local variable, it would use this instead. The result() function return sum of the a and b value.
In our example, the result() function had preserved the value of b when the add() function was executed, and continued to preserve (closure) it.
Expressions and statements are the bread and butter of a program’s code structure. In this blog I try to explain the concept of expressions and statements.
Expressions are fragments of code that produces a new value as a result. For example it is similar to arithmetical operation. By arithmetical operations we can do addition or subtraction between two numbers or more to create a new number as the result. There is an easy way to spot expressions is to look for the operator sign in the code.
There are different types of expressions:
- Arithmetic Expressions :
- String Expressions:
- Array and Object Expressions:
- Logical Expressions :
- Object Creation Expressions:These expressions return an object
- Object Property Expressions:
- Function Definition Expressions:
On the other hand, Most JavaScript programs contain JavaScript statements . The statements are executed, one by one in the same order as they are written.
We can see that , the statements are executed one by one and after statement 4 the result is executed.
Reference: https://eloquentjavascript.net/
Defining Class in JavaScript
JavaScript is very flexible object-oriented language in case of syntax. In object- oriented programming the concept that comes to our mind with object is ‘Class’. But the interesting fact about JavaScript is that there are no classes in JavaScript. Everything is a object. In case of inheritance, objects inherit from objects, not classes from classes as in the “class”-ical languages. So, isn’t it possible to define a class in JavaScript? The answer is yes.
The goal of this article to demonstrate the ways of defining class in JavaScript. Here are some ways-
1.Using function
Probably, one of the most common way to define a class is to define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), the keyword ‘this’ is used as seen in the following example.
We can instantiate an object using a constructor function of Student. Then to set some properties and call methods we can do the following:
2.Using Object Literals:
Another way of defining class is literals. Literals are shorter way to define objects and arrays in JavaScript.
To create an empty object we can do var empty={}; instead of normal way
var empty=new object();
For Array we can do:
var array=[]; instead of normal way
var array=new Array();
Here’s the same functionality as described in the previous examples, but using object literal syntax this time:
In this case we don’t need to (and cannot) create an instance of the class, it already exists. So we simply start using this instance.
Such an object is also sometimes called singleton. In java, Singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. But there is no scope of this concept in concept as JavaScript has no deal with class actually, it deals with object.
3. Singleton(Using a function)
Again Singleton? Yes, But the concept is little bit different. Let’s see how?
This way is actually the combination of the other two. The concept is that we can use function to define a singleton object.
So we see that, this is quite similar to 1. But the way of using object is exactly like 2.
Here the main point is that, the new function(){…} does two things at the same time. One, define an anonymous constructor function. Two, invoke it with new. But it might look a bit confusing. It’s an option, when one wants a constructor function that is needed to use only once and there’s no sense of giving it a name.
Summary
In our above discussion, we have tried to discuss different ways of defining class in JavaScript. But don’t forget that JavaScript has no class concept actually. It works with object only in function oriented way. But ‘Class’ keyword is being used now to define a class which is the concept of JavaScript ES6. We’ll talk about it later. That’s for today!!
Happy Coding !!!
Map() method:
This method is used when you need to do some type of transform on every element. The map method will applying a function to all of its elements in the array and creates a new array. Example,
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
We need persons id.
var personsId= persons.map(x=> x.id);
console.log(personsId);
Output: [1, 2, 3, 4]
This new array will always be the same size as the original array, even if you don’t return anything.
Filter() Method:
The filter method creates a new array with all array items that pass the test implemented by the function. The filter method will return an array that is the same size or smaller as the original array.
Use filter method: Filter receives the same arguments as map, and works very similarly.
Example:
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
Let’s find out the names of those whose salaries are under 4000.
var newPersons= persons.filter(x=> x.salary>= 4000);
newPersons.forEach(function(person){
console.log(person.name);
});
Output: Korim
Razzak
Abdul
Reduce() Method:
The reduce() method takes an array and apply a function to each item, resulting in a single output value. As a result, an array of numbers we can easily find the total or average of all values.
Example,
var numbers= [0,1,2,3];
var total= numbers.reduce((sum, value)=>sum+value,0);
console.log(total);
Output: 6
Syntax of reduce() method: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Combining map(), .filter() and reduce():
map() method and filter() method both return arrays. The reduce method return a single value from array. So, we can easily use. example,
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
find out the sum of their under salary 4000.
var total= persons.map(x=> x.salary)
.filter(x=> x>= 4000)
.reduce((sum, value)=>sum+value,0);
console.log(total);
Output: 21000
Higher Order Function
Before Higher order function we have to know about function. So let us introduce a function.
What is a function?
A function is a block of code that can solve a particular task and give result. A function must have a name and body. And also can have argument if needed by which it works and prepare output.
Functions are executed when they are called by name.
Example:
function Add(A,B) {
return A+B;
}
Now What is Higher order function?
Higher order function is a function that can receive another function as argument and return a function as output.
Sometimes we need to do some task in a function and one of the task is already done in another function which is created. At that moment to reduce code or complexity we can use this function as argument or return value.
Example:
Output: hello hamidur
here, hello() is a higher order function which take print() function as it’s argument. and return value from print() function.
Here we can see that filterEven is a function that filter all even numbers from an array. To find even numbers it use another function named test as it’s argument.
Filtering Array:
Array can be filtered it’s component on condition using filter() method. Filter() is a method of array that used to filter an array.
The filter array method creates a new array with all elements that pass the test implemented by the provided function.
Suppose we want to filter an array to even numbers. To find the even number it declare a function findEven(). And finally it find the even numbers by calling filter() method with argument findEven().
Example:
We can also write the function in this way… output will be same.
Output: 2,4,6,8
Summarizing with Reduce:
The reduce() method applies to a function against an accumulator to find a single value from an array based on condition.
Reduce() method provide a loop for the array and execute the function for each value of the array. The Return value is stored in the accumulator.
Example: Suppose we want to find the maximum value from an array . To solve this problem a function findMax() is used . In this function val is the accumulator which store the result. And maximum value is found by calling reduce() method with findMax() method.
Here the output is 9.
Another example is here, the reduce method is used to find the sum of all values in the array.
Transform with map:
map() is an array method to update the old array values. It calls with a function and create a new array with the result of calling function which works for every element of the array.
Example: Suppose we want to update an array for any reason . we want that every element of the array will be update by increasing 2.
Output: 3,4,5,6,7
We can also create a mapped function. In the example bellow we convert every element of the array into uppercase.
Output: A,B,C
- 1
- 2