Is Javascript Object Literal same as JSON?

There are lot of people still confused about Javascript Object versus and JSON.

both are same?

Answer is No . There is a difference between two

Look at the below sample code , both objects are valid javascript object literal.
var employeeObject1 = {
firstName: "Jameel",
lastName: "Moideen"
}

var employeeObject2 = {
"firstName": "Jameel",
"lastName": "Moideen"
}

Then what is the difference between JSON?
Answer is very simple. JSON have very strict rule , the property name should enclose with quotes.In the above example employeeObject2 is valid JSON.

Valid JSON
{
“firstName”: “Jameel”,
“lastName”: “Moideen”
}

InValid JSON
{
firstName: “Jameel”,
lastName: “Moideen”
}

There are some built in function in javascript to convert an array in to JSON , which can use from object to Valid JSON before you send it across the wire.

JSON.stringfy() – Convert an object to valid JSON
Example
JSON.stringify(employeeObject1)

“{“firstName”:”Jameel”,”lastName”:”Moideen”}”

JSON.parse() – Convert a string to Javascript Object
JSON.parse('{"firstName":"Jameel","lastName":"Moideen"}')

{firstName: “Jameel”, lastName: “Moideen”}

JavaScript check null or undefined – Best Practice

Let’s assume I have a variable called ‘a’ , which looks for some value.
var a;
if (a !== undefined && a!== null && a!=='') {
console.log("Something");
} else {
console.log("Nothing");
}

I have seen lot of developers is trying check condition like above to ensure we are getting the expected value we want.Do we really need to check the value a undefined and null and ?.

No. We don’t need.

Do like below as Best Practice

var a;
if (a) {
console.log("Something");
} else {
console.log("Nothing");
}

Did you understand what’s Javascript Engine doing under the hood?. In order to understand, Let’s analyze what will be the value return by the Javascript Engine when converting undefined , null and ”(An empty string also). You can directly check the same on your developer console.

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code.

Also I want to point out one more thing

What will be the result of Boolean(0)?

Ofcourse false. This will create some bug on your code when 0 become a valid value on your expected result. So please make sure this thing also when you write the code

How to serve static files from the nodemodules in ASP.NET Core

Here I am going to explain how to serve static files from the nodemodules

Step 1 : Add a NPM package.json file
Right click on Visual Studio Add > NewItem and select NPM configuration files and add to the project.


Step 2 : Update the package.json with required dependencies for application.

Make sure name should be lowercase without space.

Once you save the package.json , you can see the npm package in project dependencies and also node modules are downloaded in to the project directory.You can include the node_modules folder in to your VS Project by clicking show all files and include in to the project.

Step 3 : Create Middle ware to serve the files from node_modules directory
In order to create your own middleware , First you have to create an extension method for the builder to serve the files from the node_modules directory

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace Microsoft.AspNetCore.Builder
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app,string rootPath)
{
//Combine the rootpath to the node_modules to get the absolute path
var path = Path.Combine(rootPath, "node_modules");
var fileProvider = new PhysicalFileProvider(path);
var options = new StaticFileOptions();
options.RequestPath = "/node_modules";
options.FileProvider = fileProvider;
app.UseStaticFiles(options);
return app;
}
}
}

When you set a RequestPath , static files Middleware only try to respond to request starts with node_modules.

FileProvider is where does it goes to FileSystem to look for the file.

Finally Call the method by passing the application rootPath

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Builder
{
public class Startup
{

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IConfiguration configuration ,ILogger logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseStaticFiles();
app.UseNodeModules(env.ContentRootPath);
app.UseMvcWithDefaultRoute();
app.UseMvc(ConfigureRoutes);

}
private void ConfigureRoutes(IRouteBuilder routeBuilder)
{
routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id}");
}
}
}

Note : Please make sure the namespaces for extension method and startup.cs class are same. This is the approach that Microsoft uses to resolve the extension method for IApplicationBuilder to ensure method is more diiscoverable.

What is WebHost builder in ASP.NET Core?

A WebHost builder is an object , which is responsible for setting up the web server environment.These settings are completely customizable by writing our own builder. By default Web host builder is using Kestrel web server, which is a cross platform web server supported by .NET Core. This Webserver will listen all the http request connections. Also This builder set ups IIS integration. If your application are running under IIS , it is the integration that allows IIS to pass through Windows Credentials to the Kestrel server.

5

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost?view=aspnetcore-2.1

How to subscribe and unsubscribe the window load event in Rxjs

I know every web programmers are aware of adding window.addeventlistener to ensure some codes are executing once when loading the web page. You can remove the listener by removing using removeEventListener to make avoid the memory leak.

You can do the same thing in a RxJs fashion using take(1). So you no need to unsubscribe it explicitly to avoid the memory leak.
var onWindowLoad=Observable.fromEvent(window,'load');

var onLoadSubscription=onWindowLoad.take(1).forEach(function(event){
alert("onLoadFireEvent");
});

How Map and Filter function works in RXJS

In order to understand how Map and Filter works , we can implement our own map function.
Map
Map in Rxjs used for projection, means you can transform the array in to entirely new array.

Array.prototype.map = function(projectionFunction){
var results=[];
this.forEach(function(item) {
results.push(projectionFunction(item));
});
return results;
};

You can see I have written a map function which accepts an anonymous function as a parameter. This will be your function to apply the projection to transform the array. Inside the map function you can see iterating each item in a array , call the project function by passing each item and finally the result of the projection function will push to the results array.

JSON.stringify([1,2,3].map(function(x){return x+1;}))

Output
[2,3,4]

https://www.learnrxjs.io/operators/transformation/map.html

Filter
Filter is used to filter an array based on some condition. You can specify the condition through an anonymous function. The implementation of Filter and Map are almost same only the difference is Map will transform each item in an array and will push to the main array. But the filter will only push to the main array if the condition pass.
var hotelCollection = [
{
"id": 9999,
"name": "Hotel XXX",
"place": "Wayne",
"rating": 5.0
},
{
"id": 8888,
"name": "Hotel YYY",
"place": "WoodCliff Lake",
"rating": 4.5
},
{
"id": 7777,
"name": "Hotel ZZZ",
"place": "Franklin Lake",
"rating": 5.0
},
{
"id": 6666,
"title": "Hotel PPP",
"place": "Lancester",
"rating": 4.3
},
];

Source

Array.prototype.filter=function(predicateFunction){
var results=[];
this.forEach(element => {
if(predicateFunction(element)){
results.push(element)
}
});
return results;
}

var collection = hotelCollection.filter(x=>x.rating===5);
https://www.learnrxjs.io/operators/filtering/filter.html
Thanks for reading