Thursday 23 May 2013

JQuery Multiple Checkbox Select/Deselect in the specific column of table

HTML - JQuery code to select and deselect checkboxes in the specific column of table. We can achieve this with very few line of JQuery code. Following are various JQuery methods which we are going use in our code.




» closest()

It begins with the current element and travels up the DOM tree until it finds a match for the supplied selector. The returned jQuery object contains zero or one element

» find()

You can use the find() to search through all the descendants(child, grandchild, great-grandchild…any levels deep) of the matched element

» index()

The index() method returns the index position of specified elements relative to other specified elements

» children()

Get the children of each element in the set of matched elements, optionally filtered by a selector. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while


» HTML Code

<table id="tbl-checkbox">
    <tr><th colspan="4">Select All</th></tr>
    <tr>        
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>

» JQuery Code

<script src="js/jquery-1.8.3.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $(".selectall").click(function(){
                     var tbl = $(this).closest("#tbl-checkbox");
            var col_index = $(this).closest("tr").children().index($(this).closest("td")) + 1;
            tbl.find("td:nth-child("+col_index+") input:checkbox").attr("checked",$(this).is(":checked"));
        });        
    });
</script>

Wednesday 22 May 2013

Create Multiple Virtual Hosts in WampServer

The term Virtual Host refers to the practice of running more than one web site (such as company1.example.com and company2.example.com) on a single machine. Today we are going to discuss on how to create multiple virtual hosts in Wamp (Windows, Apache, MySql, PHP) Server. I am hoping that you already have WampServer installed in your machine, if not then you can easily install it from http://www.wampserver.com/en/

Key Files:

hosts (C:\Windows\System32\Drivers\etc)
httpd.conf (C:\wamp\bin\apache\Apache2.2.21\conf)
httpd-vhosts(C:\wamp\bin\apache\Apache2.2.21\conf\extra)

(Note: I am considering that you have installed wamp on C:/ drive)

» Step 1: Go to path C:\wamp\bin\apache\Apache2.2.21\conf and open configuration file http.conf search for the "Virtual Hosts" and uncomment the line "Include conf/extra/httpd-vhosts.conf"


» Step 2: Go to path C:\wamp\bin\apache\Apache2.2.21\conf\extra and open file "httpd-vhosts"


» Step 3: Add the following lines to the very bottom of the file


» For localhost

<VirtualHost *:80>
  ServerName localhost
  DocumentRoot 'C:\wamp\www'
</VirtualHost>

» For site1

<VirtualHost *:80>
  ServerName mysite1.example.com
  DocumentRoot C:\wamp\www\mysite1
  SetEnv APPLICATION_ENV "development"
  <Directory C:\wamp\www\mysite1>
    Options -Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

» For site2

<VirtualHost *:80>
  ServerName mysite2.example.com
  DocumentRoot C:\wamp\www\mysite2
  SetEnv APPLICATION_ENV "development"
  <Directory C:\wamp\www\mysite2>
    Options -Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

» Step 4: Uncomment the line "NameVirtualHost *:80" if its not already uncommented


» Step 5: Now go to "C:\Windows\System32\Drivers\etc" and open "hosts" file. The hosts files has entries which maps IP Address to a name. By default the name “localhost” is mapped to 127.0.0.1 IP Address.

127.0.0.1     localhost

» Step 6: Now what we have to do is to simply add few more entries per client in this file. You may want to use your clients domain name as mapping key.

127.0.0.1     mysite1.example.com

127.0.0.1     mysite2.example.com

Add as many entries as you want in hosts file. Whenever you enter “mysite1.example.com” or "mysite2.example.com" in your web browser, windows will first look into hosts file and if it gets the corresponding entry, it sends the request to that IP Address.

» Step 7: Finally check for the read-write permission of project folder and restart the Apache.

Hope this help you.

Thanks. Have a great day!!

Thursday 9 May 2013

Useful Interview Questions and Answers


Here I've shared some very important questions and answers related to Web technology (PHP, JavaScript, MySQL etc..) which are really helpful for you while facing interviews. Well some of them I've made, modified while some of them I've referred from various articles available on google so, if you want to provide some suggestion, correction or anything about this article then feel free to post a comment.


PHP

» What is the difference between echo, print and printf?

→ print and echo both output what is passed to them. print acts like a function, so you can use it in complex statements. printf is used to format the output.

» Are variables passed to functions by reference or value?

→ A variable is passed by value unless the variable is passed with an &, such as functionName(&$variableName)

» What does a special set of tags <?= and ?> do in PHP?

→ The output is displayed directly to the browser.

» What is the difference between PHP4 and PHP5?

→ PHP4 cannot support oops concepts and Zend engine 1 is used. PHP5 supports oops concepts and Zend engine 2 is used. Error supporting is increased in PHP5. XML and SQLLite will is increased in PHP5.

» What are the different types of errors in PHP?

→ There are 3 types of errors in PHP.

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.

2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors - for example, instantiating an object of a nonexistent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.

» What are the differences between require and include, include_once?

→ Following are the answers

Anwser 1: require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again. But require() and include() will do it as many times they are asked to do.

Anwser 2: The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.

Anwser 3: All three are used to an include file into the current page. If the file is not present, require(), calls a fatal error, while in include() does not. The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

Anwser 4: File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.

» How can we know the number of days between two given dates using PHP?


<?php
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
?>

» What is the difference between unlink() and unset() in PHP?

→ Unlink() used for file system handling which removes a file and Unset() is used for destroying a variable that was declared earlier.

» What is array_push(), array_merge() and array_combine() in PHP?

→ array_push() : The array_push() function inserts one or more elements to the end of an array. for example,

<?php
$var=array("red","blue");
array_push($var,"green","yellow");
print_r($var);
?> 
Output: Array ( [0] => red [1] => blue [2] => green [3] => yellow )
→ array_merge() : The array_merge() function merges one or more arrays into one array. for example,

<?php
$a1=array("a"=>"red","b"=>"blue");
$a2=array("c"=>"green","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Array ( [a] => red [b] => yellow [c] => green )
→ array_combine() : The array_combine() function creates an array by using the elements from one "keys" array and one "values" array. (Note: Both arrays must have equal number of elements!). For example:

<?php
$fname=array("sachin","rahul","sourav");
$age=array("40","41","42");

$c=array_combine($fname,$age);
print_r($c);
?> 
 Array ( [sachin] => 40 [rahul] => 41 [sourav] => 42 ) 

» How to submit form without submit button?

→ Javascript submit() is used for submit form without submit button. onclick call document.formname.submit().

» How to Reverse String without using string's built-in function in PHP?


<?php
$str = "Cricket";
echo "Original String: " . $str . "<br>";
$lencount = strlen($str);
echo "<b>Output:</b><br>";
for ($i = $lencount; $i >= 0; $i--) {
    echo $str[$i];
}
?>

» How to reverse string without using any loop and built-in function in php?


<?php
function revstr($str) {
    if ($str) {
        $str = revstr(substr($str, 1)) . $str[0];
    } else {
        $str = "";
    }
    return $str;
}

echo "Original String: Cricket<br>";
echo "<b>Output:</b><br>";
echo revstr("Cricket");
?>

» How to reverse an Array values without using array_reverse function in PHP?


<?php
$arrVal = array(1, 2, 3, 4, 5, 6);
echo "Original Array: array(1, 2, 3, 4, 5, 6)" . "<br>";
$count = count($arrVal);
echo "<b>Output:</b><br>";
for ($i = $count; $i >= 0; $i--) {
    echo $arrVal[$i];
}
?>

» Find String Length without using any stren() function in PHP?


<?php
function mystrlen($str) {
    $count = 0;
    for ($i = 0; $i < 10000000; $i++) {
        if ($str[$i] != "")
            $count++;
        else
            break;
    }
    return $count;
}

echo "String: Cricket<br>";
echo "<b>Output:</b><br>";
echo mystrlen("Cricket");
?>

» Asterisks Pyramid in PHP


<?php
echo "<pre>";
$horizontal = 10;
$vertical = 10;
while ($vertical--)
    echo str_repeat(' ', $vertical) . str_repeat('* ', $horizontal - $vertical) . "\n";
echo "</pre>";
?>

» Divide two numbers without using % and / operator


<?php
$dividend = 100;
$divisor = 5;
$count = 0;
for ($i = 0; $i <= $dividend; $i+=$divisor) {
    if ($i > 0) {
        $count += 1;
    }
}
echo $count;
?>
OR
<?php
$a = 10;
echo $b = bcdiv($a, 5);
?>
Learn more about BC Match functions

» Find string palindrome or not in PHP without using strrev() function

Check this

» What is var_dump in PHP?

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
<?php
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}
?>

» What is print_r() in PHP?

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
<?php
print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)
?>

Ref: http://stackoverflow.com/questions/3406171/php-var-dump-vs-print-r

» What is the difference between == and === in PHP?

- The == operator just checks to see if the left and right values are equal.
- The === operator actually checks to see if the left and right values are equal along with it also checks to see if they are of the same variable type (like whether they are both String, booleans, integers etc)

» Where Are PHP Configuration Settings Stored?

PHP stores configuration settings in a file called php.ini in PHP home directory. You can open it with any text editor to your settings.

» What exactly is validating and sanitizing?

Validating and sanitizing are two different kinds of filters Validating filters: - These filters are used to validate user sent information (input). Strict rules are applied for formatting such as URL or Email validating. It also sends the success type for a particular operation whether false or true.
Sanitizing filters: - These filters are used to allow or disallow specific characters present in a string. There are no restrictions on data format rules. This filter always returns the string.

» What are some magic methods in PHP, how might you use them?

Magic methods are basically triggers that occur when particular events happen in your coding. The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

» Explain how a PHP session works?

A PHP session cookie is set in the clients browser, on every request the client sends that cookie to the server. PHP then uses that cookie to select the corresponding session information. By default PHP session_start() will store session data in files, you can also store sessions in a database.

» How we declare cookies and how we expire it?

setcookie() function is used to set cookies in php.
To declare Cookies syntax will be:- setcookie(name, value, expire, path, domain);
name : Name of the cookie
value : Value of the cookie
expire : The time for cookie to expire
path : path to save the cookie where we want to save the cookie information
domain : domain name on which we want to save the cookie

» What is a .htacces file?

.htaccess is a configuration file running on Apache server.These .htaccess file used to change the functionality and features of apache web server.
Example:
.htaccess file used for url rewrite.
.htaccess file used to make the site password protected.
.htaccess file can restrict some ip addresses ,so that on restricted ip adresses site will not open.

» Is PHP an interpreted language or compiler language?

PHP is an interpreted language.

» What is the difference between compiler language and interpreted language?

Interpreted language executes line by line, if there is some error on a line it stops the execution of script.
Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script ,if there is some error on some line.

» How can we resolve maximum allocation time exceeds error?

We can resolve these errors through php.ini file or through .htaccess file.
1. From php.ini file increase the max_execution_time =360 (or more according to need) and change memory_limit =128M (or more according to need)
2. From php file we can increase time by writing ini_set(‘max_execution_time’,360 ) at top of php page to increase the execution time. And to change memory_limit write ini_set(‘memory_limit ,128M )
3. From .htaccess file we ncrease time and memory by

<IfModule mod_php5>
php_value max_execution_time 360
php_value m emory_limit  128M
</ IfModule >

» List out the predefined classes in PHP?

Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

» cURL in PHP?

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

<?php
  $curl_handle=curl_init();
  curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
  curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
  $buffer = curl_exec($curl_handle);
  curl_close($curl_handle);
  if (empty($buffer)){
      print "Nothing returned from url.<p>";
  }
  else{
      print $buffer;
  }
?>


Object Oriented Programming

» What is Polymorphism?

Polymorphism in OOP means classes have different functionality while sharing a common interface. It use to make application modular and extensible.
Basically, let’s say we have "cricket, football, tennies" classes. They’re all different, but they all fall under the same category as "sport". So, it would make sense to create an interface named "sport" and have all these classes implement it. That’s what polymorphism is. It’s a bunch of classes with different functionality and structure, but all use the same interface.

» What is Encapsulation?

Wrapping up data in single unit. It is also often used interchangeably with "Information Hiding". Encapsulation is just a way to define how our properties and methods can be used.
private, public and protected methods and properties are example of encapsulation.

class Encap
{
  //"$name" It is public and can be called in same clsss as well as child class
 public $name;
 
 // "$id" Keep social secirty numbers that are private. Only call in same class
 private $id;
 
  //"$tax" It is protected and only used on child class 
 protected $tax;
}

» What is Inheritance?

Inheritance is when a class extends another class and inherits the properties and methods of that class. The main advantage to this is the ability to use a parent class and modify it for a special use without actually modifying the actual class itself. You can create new methods and properties that can be used alongside the parent’s methods and properties.

class Sport
{
 public $sportname="cricket";

 public function myfavoritesport()
 {
  // body
 }
}

class Cricket extends Sport
{
 echo $this->sportname; // here we can use property of Sport class inside Cricket

 public function myfavoritesport() 
 {
         parent::myfavoritesport(); // preserving functionality of parents function
 } 
}

» What is Data Abstraction?

Abstraction is the process of recognizing and focusing on important characteristics of a situation or object and leaving/filtering out the un-wanted characteristics of that situation or object.Lets take a person as example and see how that person is abstracted in various situations

A doctor sees (abstracts) the person as patient. The doctor is interested in name, height, weight, age, blood group, previous or existing diseases etc of a person An employer sees (abstracts) a person as Employee. The employer is interested in name, age, health, degree of study, work experience etc of a person. So, you see that Abstraction is the basis for software development. Its through abstraction we define the essential aspects of a system. The process of identifying the abstractions for a given system is called as Modelling (or object modelling).

In the above example, the doctor may not be interested in characteristics of a person on which the employer is interested in and vice versa. Both employer and doctor will not be interested in all the characteristics of a person (like the color of dress the person wears on a particular day, the food the person takes, the relatives of the person etc). But however some elements are common to both doctor and the employer (like name, age, height etc). This common element gives way to generalization. Ie, if we eliminate enough details of an abstraction, it become so generalized that it can be applied wide in range of situations.

Reference: https://azagappan.wordpress.com/2006/05/26/what-is-data-abstraction/

SQL

» SQL commands

→ DDL (Data Definition Language) : create, alter, drop.
→ DML (Data Manipulation Language) : select, insert, update and delete
→ DCL (Data Control Language) : GRANT- Gives a privilege to user, REVOKE - Takes back privileges granted from user

» List MySQL Engines

PERFORMANCE_SCHEMA
InnoDB
MRG_MYISAM
BLACKHOLE
MyISAM

» What are MySQL triggers and how to use them?

See Answer

» MySQL Joins

- INNER JOIN: Returns all rows when there is at least one match in BOTH tables
- LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
- RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
- FULL JOIN: Return all rows when there is a match in ONE of the tables

» Find 3rd or nth maximum salary from table

Consider table "employee" having 3 columns: 1. emp_id, 2.emp_name, 3.emp_salary

- Select emp_salary from (SELECT DISTINCT emp_salary from employee ORDER BY emp_salary DESC LIMIT 0,3) a ORDER BY emp_salary ASC LIMIT 1;
OR
- Select TOP 1 emp_salary from (SELECT DISTINCT TOP 3 emp_salary from employee ORDER BY emp_salary DESC) a ORDER BY emp_salary ASC;

See more answers

» Primary Key

Primary Key uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Most tables should have a primary key, and each table can have only ONE primary key.

» Unique Key

It is same as Primary Key i.e. it enforces the Uniqueness of the values (i.e. avoids duplicate values) on the column[s] on which it is defined. But unlike primary key it allows Null value. Also we can have more than one Unique key columns.

» Foreign Key

A foreign key is a key used to link two tables together. This is sometimes called a referencing key. Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table. The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.

» Indexing in sql

Indexing is used to create indexes in tables. Indexes allow the database application to find data fast; without reading the whole table. An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries.

» What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

» How can we know the number of days between two given dates using MySQL?


SELECT DATEDIFF(‘2007-03-07′,’2005-01-01′);


AngularJS

» What is AngularJS?

AngularJS is a client side JavaScript framework for adding interactivity to HTML. If you want to create a dynamic web application then AngularJS is better because it helps you to organise your JavaScript code.

» What are Directives?

Directive is a marker on a HTML tag that tells Angular to run some JavaScript code. There are two types of Directives: 1) AngularJS Directives (Built-in) and 2) Custom Directives (User defined).
AngularJS Directives: AngularJS Directives prefix with "ng-". These are nothing but the extended HTML attributes which means we write it inside HTML tag same like we write other HTML attributes.
Some AngularJS Directives are:
- ng-app
- ng-model
- ng-controller
- ng-init
- Ex:
<div ng-app="MyApp"></div>

Custom Directives: We can write Custom Directive using "directive" function in AngularJS. It allows us to write HTML that express the behaviour of our Application. It simply replaces the element for which it is activated.
- Ex:
<h1>
<book-title></book-title>
<book-author></book-author>
</h2>

» Element Directives vs Attribute Directives

There are two types of Custom Directives you can create in AngularJS. One is "Element" Directive and second is "Attribute" Directive.

Element Directives: It allows us to create our own Element much like HTML element.
Ex: Consider a cricket team where we've many cricket players making up a cricket team. Wouldn't it be nice if in your HTML you could write this to display a cricket player in HTML?
<cricket-player></cricket-player>
To accomplish this it would take saveral HTML tags. But in AngularJS you can easily create this kind of elements.

Attribute Directives: It means we can write our own attribute inside HTML element like:
<h1 cricket-player></h1>
here we've defined "cricket-player" as an Attribute Element inside h1 tag. It would be difficult to understand the functionality of HTML by just looking at it so there comes the Custom Directives to write expressive HTML. Note: Use Element Directives for UI widgets and Attribute Directives for mixin behaviours ...like a tooltip.

» What is One Way Data Binding in AngularJS?

One way data binding means binding data from Model to View. Means data flows from Model to View/UI and not vice-versa.

» What is Two Way Data Binding in AngularJS?

Two way data binding means binding data from Model to View and vice versa. It ensures the synchronisation between Model and View.

» Why is custom directives are useful?

Expressiveness: It lets you write expressive HTMl so you can understand the application behaviour just by reading the HTML.
Reusablity: It lets you create self-contained units of functionality. We could easily plug in this directive into another angular app and avoid writing a lot of repetitive HTML.

» AngularJS Routes?

Routes are a way to manage apps containing more views.
Ex: When the app grows and needs to display more information? Stuffing more code to a single view will quickly make things messy. A better solution is to use multiple templates that display different pieces of data based on the URL that the user is visiting. We can do this with Angular's application routes.

» There are four steps to using routing in Angular


- Using ngView - This allows us to tell our Angular app where to load in templates

- Loading the ngRoute library - You need to explicitly import ngRoute in your application to slim the Angular core down, they put routing in separate module

- Importing ngRoute module - We need to include ngRoute in our main application module so our whole app will have access to this service

- Defining Routes: We can use $routeProvider's method to define routes i.e. .when() and .otherwise()

» What is $routeParams?

$routeParams is a service which allows us to retrieve current set route parameters. We can pull things like "id" from url parameters. It requires ngRoute module to be installed

» What is difference between $scope and Scope Object?

$scope: Allows you to set values as properties on our scope object.
Scope object: Allows you to create an isolate scope private to this directive.

» Difference between $rootScope and $scope

- $rootScope is available globally, no matter what controller you are in, whereas $scope is only available to the current controller and it's children.
- $rootScope is a parent object of all $scope angular objects created in a web page.
- $scope is created with ng-controller while $rootscope is created with ng-app.

» What is Services?

- Services use to organize and share code across your application.
- Services are responsibile for connecting and fetching data, and then sharing it across application.
- Services, like on the server-side, offer a great way for separating logic from your controllers.
- We can then use that service inside our controller, directive, filter and even in another service.
- AngularJS offers several built-in services like $http, $timeout, $filter etc...
- In AngularJS you can also define your own service. Following are the different ways using we can create service:

=> Using the service() method
=> Using the factory() method
=> Using the provider() method
=> Using the value() method
=> Using the constant() method
The most commonly used methods are service(), factory() and provider(). Have a look at following example referenced from : http://stackoverflow.com/questions/13762228/confused-about-service-vs-factory
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!"
            }
        }
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}​

So basically, provider(), factory(), and service() are all providers. A factory() is a special case of a provider() when all you need in your provider() is a $get() function. It allows you to write it with less code. A service() is a special case of a factory when you want to return an instance of a new object, with the same benefit of writing less code.
Refer http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/ to read more details about factory(), service() and provider()

» $broadcast(), $emit() and $on()

$broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite. It sends an event upwards from the current controller to all of its parent controllers. From the syntax point of view a typical call to $broadcast() and $emit() will look like this:

$scope.$broadcast("MyEvent",data);
$scope.$emit("MyEvent",data);

Here, MyEvent is the developer defined name of the event that you wish to raise. The optional data parameter can be any type of data that you wish to pass when MyEvent is dispatched by the system. For example, if you wish to pas data from one controller to another that data can go as this second parameter.
An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. A typical call to $on() will look like this:

$scope.$on("MyEvent", function(evt,data){ // handler code here });

Refer more details on : http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

» Dependency Injection?

When angular loads it creates something called an "Injector". When built-in services loads (like $http, $log) they registers with injector as being available libraries. When application loads it registers our controller with Injector telling it when I run I need ($http, $log) services. Then injectors say cool :) and when page loads and controller gets used the injector grabs those services and passed it to controller as an arguments thats called dependency Injection because its injecting depencies (in this case services) in to the controller as arguments.

» What is the bootstrapping in AngularJS?

In AngularJS initializing or starting an Angular application is called "Bootstrapping". AngularJS supports Automatic and Manual bootstrapping.
If you want angular to auto-bootstrap your application you need to add ng-app directive to the root of your application, typically on the tag or tag.
<!-- Example Auto-bootstrapping Angular App -->
<html ng-app="myAngularApp">

Another way to bootstrapping is manually initializing using script. Manual initialization provides you more control on how and when to initialize angular App. It is useful when you want to perform any other operation before Angular wakes up and compile the page.

<!-- Example: Manually Bootstrapping Angular App -->
<script>
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
</script>

» $sce service in AngularJS?

“Strict Contextual Escaping” abbreviated as “sce” is a service of angular, which helps to safely bind the values in angular application. One such example can be of HTML binding.

» AngularJS link function

Link: The link function is run after directive has been compiled or linked so it is best spot to do DOM manipulation or logic functionality for directive.

Ex:
angular.module("MyModule").directive("myDirective", function myDirective(){
  return 
  {
         link: function(scope,element,attrs)
 {
  element.on("click", function(){
   element.toggleClass("hidden");
  }
 }
 ...
  }
}

AngularJS passes several arguments to the link function, which looks like following:
scope : It is the scope of the element the directive is applied on. Note that scope is not injected but passed in.
element : It is the DOM element in HTML the directive is applied on.
attrs : These are the list of attributes as string available on the element in HTML.




JavaScript

» Javascript Object Creation: There are multiple ways to create object in JavaScript


// 1) Declaring Object Literal
var myObj = {};

// 2) Using the Object() constructor
var myObj = new Object();

// 3) Using Object.create() method
var myObj = Object.create(null);

» Functions in JavaScript

1) Declared functions:
function numAdd(a, b){
 return a+b;
}
This function since it declared is actually loaded right when the program is run and it is loaded into the memory and held there until you want to use it.
2) Function expressions:
var add = function numAdd(a,b){
 return a+b;
};
Function expressions are apply things little bit differently. In function expression we assigned declared function to a variable i.e. add. This particular thing is called function expression and it loads only when this particular line of code is reached inside your program. Since this is an assignment statement we need a semicolon to complete the statement.
To call function expression we actually use variable name i.e. add instead of function name. Ex:
add(2,4); // will return 6

3) Anonymous function: Anonymous function is the function expression without name means no need for naming function a second time.
var add = function (a,b){
 return a+b;
};
Here we've removed "numAdd" function name from function expression. We can call this function similar way we call function expression. Ex:
add(2,4) // will return 6

» What is Immediately Invoked Function Expression (IIFE) or Self Invoking Function in JavaScript?

An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition. It's just as if you assigned it to a variable, and used it right after, only without the variable.
var myAge = 24;

var myVar = (function() {
    var myAge = 25;
    console.log(myAge);
})();

console.log(myAge);

// Output: 

25
24
Here myVar function invoked immediately after completion of its definition so output becomes 25 first and 24 second.
More ref: Self Invoking Function or IIFE

» What is a closure?


  • A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. 
  • The closure has three scope chains: 
  • It has access to its own scope (variables defined between its curly brackets)
  • It has access to the outer function’s variables, and 
  • It has access to the global variables. 

Example:

function closureTest(){
 var x=4;
 return x;
}

Here, if I call closureTest(); it'll return 4

but if I try console.log(x); it'll return undefined because x is only accessible inside closureTest() function.

Now lets make it slight more complex

function closureTest(){
     var x=4;
 // The inner function can access the outer function's variables, because they feel like global variables
 function xClose(){    
  return x;
 }
 return xClose();
}

Lets call it

var checkLocalX=closureTest();
checkLocalX(); // Ouput is 4

Eventhough closureTest() has finished operating, its local variable is now bound within checkLocalX.
More examples of closure:

function myCar(carName) {
  var modelName = "Audi A6";

  function myCarColor(colorName) {
    console.log("Name: ", carName);
    console.log("Model: ", modelName);
    console.log("Color: ", colorName);
  }

  myCarColor("Red");
}

myCar("Audi");

// Here, myCarColor can access the "carName" variable which is defined as an argument to "myCar" function. 

// Also it can access modelName from "myCar" function

// This is closure

Closure memory efficiency example:

// Closure memory efficiency example

function getBigData(index){
 const array = new Array(5000).fill('Hello');
  console.dir("created..!!!");
  return array[index];
}

getBigData(600);
getBigData(1200);
getBigData(2400);

// In first example we are creating the array 3 times

function getBigData2(){
 const array = new Array(5000).fill('Hello');
  console.dir("Created again...");
  return function(index){
   array[index];
  } 
}

let data = new getBigData2();

data(600);
data(1200);
data(2400);


// But in first example we have created it only once and then maintaining it in 
// the closure scope. 
// It just saving our creation process hence it'll take less memory as compare to 
// first example.

» What is JavaScript Hoisting?


In JavaScript Hoisting is the concept of program load order. Load order ensures that every line of code can execute when it's needed.
Example:
We build a function like this:

function sumOfNum(x,y){
 var result=add(x*x, y*y);
 return result;

 function add(a,b){
  var c=a+b;
  return c;
 }
}

But JavaScript compiler actually loads it like this:
function sumOfNum(x,y){
 var result=undefined;  // given memory space at the beginning of scope initialization but it has no value. The very first value it has is undefined
 function add(a,b){ //next is whole declared function hoisted on top of scope and sits there in memory waiting for us to use it
  var c=a+b;
  return c;
 }
 result=add(x*x, y*y); //finally executable code will run
 return result;
}
Because declared stuff that needs space in memory is first "hoisted" to the top of the scope before any operational code run.

Order of precedence:
  1. Variable assignment
  2. Function declaration
  3. Variable declaration

For More details read this: https://scotch.io/tutorials/understanding-hoisting-in-javascript

» Explain Prototype and Inheritance in JavaScript?

The Object's parent is called it's Prototype.
Following are some of the properties of object in javascript:

  • constructor
  • valueOf
  • toLocaleString
  • toString
  • propertyIsEnumerable
  • isPrototypeOf
  • hasOwnProperty

All the above properties are belong to or come from the Object's Prototype.

When a generic object is created, its properties passes it many important properties.

A Prototype is like a blueprint object for the object we are trying to create.

So the Object Prototype (Highest Prototype) passess all the properties to object and that is called "Inheritance".

Inheritance helps avoid over-coding multiple properties and methods into similar objects.
So the object we create inherits directly from the highest level of javascript hierarchy i.e. the Object Prototype.

Similarly all the native JavaScript data structures inherit all of their properties and methods from their own prototypes. Like,

  • Array inherits from Array Prototype, so all the array methods & properties like push(), pop(), length, shift(), join(), reduce(), sort(), slice(), join() these all come from Array Prototype.
  • String inherits from String Prototype, so all the string methods & properties like concat(), trim(), length, toLowerCase(), toUpperCase(), substring(), replace(), indexOf(), these all come from String Prototype.
  • Number inherits from Number Prototype, so all the number methods & properties like toFixed(), toExponential(), toPrecision() these all come from String Prototype.
  • Function inherits from Function Prototype, so all the function methods & properties like name, bind(), call(), apply(), these all come from Function Prototype.
  • And all these above (lower level) prototypes (Array, String, Number, Function) inherit from the Object Prototype. 
  • That means all these prototypes have access of Object properties.

Ex:
var myString="Hello World";

myString.length;
myString.trim();
myString.indexOf();
myString.toString(); // Can access object prototypes method
myString.valueOf(); // Can access object prototypes method
Because Object Prototype is Ancestor of String Prototype and myString variable.

» Explain "Short-Circuiting" in JavaScript?

Like many other languages Javascript’s && and || operators short-circuit evaluations, that is, for && if the first operand evaluates to false, the second operand is never evaluated because the result would always be false. Similarly, for || if the result of the first operand is true, the second operand is never operated.
Example:

var myVar=true; 
myVar=myVar || null;
console.log(myVar);

Output: true;

var myVar=false; 
myVar=myVar || null;
console.log(myVar);

Output: null;

var myVar=undefined; 
myVar=myVar || null;
console.log(myVar);

Output: null;
Which means as soon as something "not false" is found, it is accepted for the assignment. This is called Short-Circuiting.

» History of JavaScript and ECMAScript

- ECMAScript 2015 or ES6 is the most extensive updated JavaScript language since the publication of its first edition in 1997.
- ECMAScript 2016 or ES7 is released after ES6 which has some cool features.
- Here are some more articles on ECMAScript
- https://webapplog.com/es6/
- https://davidwalsh.name/es7-es8-features
- https://medium.com/@madasamy/javascript-brief-history-and-ecmascript-es6-es7-es8-features-673973394df4
- Arrow Functions in ES6
- JavaScript Design Pattern

» Declaring variables with "let" in JavaScript

"let" variables are scoped to the nearest block (a block is any code section with curly braces, like if,else,for, while etc.) and are not hoisted. Using let instead of var prevents variable declarations from being moved to the top of the scope on hoisting.
let vs var:
var has some unexpected behaviour inside for-in loop.
Example:
function getUserProfile(usersArr){
 for(var i in usersArr){
  //calling fetchProfile function to fetch users data. It has two args 1. server url to grab data & 2. callback when we got response from server
  fetchProfile("/users/"+usersArr[i], function(){
   console.log("Fetched ", usersArr[i]); //we are accessing i inside callback  }
 }
}

When we call getUserProfile(['virat','rohit','ashwin','jadeja']; we'll get an output like

Fetched jadeja
Fetched jadeja
Fetched jadeja
Fetched jadeja

This is unexpectedly outputs the same value on all iterations because here first of all var i is hoisted to the top of the function and shared across each iteration of the loop which means we've same i variable so when callbacks begin to run, i holds the last value assigned to it from the for loop.
We can solve this by just replacing var keyword with let.

Example:
function getUserProfile(usersArr){
 for(let i in usersArr){
  //calling fetchProfile function to fetch users data. It has two args 1. server url to grab data & 2. callback when we got response from server
  fetchProfile("/users/"+usersArr[i], function(){
   console.log("Fetched ", usersArr[i]); //we are accessing i inside callback  }
 }
}

Now When we call getUserProfile(['virat','rohit','ashwin','jadeja']; we'll get an output like:

Fetched virat
Fetched rohit
Fetched ashwin
Fetched jadeja

With let, there is no sharing in for loops. A new variable is created on each iteration. So each callback function holds a reference to their own version of i.
Variable declared with "let" can be reassigned, but cannot be redeclared within the same Scope.

let sport="cricket";
sport="football";
// Reassigning is allowed

let sport="cricket";
let sport="football";
// Redeclaring is not allowed thus it'll throw an error : TypeError: Identifier 'sport' has already declared

Now lets see another example:

    let myVar = "hello";                     // Global Scope
            function myFun(){
            let myVar = "world";            // Local Scope
                    console.log(myVar);
            }            
    console.log(myVar);
    myFun();

Output:
Hello
World

In above example though we are using same variable "myVar" it will not throw any error because we are using it within different scope.

» How to reverse string in JavaScript without using reverse() function?


<script type="text/javascript">    
    /*
     ***************** Example 1******************
     */
    var string="kunal jog";
    var len=string.length;
    var count="";
    for(var i=(len-1); i>=0;i--){
        count+=string[i];
    }
    //alert(count);    
    console.log(count);
        
        
    /*
     ***************** Example 2******************
     */
    var string="javascript";
    var len=string.length;
    var count="";
    for(var i=1; i<=len; i++){
        count+=string[len-i];
    }
        
    //alert(count);    
    console.log(count);    
</script>


» How to count string length in JavaScript without using length property?


<script type="text/javascript">        
    var string="JavaScript";
    var count=0;    
    while(string[count] != undefined){
        count++;
    }    
    //alert(count);
    console.log(count);
</script>


» String Palindrome program in JavaScript?



<script type="text/javascript">
function isPalindrome(str) {
    str = str.replace(/\W/g, '').toLowerCase();
    alert(str);
    return (str == str.split('').reverse().join(''));
}

console.log(isPalindrome("level"));                   // logs 'true'
console.log(isPalindrome("levels"));                  // logs 'false'
console.log(isPalindrome("A car, a man, a maraca"));  // logs 'true'
</script>


» How to empty an array in JavaScript?



<script type="text/javascript">

/* Example: Consider following array */

 var arrayList =  ['a','b','c','d','e','f'];

/* There are a couple ways we can use to empty an array */

arrayList = []     // Method 1

arrayList.length = 0;    // Method 2

arrayList.splice(0, arrayList.length);      // Method 3

</script>


» What is Memoization?

Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed input.

Example:

<script type="text/javascript">
var cachedResult;
function doHeavyCalculation()
{
    if (typeof(cachedResult) !== 'undefined')
        return cachedResult;

    // no cached result available. calculate it, and store it.
    cachedResult = /* do your computation */;
    return cachedResult;
}
</script>

Thanks to Drew Noakes. Reference: http://stackoverflow.com/questions/20103739/javascript-memorization

» What is JQuery Method Chaining?

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
//Example without chaining:

$("#p1").css("color","red);
$("#p1").slideUp(2000);
$("#p1").slideDown(2000);


//Example with chaining:

$("#p1").css("color", "red").slideUp(2000).slideDown(2000); //single statement

Notice that with chaining, the #p1 only needs to be selected one time, whereas without chaining, jQuery must search the whole DOM and find the #p1 before each method is applied. Thus, in addition to yielding more concise code, method chaining in jQuery offers a potentially powerful performance advantage.

» What is Event Delegation and Event Bubbling?

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Event Bubbling means that an event propagates through the ancestors of the element the event fired on.

For more details: Read Here

» What is Event loop?

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed

» What is DOM (Document Object Model)

- It is a tree-like structure created by browsers so we can quickly find HTML elements using JavaScript.
- Manipulating/Changing the DOM means using this API to change the document (add elements, remove elements, move elements around etc...)
- Traversing the DOM means navigating it - selecting specific elements, iterating over groups of elements etc

» Difference between null and undefined in JavaScript

- In JavaScript null is an object without any value and undefined is type.


// Example:

typeof null; // "object"
typeof undefined; // "undefined"

var a;  
var b = null;  
a == b; // "true" because their values are the same  
a === b; // "false". they have different types


» What is the difference between ‘display:none’ and ‘visibility:hidden’?

display:none will not be available in the page and does not occupy any space. visibility:hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout. visibility:hidden preserve the space, whereas display:none doesn't preserve the space.

» window.onload vs document.onload

window.onload()
By default, it is fired when the entire page loads, including its content (images, css, scripts, etc.) In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.

document.onload()
It is called when the DOM is ready which can be prior to images and other external content is loaded.

What would “1”+2+3 and 1+2+“3” evaluate to, respectively?

"1"+2+3 will display 123
because when the first character is a string, the remaining characters will be converted into a single string, rendering 123

And

1+2+"3" will display 33
because if the string is at the end, the initial characters will perform normal mathematical functions before converting into a string, resulting in 33

» Javascript call() & apply() vs bind()?


var obj={num:2};
var addToThis=function(a, b){
 return this.num+a+b;
};

/* .call() attaches a function to object temporarily,
runs it and give back as a part of object. 
It attaches "this" into function and executes the function immediately */
alert(addToThis.call(obj,4,8));


/* .apply() is similar to call except that it takes 
an array-like object instead of listing the arguments 
out one at a time */
var arr = [4,8];
alert(addToThis.apply(obj,arr));


/* .bind() attaches "this" into function and it needs to be invoked separately like this: */

var add=addToThis.bind(obj);
alert(add(4,8));
// or we can also it like this
var add=addToThis.bind(obj,4,8);
alert(add());

call() & apply() - are useful for borrowing methods while apply() is useful for us to call a function later on with certain context (or certain this keyword). See example below:

var mySport = {
 name: "Cricket",
  matchesWon: 5,
  getData(num1, num2){
   return this.matchesWon += num1+num2;
  }
}

var mySport1 = {
 name: "Football",
  matchesWon: 5
}

// So lets say I want to borrow a function getData() from mySport object to mySport1 object then

mySport.getData.call(mySport1,10,10);

console.log("Call ex => ", mySport1);

// result would be: 
// {"name":"Football","matchesWon":25}

// Apply is the same only it takes arguments as an array, Ex:

mySport.getData.apply(mySport1,[20,20]);

console.log("Apply ex => ", mySport1);

// result would be: 
// {"name":"Football","matchesWon":65}


// Lets see bind() now. 

// Unlike call() and apply() bind returns a new function 
// with a certain context and parameters instead of immediatelly calling it.

mySport.getData.bind(mySport1,30,30);

// now if I do console then it won't work
console.log("bind without function call ex => ", mySport1);

// result would be: 
// {"name":"Football","matchesWon":65}

// but if I do like this

var newSport = mySport.getData.bind(mySport1,30,30);
newSport();

console.log("bind with function call ex => ", mySport1);

// result would be: 
// {"name":"Football","matchesWon":125}

» Compare two arrays and find difference between them?


<script type="text/javascript">
    var array1 = [1, 2, 3, 4, 5, 6];
    var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    var result = [];

    /***********Method 1************/
    var count = 0;
    $.grep(array2, function (index) {
        console.log(index);
        if ($.inArray(index, array1) == -1)
            result.push(index);
        count++;
    });
    console.log(" the difference is " + result);


/************Method 2**************/
    var len = array2.length;
    for (var i = 0; i <= len - 1; i++) {
        if (array1.indexOf(array2[i]) == -1) {
            result.push(array2[i]);
        }
    }
    console.log(" the difference is " + result);


/************Method 3**************/
    var diff = $(array2).not(array1).get();
    alert(diff);
</script>

» Shallow Copy and Deep Copy

  • Shallow Copy - its slightly opposite of above i.e. even if you copy old variable to new one certain values (sub-values) are still connected to the old variable.
  • Deep Copy - means all the values of old variable are copied to the new variable and changing values from new variable will not affect on old one.
  • Refer this blog for more details

» NaN and isNaN() in JavaScript

  • NaN is return value of a number which have an undefined numerical result
  • Ex. typeof NaN // output will be Number
  • NaN can happen if you divide number zero by zero (0/0), if you try to convert undefined or non-numeric string into a number, any operation where NaN is an operand etc..
  • isNaN - It checks whether the value is Not a Number which means illegal number.
  • It returns true of value is not a number
- Ex:

isNaN('Hello') //true
isNaN(712) //false
isNaN(-2) //false
isNaN(10-5) //false
isNaN(0) //false
isNaN('1') //false
isNaN('') //false
isNaN(true) //false
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true

» JavaScript Array Methods : forEach, Filter, Map and Reduce

https://codeburst.io/array-methods-explained-filter-vs-map-vs-reduce-vs-foreach-ea3127c6d319

» JavaScript Spread Operator

http://creativecoders.blogspot.com/2019/04/javascript-es6-spread-operator.html

» JavaScript => Arrow Functions i.e. Fat Arrow Functions

https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26

» Callback functions in JavaScript

https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

» JSONp (JSON Padding) and CORS (Cross Origin Resource Sharing)

https://medium.freecodecamp.org/use-jsonp-and-other-alternatives-to-bypass-the-same-origin-policy-17114a5f2016



Angular (2,4,6+)

» Angular Compilation : AOT vs JIT


Angular offers two types of code compilation i.e. AOT and JIT.

What is mean by code compilation in angular: Well it DOES NOT MEAN COMPILING TYPESCRIPT INTO JAVASCRIPT BECAUSE THAT IS THE JOB OF CLI. Angular also needs to compile our templates i.e. html dom, so it first parses these html files and compiles it into JavaScript because accessing JavaScript is faster than accessing HTML DOM.

JIT:

  • JIT stands for Just in Time compilation
  • It compiles our code i.e. HTML and TypeScript on browser at runtime hence performance wise its slow
  • For JIT you don't need to build after changing your code or before reloading the browser page which is suitable for local env while development.
  • Commands : ng build, ng serve

AOT:

  • AOT stands for Ahead of Time compilation
  • It compiles at the build time i.e. machine itself does the compilation process via command line.
  • It it suitable mainly for production build as you don't need to deploy compiler.
  • It is secure, original source code node disclosed.
  • Detect template errors earlier.
  • Commands : ng build --aot, ng serve --aot, ng build --prod


» What is Polyfills.ts in Angular?


Polyfills in angular is a plugin which makes your application compatible for different browsers as Angular has new features which written in ES6 and typescript, so polyfills helps to compatible with different browsers.

Polyfills does some environment setups before rendering it on to the browser.

From Docs : Angular is built on the latest standards of the web platform. Targeting such a wide 
range of browsers is challenging because they do not support all features of modern browsers.

» Dependancies vs DevDependencies


The difference between these two, is that devDependencies are modules which are only required during development, while dependencies are modules which are also required at runtime.

To save a dependency as a devDependency on installation we need to do an npm install --save-dev, instead of just an npm install --save. A nice shorthand for installing a devDependency that I like to use is npm i -D. The shorthand for saving a regular dependency is -S instead of -D.

» ForRoot vs ForChild


  • ForRoot: Use in root modules like app.modules. It creates a module that contains all the other directives, given routes and other router service itself.
  • ForChild: Use in child modules. It creates a module that contains all the other directives, given routes but does not include router service.

» What is resolver in Angular

  • Resolver basically an intermediator service, which can be executed when a link has been clicked and before a component is loaded.
  • Resolvers basically get the data for you first and then it allows you to route to the component. 

» JavaScript Mutable and Immutable data structure

https://benmccormick.org/2016/06/04/what-are-mutable-and-immutable-data-structures-2

» Angular change detection

https://alligator.io/angular/change-detection-strategy/

» More Interview Questions:

Frequently asked Angular interview questions & answers
Web Developer interview questions & answers
https://github.com/sudheerj/angular-interview-questions#what-is-the-difference-between-angularjs-and-angular


HTML

» What are some of the key new features in HTML5?

  • Improved support for embedding graphics, audio, and video content via the new canvas, audio, and video tags.
  • Extensions to the JavaScript API such as geolocation and drag-and-drop as well for storage and caching.
  • Introduction of “web workers”.
  • Several new semantic tags were also added to complement the structural logic of modern web applications. These include the main, nav, article, section, header, footer, and aside tags.
  • New form controls, such as calendar, date, time, email, url, and search

» What is Semantic Elements in HTML and what are the advantages of it

Semantic elements clearly describes it's meaning in machine and human readable way. It accurately describes purpose of an element and the type of content within that element.
  • <article>
  • <aside>
  • <details>
  • <figcaption>
  • <figure>
  • <footer>
  • <header>
  • <main>
  • <mark>
  • <nav>
  • <section>
  • <summary>
  • <time>

Following are the benefits of semantic elements:
  1. It makes our code clearer hence we can easily maintain it.
  2. It improves the SEO (Search Engine Optimization) of application. SEO algorithms uses it to better understand the page.
  3. Help screen readers to read the site well.

» What is a Web Worker?

  • A web worker is a JavaScript running in the background, without affecting the performance of the page.
  • A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

» Block vs Inline vs Inline-Block elements in HTML

  • Block Elements: 
  • Acquires full width of web page if width is not defined.
  • Blocks out any elements from sitting next to it on left or right.
  • Can have width, height and margin.
  • Ex: <div>, <p>, <h1> to <h6>, <ol>,<ul>,<li>, <form>
  • Inline Elements:
  • Take as much width as needed to display contents of the element.
  • Allow any other elements to sit to left or right.
  • Cannot have width, height and vertical margin.
  • Ex: <span>,<img>,<a>
  • Inline Block Elements:
  • Allow any other elements to sit to left or right.
  • Can have width and height and vertical margin.

» Local Storage vs Session Storage vs Cookies

  • Local Storage:
  • No expiry date.  Persist until explicitly deleted.
  • 5MB Storage
  • Can be only read on client side
  • Data not transferred for every HTTP request
  • Session Storage:
  • Stores data only for a session. Data will get removed when the browser or tab is closed.
  • 5MB Storage
  • Can be only read on client side
  • Data not transferred for every HTTP request
  • Cookies:
  • We can set expiration time for each cookie.
  • 4KB Storage
  • Can be read on Server side and client side
  • Data transferred for every HTTP request
Example Local Storage:
Example:

// set value in local storage object
localStorage.setItem('sport','cricket');
// Here, key is 'sport' and value is 'cricket'

// get the value from key
localStorage.getItem('sport');

// remove item
localStorage.removeItem('sport');

//delete all from local storage
localStorage.clear();

Example Session Storage:
// set value in session storage object
sessionStorage.setItem('sport','cricket');

Here, key is 'sport' and value is 'cricket'

// get the value from key
sessionStorage.getItem('sport');

// remove item
sessionStorage.removeItem('sport');

//delete all from session storage
sessionStorage.clear();

Example Cookies (In PHP):
<?php
// Syntax:
// setcookie(name, value, expire, path, domain, secure, httponly);

$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

» How do you indicate the character set being used by an HTML5 document?

In HTML5, the encoding used can be indicated with the charset attribute of a "meta" tag inside the document’s "head" element:

<!DOCTYPE html>
<html>
<head>
...
<meta charset="UTF-8">
...
</head>
...
</html>

» What happens when you remove doctype from html page?

https://medium.com/@heitorhherzog/what-happens-when-you-remove-doctype-from-the-html-page-b062e6a0beec

» Briefly describe the correct usage of the following HTML5 semantic elements: <header>, <article>, <section>, <footer>?

The <header> element is used to contain introductory and navigational information about a section of the page. This can include the section heading, the author’s name, time and date of publication, table of contents, or other navigational information.

The <article> element is meant to house a self-contained composition that can logically be independently recreated outside of the page without losing it’s meaining. Individual blog posts or news stories are good examples.

The <section> element is a flexible container for holding content that shares a common informational theme or purpose.

The <footer> element is used to hold information that should appear at the end of a section of content and contain additional information about the section. Author’s name, copyright information, and related links are typical examples of such content.

CSS

» What is position property in CSS?

The position property specifies the type of positioning method used for an element. There are four different position values: 1) Static 2) Relative 3) Fixed 4) Absolute

Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.
  • Static: HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, and right properties. An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:
  • Relative: An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.
  • Fixed: An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.
  • Absolute: An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

» What is CSS Image Sprite?

CSS Spriting is a technique used to limit the number of HTTP requests generated by a web page. This is done by combining multiple images into one image and using the CSS background-position property.

Other

» API vs Web Services

See Answer

» What is payment gateway and how it works?

Ref-1
Ref-2

» Web Application Security

Web application security is a branch of Information Security that deals specifically with security of websites, web applications and web services. At a high level, Web application security draws on the principles of application security but applies them specifically to Internet and Web systems. Typically web applications are developed using programming languages such as PHP, Java EE, Java, Python, Ruby, ASP.NET, C#, VB.NET or Classic ASP.
See more..

» What is XML?

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format which is both human-readable and machine-readable.

» What is SOAP (Simple Object Access Protocol) ?

SOAP is a communication protocol which is designed to communicated via internet. It provides data transport for Web Services. It is the XML way of defining what information gets sent and how.

» What is REST?

REpresentational State Transfer. It describes how one system can communicate state with another. One example would be the state of a product (its name, description etc) represented as XML, JSON, or plain text. REST (REpresentational State Transfer) is a simple stateless architecture that generally runs over HTTP. REST is often used in mobile applications, social networking Web sites, mashup tools and automated business processes.

» What is JSON?

JSON stands for JavaScript Object Notation. It is syntax for storing and exchanging data. JSON uses JavaScript syntax, but the JSON format is text only, just like XML. JSON is much simpler than XML. JSON has a much smaller grammar and maps more directly onto the data structures used in modern programming languages. JSON is not extensible because it does not need to be. JSON is not a document markup language, so it is not necessary to define new tags or attributes to represent data in it. For JavaScript, this is a no-brainer, as JSON is actual JavaScript code, and thus much more "lightweight" for a JavaScript parser to process.

» What is AJAX (Asynchronous JavaScript and XML)?

AJAX is about updating parts of a web page, without reloading the whole page. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

» List down some HTTP methods

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • PATCH
  • OPTIONS
Reference: 7 HTTP methods every web developer should know and how to test them