Saturday, December 22, 2018

My Repo


·         Install cli
          npm install -g @angular/cli

·         uninstall cli
npm uninstall -g @angular/cli
npm cache clean

·         if cache clear fail run the command with
npm cache clean –force

·         msinfo32 from run command gives answer on whether OS is 32 bit or 64 bit.
·         Opening control panel from command prompt appwiz.cpl
·         If ng command is not recognized then go to “C:\Users\shahanu1\AppData\Roaming\npm” for ng.cmd file. Copy the path and add to the environment variable.

Opening of system properties from command prompt: sysdm.cpl
·         Add path “C:\Program Files\Microsoft VS Code“ to path variable in sysdm.cpl
·         Sysdm.cplàEnvironment variableàSystem VariablesàPathàNew Add new variables.

·        Upgrading CLI ànpm install -g @angular/cli@6”  it upgrades cli to version 6.0
Steps to be able to create angular apps in different version of angular
·        Get the latest CLI and install at global level
·        In order to create angular app in older version for example version 6 install CLI 6 in local folder.

·        To run angular app with ng command on a any machine other than lcoalhost.
ng serve --port 8080 --host 0.0.0.0 --disableHostCheck true
also you can modify angular.json file.
ading serve on .angular-cli.json.
Port here 4201. Solution found from #2542.
"defaults": {
"styleExt": "css",
"component": {},
"serve": { "host": "0.0.0.0", "port": 4201 }
}

---------------------------------------------------------------------------------------

1)   run command-" ng serve --host=0.0.0.0 --disable-host-check "
2)   This will disable host check and allow to access from outside(instead localhost) with ip address
Getting IP address of Wifi
goto system tray "All Settings" --> Network and Internet --> WiFi --> Show available networks --> goto connected -->
if its ethernet or wifi goto IPv4 address it is usually 192.168.32.x

Update npm 5:
As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.
Original answer:
Before version 5, NPM simply installed a package under node_modules by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the dependencies section of your package.json.
The --save option instructed NPM to include the package inside of the dependencies section of your package.json automatically, thus saving you an additional step.
In addition, there are the complementary options --save-dev and --save-optional which save the package under devDependencies and optionalDependencies, respectively. This is useful when installing development-only packages, like grunt or your testing library.


install Bootstrap 4 in Angular CLI with SASS (SCSS)

First we create a new project and tell angular to use SCSS for styling.
Open up your command prompt and enter:
ng new my-app --style=scss
cd my-app
Next we install Bootstrap 4 and the optional modules with npm
npm install jquery --save-prod
npm install popper.js --save-prod
npm install bootstrap --save-prod
Create an empty file _variables.scss in src/.
This _variables.scss file you can use to overwrite the Bootstrap variables. For more info on theming Bootstrap, read here.
In your project in src/styles.scss add the following:
@import 'variables';
@import '~/bootstrap/scss/bootstrap';
In angular.json (Angular 6 and higher)  add the three js files under scripts:
"scripts": [
   "node_modules/jquery/dist/jquery.slim.js",
   "node_modules/popper.js/dist/umd/popper.min.js",
   "node_modules/bootstrap/dist/js/bootstrap.min.js"
],
Restart ng serve to see the changes.

Install Bootstrap 4 in Angular CLI with CSS

Create a new Angular CLI project
ng new my-app
cd my-app
Install bootstrap 4 with npm:
npm install jquery --save-prod
npm install popper.js --save-prod
npm install bootstrap --save-prod
Open the styles.css file in your project.
Import the bootstrap style sheet as the first line.
/* You can add global styles to this file, and also import other style files */
 
@import "~bootstrap/dist/css/bootstrap.min.css";
Please note that before Angular 6 you would add the bootstrap css file to the styles section in the .angular-cli file. This no longer works.
Open angular.json in your project.
Find the first styles section under the build node and add the following lines:
NOTE: there are two styles sections!! One under build and one under test. If necessary put these lines in both sections.
"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],
Next find the first scripts section under the build node and add the following three scripts:
"scripts": [
  "node_modules/jquery/dist/jquery.slim.js",
  "node_modules/popper.js/dist/umd/popper.min.js", 
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
],
Restart ng serve to see the changes.
Source:
-----------------------------------------------------------------------------------------------------------------
IIS  - URL rewrite module
Download  
build the angular app with
ng build –base-ref “/<folder in inetpub\wwwroot>” –prod
for deploying application at root level you copy content at
ng build –prod


Ping SSo
pickupLocBaseUrl -https://ssolab.esurance.com/ext/ref/pickup
pickupLocBaseUrl -https://ssolab.esurance.com/ext/ref/pickup?REF=E6FD8C9E1A5623EAFA9694EA18A484E279A9EC91D89336DB854714D00003
pUsername - PingFedAdaptor-lab
pPassword - E$ur4nc3!
application instanceid – XPMAgentless
getmac address
cmd.exe
getmac /v /fo list
           opening programs - control appwiz.cpl
           admin                           -  control admintools
           printers                            -  control printers
           services                            - services.msc
Reactive forms provide a relatively easy testing strategy because they provide synchronous access to the form and data models, and they can be tested without rendering the UI.
           
Compodoc: Compodoc is a documentation tool for Angular applications. It generates a static documentation of your application.
Steps
1)    npm install -g "@compodoc/compodoc"
2)    npm install --save-dev @compodoc/compodoc
3)    Define a script task for it in your package.json
"scripts": {
  "compodoc": "./node_modules/.bin/compodoc -p src/tsconfig.app.json –w -s"
}

Run below command in a second terminal in VS code.
npm run compodoc
it will generate the documentation at http://127.0.0.0:8080 link.

In order to add markdown file (.md extension) for a “README” tab of a given component just add <name of component file>.md in the component folder.



Hosting simple html page with live-server.
1)  Install nodejs
2)  Npm install –g live-server.
3)  Add path of live server which generally is “C:\Users\shahanu1\AppData\Roaming\npm\node_modules\live-server\live-server.js” to user variable.

4)  Cd <myfolder> folder where you have index.html file
5)  Type command live-server.
6)  It will launch your html application.
Hurray.

                                         
You also may have noticed that we passed along { useHash: true } as the second argument — by default Angular 2 uses HTML5 location based routing, but that would require us to have a server set up that's smart enough to handle it. For the sake of simplicity we told Angular 2 to use hash based routing instead as it's guaranteed to work in virtually any environment setup.





Reactive programming is the idea we can define an application as a series of different streams with operations that connect the different streams together and which are automatically called when new values are pushed onto those streams.

Some people claim that Observables are asynchronous. That is not true. If you surround a function call with logs, like this:

Which proves the subscription of foo was entirely synchronous, just like a function.
Observables are able to deliver values either synchronously or asynchronously.

What is the difference between an Observable and a function? Observables can "return" multiple values over time, something which functions cannot. You can't do this:

Checking process listening port.
netstat -aon |find /i "listening”



Deploying Angular app to githubpages.

Prerequisites
You need to have Node.js, NPM and Angular CLI 6 installed, you also need to generate a new Angular 6 project using Angular CLI 6 or you can also apply this to an existing project that you want to deploy to Github Pages.

Next you also need to install a package which makes the process of deploying to Github pages easy.

$ npm install -g angular-cli-ghpages

Building the Angular 6 Application
The next step is to build your web application for production and with the base href location set to your Github Page URL.

$ ng build --prod --base-href "https://<YOUR_GITHUB_USER-NAME>.github.io/<YOUR_REPO_NAME>/"

ng build --prod --output-path <your_repo_name> --base-href="https://<your_github_user-name>.github.io/<your_repo_name>/"

Deploying to Github Pages
Now you are ready to deploy your web app to Github pages. Thanks to angular-cli-ghpages this is a one command process so just run:

$ ngh

You web app will be depoyed to https://username.github.io/app-name/


Providers –

In this case, providedIn: 'root' specifies that the service should be provided in the root injector.


providedIn and NgModules
It's also possible to specify that a service should be provided in a particular @NgModule. For example, if you don't want UserService to be available to applications unless they import a UserModule you've created, you can specify that the service should be provided in the module:

The example above shows the preferred way to provide a service in a module. This method is preferred because it enables tree-shaking of the service if nothing injects it. If it's not possible to specify in the service which module should provide it, you can also declare a provider for the service within the module:


In the basic CLI-generated app, modules are eagerly loaded which means that they are all loaded when the app launches. Angular uses an injector system to make things available between modules. In an eagerly loaded app, the root application injector makes all of the providers in all of the modules available throughout the app.
This behavior necessarily changes when you use lazy loading. Lazy loading is when you load modules only when you need them; for example, when routing. They aren’t loaded right away like with eagerly loaded modules. This means that any services listed in their provider arrays aren’t available because the root injector doesn’t know about these modules.
When the Angular router lazy-loads a module, it creates a new injector. This injector is a child of the root application injector. Imagine a tree of injectors; there is a single root injector and then a child injector for each lazy loaded module. The router adds all of the providers from the root injector to the child injector. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.
Any component created within a lazy loaded module’s context, such as by router navigation, gets the local instance of the service, not the instance in the root application injector. Components in external modules continue to receive the instance created for the application root.
Though you can provide services by lazy loading modules, not all services can be lazy loaded. For instance, some modules only work in the root module, such as the Router. The Router works with the global location object in the browser.
forRoot() and forChild()
You might have noticed that the CLI adds RouterModule.forRoot(routes) to the app-routing.module.ts imports array. This lets Angular know that this module, AppRoutingModule, is a routing module and forRoot() specifies that this is the root routing module. It configures all the routes you pass to it, gives you access to the router directives, and registers the RouterService. Use forRoot() in the AppRoutingModule—that is, one time in the app at the root level.
The CLI also adds RouterModule.forChild(routes) to feature routing modules. This way, Angular knows that the route list is only responsible for providing additional routes and is intended for feature modules. You can use forChild() in multiple modules.
forRoot() contains injector configuration which is global; such as configuring the Router. forChild() has no injector configuration, only directives such as RouterOutlet and RouterLink.
SkipSelf
decorator
A constructor parameter decorator that tells the DI framework that dependency resolution should start from the parent injector.
Optional
decorator
A constructor parameter decorator that marks a dependency as optional.

importing a module does not automatically re-export the imported module's imports. Module 'B' can't use ngIf just because it imported module 'A' which imported CommonModule. Module 'B' must import CommonModule itself.

Re-export makes module transitivity explicit. If Module 'A' re-exports CommonModule and Module 'B' imports Module 'A', Module 'B' components can use ngIf even though 'B' itself didn't import CommonModule.
entryComponents
A list of components that can be dynamically loaded into the view.
By default, an Angular app always has at least one entry component, the root component, AppComponent. Its purpose is to serve as a point of entry into the app, that is, you bootstrap it to launch the app.
Routed components are also entry components because they need to be loaded dynamically. The router creates them and drops them into the DOM near a <router-outlet>.
While the bootstrapped and routed components are entry components, you don't have to add them to a module's entryComponents list, as they are added implicitly.
Angular automatically adds components in the module's bootstrap and route definitions into the entryComponents list.
That leaves only components bootstrapped using one of the imperative techniques, such as ViewComponentRef.createComponent() as undiscoverable.
Dynamic component loading is not common in most apps beyond the router. If you need to dynamically load components, you must add these components to the entryComponents list yourself.
For more information, see Entry Components.
Bootstraping angular app using ngDoBootstrap
Hook for manual bootstrapping of the application instead of using bootstrap array in @NgModule annotation.
class AppModule implements DoBootstrap {
  ngDoBootstrap(appRef: ApplicationRef) {
    appRef.bootstrap(AppComponent); // Or some other component
  }
}







WebSocket
To begin the process of repurposing the TCP socket for WebSocket communication, the client can include a standard request header that was invented specifically for this kind of use case:
GET /index.html HTTP/1.1
Host: www.example.com
Connection: Upgrade
Upgrade: websocket
The Connection header tells the server that the client would like to negotiate a change in the way the socket is being used. The accompanying value Upgrade indicates that the transport protocol currently in use via TCP should change. Now that the server knows that the client wants to upgrade the protocol currently in use over the active TCP socket, the server knows to look for the corresponding Upgrade header, which will tell it which transport protocol the client wants to use for the remaining lifetime of the connection. As soon as the server sees websocket as the value of the Upgrade header, it knows that a WebSocket handshake process has begun.
Note that the handshake process (along with everything else) is outlined in RFC 6455, if you’d like to go into more detail than is covered in this article.
The first part of the WebSocket handshake, other than what is described above, involves proving that this is actually a proper WebSocket upgrade handshake and that the process is not being circumvented or emulated via some kind of intermediate trickery either by the client or perhaps by a proxy server that sits in the middle.
When initiating an upgrade to a WebSocket connection, the client must include a Sec-WebSocket-Key header with a value unique to that client. Here’s an example:
Sec-WebSocket-Key: BOq0IliaPZlnbMHEBYtdjmKIL38=
The above is automatic and handled for you if using the WebSocket class provided in modern browsers. You need only look for it on the server side and produce a response.
When responding, the server must append the special GUID value 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 to the key, generate a SHA-1 hash of the resultant string, then include it as the base-64-encoded value of a Sec-WebSocket-Accept header that it includes in the response:
Sec-WebSocket-Accept: 5fXT1W3UfPusBQv/h6c4hnwTJzk=
In a Node.js WebSocket server, we could write a function to generate this value like so:
JS
const crypto = require('crypto');

function generateAcceptValue (acceptKey) {
  return crypto
    .createHash('sha1')
    .update(acceptKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', 'binary')
    .digest('base64');
}
We’d then need only call this function, passing the value of the Sec-WebSocket-Key header as the argument, and set the function return value as the value of the Sec-WebSocket-Accept header when sending the response.
To complete the handshake, write the appropriate HTTP response headers to the client socket. A bare-bones response would look something like this:

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: m9raz0Lr21hfqAitCxWigVwhppA=
We’re not actually quite finished with the handshake at this point – there are a couple more things to think about.


WebSocket messages are delivered in packages called “frames”, which begin with a message header, and conclude with the “payload” – the message data for this frame. Large messages may split the data over several frames, in which case you need to keep track of what you’ve received so far and piece the data together once it has all arrived.

Running Angular app using http-server –
·         Install http-server globally using “npm install –g http-server”.
·         Goto dist folder of your angular app. CD /dist/<angular-app>
·         Start the http-server using the command on port 8081 “http-server –p 8081 –o” (-o option will launch the browser window)
·          


Using the async pipe
The above is a good start but we are not really using Observables to their full extent, for one thing
we are subscribing to the observable and storing the results locally on the component, we can skip
that by just using the async pipe in our template like so:

class AppComponent {

private loading: boolean = false;
private results: Observable<SearchItem[]>;

constructor(private itunes:SearchService) { }

doSearch(term:string) {
this.loading = true;
this.results = this.itunes.search(term);
}
}

results now stores the Observable itself and not an array of SearchItems. We don’t need to
subscribe but simply store the result of calling itunes.search.

To make the above work we need to use the async pipe in our template, like so:
<div *ngFor="let item of results | async"> ... </div>

What is the purpose of cache busting and how can you achieve it?
Browsers have a cache to temporarily store files on websites so they don't need to be re-downloaded again when switching between pages or reloading the same page. The server is set up to send headers that tell the browser to store the file for a given amount of time. This greatly increases website speed and preserves bandwidth.
However, it can cause problems when the website has been changed by developers because the user's cache still references old files. This can either leave them with old functionality or break a website if the cached CSS and JavaScript files are referencing elements that no longer exist, have moved or have been renamed.
Cache busting is the process of forcing the browser to download the new files. This is done by naming the file something different to the old file.
A common technique to force the browser to re-download the file is to append a query string to the end of the file.
·         src="js/script.js" => src="js/script.js?v=2"
The browser considers it a different file but prevents the need to change the file name.




What is BEM (Block Element Modifer)


#div1{
    box-sizing: border-box;
    width: 150px;
    height: 200px;
    padding: 5px;
    border: 2px solid blue;
    margin: 10px;
}

Below css styling - resets all of the selected element's properties to their initial values as defined in the CSS spec.
<div style="all:initial;">
  <div id="div1">something</div>
</div>

NodeJS often uses a callback pattern where if an error is encountered during execution, this error is passed as the first argument to the callback. What are the advantages of this pattern?

fs.readFile(filePath, function(err, data) {
  if (err) {
    // handle the error, the return is important here
    // so execution stops here
    return console.log(err)
  }
  // use the data object
  console.log(data)
})
Hide answer
Advantages include:
  • Not needing to process data if there is no need to even reference it
  • Having a consistent API leads to more adoption
  • Ability to easily adapt a callback pattern that will lead to more maintainable code
As you can see from below example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an Error object, which then becomes the callback's only parameter. The callback function allows a user to easily know whether or not an error occurred.
This practice is also called the Node.js error convention, and this kind of callback implementations are called error-first callbacks.
var isTrue = function(value, callback) {
  if (value === true) {
    callback(null, "Value was true.")
  } else {
    callback(new Error("Value is not true!"))
  }
}
 
var callback = function(error, retval) {
  if (error) {
    console.log(error)
    return
  }
  console.log(retval)
}
 
isTrue(false, callback)
isTrue(true, callback)
 
/*
  { stack: [Getter/Setter],
    arguments: undefined,
    type: undefined,
    message: 'Value is not true!' }
  Value was true.
*/

Good to hear

What is the difference between null and undefined?

In JavaScript, two values discretely represent nothing - undefined and null. The concrete difference between them is that null is explicit, while undefined is implicit. When a property does not exist or a variable has not been given a value, the value is undefinednull is set as the value to explicitly indicate “no value”. In essence, undefined is used when the nothing is not known, and null is used when the nothing is known.

Good to hear

·         typeof undefined evaluates to "undefined".
·         typeof null evaluates "object". However, it is still a primitive value and this is considered an implementation bug in JavaScript.
·         undefined == null evaluates to true.

Does JavaScript pass by value or by reference?

JavaScript always passes by value. However, with objects, the value is a reference to the object.

Good to hear

·         Difference between pass-by-value and pass-by-reference

How does prototypal inheritance differ from classical inheritance?

In the classical inheritance paradigm, object instances inherit their properties and functions from a class, which acts as a blueprint for the object. Object instances are typically created using a constructor and the new keyword.
In the prototypal inheritance paradigm, object instances inherit directly from other objects and are typically created using factory functions or Object.create().

What is the output of the following code?

const a = [1, 2, 3]
const b = [1, 2, 3]
const c = "1,2,3"
 
console.log(a == c)
console.log(a == b)
The first console.log outputs true because JavaScript's compiler performs type conversion and therefore it compares to strings by their value. On the other hand, the second console.log outputs false because Arrays are Objects and Objects are compared by reference.

Good to hear

·         JavaScript performs automatic type conversion
·         Objects are compared by reference
·         Primitives are compared by value

Where and why is the rel="noopener" attribute used?

The rel="noopener" is an attribute used in <a> elements (hyperlinks). It prevents pages from having a window.opener property, which would otherwise point to the page from where the link was opened and would allow the page opened from the hyperlink to manipulate the page where the hyperlink is.

Good to hear

·         rel="noopener" is applied to hyperlinks.
·         rel="noopener" prevents opened links from manipulating the source page.

What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous means each operation must wait for the previous one to complete.
Asynchronous means an operation can occur while another operation is still being processed.
In JavaScript, all code is synchronous due to the single-threaded nature of it. However, asynchronous operations not part of the program (such as XMLHttpRequest or setTimeout) are processed outside of the main thread because they are controlled by native code (browser APIs), but callbacks part of the program will still be executed synchronously.

Good to hear

·         JavaScript has a concurrency model based on an "event loop".
·         Functions like alert block the main thread so that no user input is registered until the user closes it.

What are the differences between varletconst and no keyword statements?

When no keyword exists before a variable assignment, it is either assigning a global variable if one does not exist, or reassigns an already declared variable. In non-strict mode, if the variable has not yet been declared, it will assign the variable as a property of the global object (window in browsers). In strict mode, it will throw an error to prevent unwanted global variables from being created.
var
var was the default statement to declare a variable until ES2015. It creates a function-scoped variable that can be reassigned and redeclared. However, due to its lack of block scoping, it can cause issues if the variable is being reused in a loop that contains an asynchronous callback because the variable will continue to exist outside of the block scope.
Below, by the time the the setTimeout callback executes, the loop has already finished and the i variable is 10, so all ten callbacks reference the same variable available in the function scope.
for (var i = 0; i < 10; i++) {
  setTimeout(() => {
    // logs `10` ten times
    console.log(i)
  })
}
 
/* Solutions with `var` */
for (var i = 0; i < 10; i++) {
  // Passed as an argument will use the value as-is in
  // that point in time
  setTimeout(console.log, 0, i)
}
 
for (var i = 0; i < 10; i++) {
  // Create a new function scope that will use the value
  // as-is in that point in time
  ;(i => {
    setTimeout(() => {
      console.log(i)
    })
  })(i)
}
let
let was introduced in ES2015 and is the new preferred way to declare variables that will be reassigned later. Trying to redeclare a variable again will throw an error. It is block-scoped so that using it in a loop will keep it scoped to the iteration.
for (let i = 0; i < 10; i++) {
  setTimeout(() => {
    // logs 0, 1, 2, 3, ...
    console.log(i)
  })
}
const
const was introduced in ES2015 and is the new preferred default way to declare all variables if they won't be reassigned later, even for objects that will be mutated (as long as the reference to the object does not change). It is block-scoped and cannot be reassigned.
const myObject = {}
myObject.prop = "hello!" // No error
myObject = "hello" // Error

Good to hear

·         All declarations are hoisted to the top of their scope.
·         However, with let and const there is a concept called the temporal dead zone (TDZ). While the declarations are still hoisted, there is a period between entering scope and being declared where they cannot be accessed.
·         Show a common issue with using var and how let can solve it, as well as a solution that keeps var.
·         var should be avoided whenever possible and prefer const as the default declaration statement for all variables unless they will be reassigned later, then use let if so.

What is a cross-site scripting attack (XSS) and how do you prevent it?

XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application. This is often achieved when the application does not validate user input and freely injects dynamic HTML content.
For example, a comment system will be at risk if it does not validate or escape user input. If the comment contains unescaped HTML, the comment can inject a <script> tag into the website that other users will execute against their knowledge.
  • The malicious script has access to cookies which are often used to store session tokens. If an attacker can obtain a user’s session cookie, they can impersonate the user.
  • The script can arbitrarily manipulate the DOM of the page the script is executing in, allowing the attacker to insert pieces of content that appear to be a real part of the website.
  • The script can use AJAX to send HTTP requests with arbitrary content to arbitrary destinations.

Good to hear

·         On the client, using textContent instead of innerHTML prevents the browser from running the string through the HTML parser which would execute scripts in it.
·         On the server, escaping HTML tags will prevent the browser from parsing the user input as actual HTML and therefore won't execute the script.

How can you avoid callback hells?

getData(function(a) {
  getMoreData(a, function(b) {
    getMoreData(b, function(c) {
      getMoreData(c, function(d) {
        getMoreData(d, function(e) {
          // ...
        })
      })
    })
  })
})
Hide answer
Refactoring the functions to return promises and using async/await is usually the best option. Instead of supplying the functions with callbacks that cause deep nesting, they return a promise that can be awaited and will be resolved once the data has arrived, allowing the next line of code to be evaluated in a sync-like fashion.
The above code can be restructured like so:
async function asyncAwaitVersion() {
  const a = await getData()
  const b = await getMoreData(a)
  const c = await getMoreData(b)
  const d = await getMoreData(c)
  const e = await getMoreData(d)
  // ...
}
There are lots of ways to solve the issue of callback hells:
  • Modularization: break callbacks into independent functions
  • Use a control flow library, like async
  • Use generators with Promises
  • Use async/await (from v7 on)

Good to hear

·         As an efficient JavaScript developer, you have to avoid the constantly growing indentation level, produce clean and readable code and be able to handle complex flows.

What is a closure? Can you give a useful example of one?

A closure is a function defined inside another function and has access to its lexical scope even when it is executing outside its lexical scope. The closure has access to variables in three scopes:
  • Variables declared in its own scope
  • Variables declared in the scope of the parent function
  • Variables declared in the global scope
1)    In JavaScript, all functions are closures because they have access to the outer scope, but most functions don't utilise the usefulness of closures: the persistence of state. Closures are also sometimes called stateful functions because of this.
2)    In addition, closures are the only way to store private data that can't be accessed from the outside in JavaScript. They are the key to the UMD (Universal Module Definition) pattern, which is frequently used in libraries that only expose a public API but keep the implementation details private, preventing name collisions with other libraries or the user's own code.

Good to hear

·         Closures are useful because they let you associate data with a function that operates on that data.
·         A closure can substitute an object with only a single method.
·         Closures can be used to emulate private properties and methods.

What is the difference between '+' and '~' sibling selectors?.

The General Sibling Selector ~ selects all elements that are siblings of a specified element.
The following example selects all <p> elements that are siblings of <div> elements:


div ~ p {
  background-color: blue;
}
The Adjacent Sibling Selector + selects all elements that are the adjacent siblings of a specified element.
The following example will select all <p> elements that are placed immediately after <div> elements:
div + p {
  background-color: red;
}
Additional links

Good to hear

·         ifference between '+' and '~' sibling selectors?.

·         Answer

·         The General Sibling Selector ~ selects all elements that are siblings of a specified element.
·         The following example selects all <p> elements that are siblings of <div> elements:
·         `css
·         div ~ p {
·         background-color: blue;
·         }
·         `
·         The Adjacent Sibling Selector + selects all elements that are the adjacent siblings of a specified element.
·         The following example will select all <p> elements that are placed immediately after <div> elements:
·         `css
·         div + p {
·         background-color: red;
·         }
·         `

 

 

 

Can you describe how CSS specificity works?

Assuming the browser has already determined the set of rules for an element, each rule is assigned a matrix of values, which correspond to the following from highest to lowest specificity:
  • Inline rules (binary - 1 or 0)
  • Number of id selectors
  • Number of class, pseudo-class and attribute selectors
  • Number of tags and pseudo-element selectors
When two selectors are compared, the comparison is made on a per-column basis (e.g. an id selector will always be higher than any amount of class selectors, as ids have higher specificity than classes). In cases of equal specificity between multiple rules, the rules that comes last in the page's style sheet is deemed more specific and therefore applied to the element.

Good to hear

·         Specificity matrix: [inline, id, class/pseudo-class/attribute, tag/pseudo-element]
·         In cases of equal specificity, last rule is applied

What is a focus ring? What is the correct solution to handle them?

A focus ring is a visible outline given to focusable elements such as buttons and anchor tags. It varies depending on the vendor, but generally it appears as a blue outline around the element to indicate it is currently focused.
In the past, many people specified outline: 0; on the element to remove the focus ring. However, this causes accessibility issues for keyboard users because the focus state may not be clear. When not specified though, it causes an unappealing blue ring to appear around an element.
In recent times, frameworks like Bootstrap have opted to use a more appealing box-shadow outline to replace the default focus ring. However, this is still not ideal for mouse users.
The best solution is an upcoming pseudo-selector :focus-visible which can be polyfilled today with JavaScript. It will only show a focus ring if the user is using a keyboard and leave it hidden for mouse users. This keeps both aesthetics for mouse use and accessibility for keyboard use.

What is a virtual DOM and why is it used in libraries/frameworks?

The virtual DOM (VDOM) is a representation of the real DOM in the form of plain JavaScript objects. These objects have properties to describe the real DOM nodes they represent: the node name, its attributes, and child nodes.
<div class="counter">
  <h1>0</h1>
  <button>-</button>
  <button>+</button>
</div>
The above markup's virtual DOM representation might look like this:
{
  nodeName: "div",
  attributes: { class: "counter" },
  children: [
    {
      nodeName: "h1",
      attributes: {},
      children: [0]
    },
    {
      nodeName: "button",
      attributes: {},
      children: ["-"]
    },
    {
      nodeName: "button",
      attributes: {},
      children: ["+"]
    }
  ]
}
The library/framework uses the virtual DOM as a means to improve performance. When the state of an application changes, the real DOM needs to be updated to reflect it. However, changing real DOM nodes is costly compared to recalculating the virtual DOM. The previous virtual DOM can be compared to the new virtual DOM very quickly in comparison.
Once the changes between the old VDOM and new VDOM have been calculated by the diffing engine of the framework, the real DOM can be patched efficiently in the least time possible to match the new state of the application.

Good to hear

·         Why accessing the DOM can be so costly.

CSS trick – image as base64 format instead of path, url.
Did you know that you don't have to link to an external image file when using an <img> element in HTML, or declaring a background-image in CSS? You can embed the image data directly into the document with data URIs.
With CSS, it looks like this:
CSS background: 
HTML image: 
Data-URI: 

The biggest reason: it saves HTTP Requests. Other than pure document size, this is the #1 factor concerning how fast a page loads. Less = better.


CSS style to convert unordered list into 3 boxes equally spaced.
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
CSS style.
ul>li{
    display: inline;
    border: 1px solid red;
    padding: 10px;
    margin-right: 5px;
}
  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
TRBL
With the CSS box-sizing Property
·         The box-sizing property allows us to include the padding and border in an element's total width and height.
·         If you set box-sizing: border-box; on an element padding and border are included in the width and height:
·          The initial keyword is used to set a CSS property to its default value.
The initial keyword can be used for any CSS property, and on any HTML element.

Grid
.wrapper {
    display: grid;
    grid-template-columns: 200px auto 200px 200px;;
    grid-template-rows:450px 250px auto;
    grid-column-gap: 10px;
    grid-row-gap: 20px;
    justify-items: stretch;
    align-items: start;
    justify-content: space-evenly;
    align-content: space-around;
  }
  * {box-sizing: border-box;}

















  .wrapper > div {
    border: 10px solid #e0d1c0;
    border-radius: 1px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
  }
 

Declaring variable in CSS
:root{
          --main-bg-color: brown;
      }

      .mycls{
          background-color: var(--main-bg-color);
      }

Closures Advantage.

·         Stateful functions
·         Encapsulating private data and internal implementation.
·         Provide UMD pattern used in js libraries, providing public APIs, preventing name collision with other libraries and data.
·         Associate data with a functions that operates on a data.
·         Can substitute an object with only a single method.
CSS
@import "~bootstrap/dist/css/bootstrap.min.css";

ul>li {
    display: inline-grid;
    margin-right: 20px;
    width: inherit;
    height: inherit;
}

div>a {
    display: inline;
}
div a h5 {
    color: darkolivegreen;
}
a:hover {
    text-decoration: none;
}