Monday, September 29, 2014

Database Design & Performance Tuning interview questions and answers

1. What is Normalization?

Keyword:
reduce redundancy, divide large tables to smaller tables, create relationships between tables.

Answer:
Normalization is the process of organizing the fields and tables of a relational database to minimize redundancy. Normalization usually involves dividing large tables into smaller (and less redundant) tables and defining relationships between them. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database using the defined relationships.

The objectives of normalization are:
a. Free the database of modification anomalies;
b. Minimize redesign when extending the database structure;
c. Make the data model more informative to users;
d. Avoid bias towards any particular pattern of querying.


2. What is First Normal Form?

Keyword:
Each column contains only atomic values

Answer:
First normal form (1NF) is a property of a relation in a relational database. A relation is in first normal form if the domain of each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain.

Let's assume we have the following employee table:
employee_name        telephone
Jack                         123-456-7890
Tom                         123-321-5678, 123-321-5679

In case of an employee has more than one telephone number, the column "telephone" contains more than one value. This design violates 1NF.
To make it comply with 1NF, we can change the employee table as follow:
employee_name        telephone
Jack                         123-456-7890
Tom                         123-321-5678
Tom                         123-321-5679

3. What is Second Normal Form?

Keyword:
1NF + each column depends on the whole candidate key

Answer:
Second normal form (2NF) is normal form higher than 1NF. A table is in 2NF if and only if it is in 1NF and every non-prime attribute of the table is dependent on the whole of a candidate key.

Let's assume we have the following project table containing projects and their participants:
project_id    employee_id   project_name
1             1             Database upgrade
1             3             Database upgrade
2             4             Email System Setup
2             7             Email System Setup
2             9             Email System Setup

This table has a composite primary key [project_id, employee_id]. The non-key attribute is [project_name].
In this case, [project_name] only depends on [project_id], which is only part of the primary key. So this design violates 2NF.

To make it comply with 2NF, we can split the table into two tables:
project table:
project_id    project_name
1             Database upgrade
2             Email System Setup

project_participant table:
project_id    participant
1             1
1             3
2             4
2             7
2             9

4. How to store tree structure in a relational database?

Keyword:
Adjacency list
Materialized Path
Nested Set

Answer:
Generally, there are three ways to store tree structure in the database:
a. Adjacency list
Each record holds a reference (parent_id) to the parent as a foreign key.
For example:
node_id    node_value    parent_id
1               a                   0
2               b                   1
3               c                   1
4               d                   2

b. Materialized Path
Each record stores the full path from the root.
For example:
node_id     node_value     path
1                a                    1
2                b                    1/2
3                c                     1/3
4                d                    1/2/4

c. Nested Set
Number the records according to a tree traversal, which visits each node twice, assigning numbers in the order of visiting, and at both visits. This leaves two numbers for each node, which are stored as two attributes: left_id, right_id.
node_id    node_value    left_id    right_id
1               a                   1            8
2               b                   2            5
3               c                   6            7
4               d                   3            4

5. Give some examples of sql injection.

Answer:
Example 1:  SQL Injection Based on 1=1 is Always True
Let's say we have the following code snippet to build a SQL query to check username and password:
String userName = getUserInput("userName");
String password = getUserInput("password");
String sql = "SELECT * FROM user WHERE user_name= '" + userName + "' AND password =''' + password +"'";
If the user input userName: "a" and password: "a OR 1=1", then the sql query becomes:
SELECT * FROM user WHERE user_name= 'a' AND password= 'a' OR 1=1
Since 1=1 is always true, it will return all rows from the user table.

Example 2: SQL Injection Based on Batched SQL Statements
Let's say we have the following code snippet to get a user:
String userId = getUserInput("userId");
String sql = "SELECT * FROM user WHERE user_id=" + userId;
If the user input the string: "1; DROP table user",  then the sql query becomes:
SELECT * FROM user WHERE user_id=1; DROP table user

6. How to prevent SQL injection attacks?

Answer:
a. Reduce the attack surface. Ensure that all excess database privileges are revoked and that only those routines that are intended for end-user access are exposed. Though this does not entirely eliminate SQL injection vulnerabilities, it mitigates the impact of the attacks.

b. Avoid dynamic SQL with concatenated input. Dynamic SQL built with concatenated input values presents the easiest entry point for SQL injections. Avoid constructing dynamic SQL this way.

c. Use Parameterized statements. Parameterized statements, like JDBC PreparedStatement, eliminate the possibility of SQL injections and enhance performance.

d. Filter and sanitize input. Assume all user-submitted data is evil and validate and sanitize everything.

7. What is query execution plan?

Keyword:
an ordered set of steps used to access data,
SQL Query Analyzer, EXPLAIN PLAN statement

Answer:
A query execution plan is an ordered set of steps used to access data in a RDBMS. Since SQL is declarative, there are typically a large number of alternative ways to execute a given query, with widely varying performance. When a query is submitted to the database, the query optimizer evaluates some of the different, correct possible plans for executing the query and returns what it considers the best alternative. Because query optimizers are imperfect, database users and administrators sometimes need to manually examine and tune the plans produced by the optimizer to get better performance.

A given database management system may offer one or more mechanisms for returning the plan for a given query. Some packages feature tools which will generate a graphical representation of a query plan, such as SQL Query Analyzer in SQL Server. Another mechanism for retrieving the query plan involves querying a virtual database table after executing the query to be examined, such as the EXPLAIN PLAN statement in Oracle.

8. Explain the general steps of database performance tuning.

Keyword:
Business Rules -> Data Design -> Application Design -> DB Logical Structure -> SQL Statements -> Query Plan -> Memory Allocation -> I/O and Storage -> Resource Contention -> OS

Answer:
Step 1. Tune the Business Rules
For optimal performance, you may need to adapt business rules. These concern the high-level analysis and design of an entire system.

Step 2. Tune the Data Design
In the data design phase, you need to determine what data is needed by your applications and consider what relations are important, and what their attributes are, and how to structure the information to best meet performance goals. For example, in this step, you need to determine the primary and foreign key indexes.

Step 3. Tune the Application Design
Business executives and application designers should translate business goals into an effective system design. Business processes concern a particular application within a system, or a particular part of an application.

Step 4. Tune the Logical Structure of the Database
This step primarily concerns fine-tuning the index design to ensure that the data is neither over- nor under-indexed. For example, you may need to create additional indexes to support the application.

Step 5. Tune Database Operations
In this step, you may need to tune your SQL statements to take full advantage of the SQL language and RDBMS specific features designed to enhance application processing.

Step 6. Tune the Access Paths
In this step, you may need to use query execution plan tools to analyze your SQL statements to determine the best query plan.

Step 7. Tune Memory Allocation
In this step, you may need to detect database memory allocation issues and tune memory allocation strategies.

Step 8: Tune I/O and Physical Structure
Tuning I/O and physical structure involves distributing data, storing data in data blocks for best access, creating extents large enough for your data, etc.

Step 9: Tune Resource Contention
Take care to reduce the following types of contention: Block contention, Shared pool contention, Lock contention, Latch contention, etc.

Step 10: Tune the Underlying Platform
In the last step, you may need to tune the underlying OS performance.

More Database Design & Performance Tuning interview questions and answers: SQL Interview Notes

  • What is Denormalization?
  • What is Third Normal Form?
  • What is Referential Integrity?
  • How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
  • Give some examples of optimize SQL query statements?
  • What is full table scan? When to use it and how to avoid it?
  • Give some tips on creating proper index?
  • Explain general guidelines that determine when to use clustered index and non-clustered index?
  • What is the advantage and disadvantage of storing binary data in database?
  • What is Database Partitioning?
  • ......

SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  




JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play


Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.

Advanced SQL interview questions and answers

1. What is View?

Keyword:
virtual table, does not contain actual data.
contains columns and rows from one or more tables.

Answer:
A View is a virtual table that contains columns and rows from one or more tables. A view does not contain actual data, it is a set of queries that are applied to one or more tables that is stored within the database as an object. After creating a view from some table(s), it used as a reference of those tables and when executed, it shows only those data which are already mentioned in the query during the creation of the View.

2. How to set auto increment column in SQL?

Answer:
In SQL Server, we use the IDENTITY keyword:
CREATE TABLE employee (
    employee_id int IDENTITY(1,1) PRIMARY KEY,
    first_name varchar(64) NOT NULL,
    last_name varchar(64)
);

In MySQL, we use the AUTO_INCREMENT keyword:
CREATE TABLE employee (
    employee_id int NOT NULL AUTO_INCREMENT,
    first_name varchar(64) NOT NULL,
    last_name varchar(64),
    PRIMARY KEY(employee_id)
);

In Oracle, we need to create a sequence and then use it in DML:
CREATE SEQUENCE seq_employee MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;

INSERT INTO employee(employee_id, first_name, last_name)
VALUES (seq_employee.NEXTVAL,'Jack','Smith’);


3. What are the advantages and disadvantages of using stored procedure?

Keyword:
Reduce server overhead, Reduce network traffic and latency, Encapsulate business logic, Delegate access-rights, Protect against SQL injection attacks
vendor-specific, lack of tool support, track versions.

Answer:
Advantages:
a. Reduce server overhead. Stored procedure statements are stored directly in the database, which may remove all or part of the compilation overhead. Stored procedure execution plans also can be reused and cached.
b. Reduce network traffic and latency. Stored procedures run directly within the database engine and have direct access to the data being accessed, which can reduce network communication costs.
c. Encapsulate business logic. Stored procedures allow programmers to embed business logic as an API in the database, which can simplify data management and reduce the need to encode the logic elsewhere in client programs. The database system can ensure data integrity and consistency with the help of stored procedures.
d. Delegate access-rights. Stored procedures can be granted access rights to the database that users who execute those procedures do not directly have.
e. Protect against SQL injection attacks. Stored procedure parameters will be treated as data even if an attacker inserts SQL commands. Also, some DBMSs will check the parameter's type.

Disadvantages:
a. Stored procedure languages are quite often vendor-specific. Switching to another vendor's database most likely requires rewriting any existing stored procedures.
b. Tool support for writing and debugging stored procedures is often not as good as for other programming languages.
c. Changes to stored procedures are more difficult to keep track of within a version control system than other code. Changes must be reproduced as scripts to be stored in the project history to be included, and differences in procedures can be more difficult to merge and track correctly.


4.  Explain the general steps of using Cursor in SQL.

Answer:
To use cursors in SQL, there are the following steps:
a. Declare a cursor
DECLARE cursor_employee CURSOR FOR SELECT employee_id, first_name, last_name FROM employee;

b. Open the cursor
OPEN cursor_employee;

c. Fetch the data into local variables as needed from the cursor, one row at a time
FETCH cursor_employee INTO ......;

d. Close the cursor
CLOSE cursor_employee;

5. What is Trigger?

Keyword:
auto execute in response to certain events: INSERT, DELETE or UPDATE

Answer:
A trigger is procedural code that is automatically executed in response to certain events (such as INSERT, DELETE or UPDATE) on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database.

For example, when a new record is added to the employee table, new records should also be created in the tables of the taxes, vacations and salaries.

6. What are the differences between Triggers and Stored Procedures?

Answer:
a. Stored procedures can be explicitly called and executed, while triggers can only be executed when an event (insert, delete, and update) is fired on the table on which the trigger is defined.
b. Stored procedures can be scheduled through a job, while triggers cannot be scheduled.
c. Stored procedure can take input parameters, while triggers cannot.
d. Stored procedures can return values, while triggers annot return a value.
e. Transaction statements like begin transaction, commit transaction, and rollback can be used inside stored procedures, but cannot be used inside triggers.

7. What is ACID?

Keyword:
Atomicity, Consistency, Isolation, Durability

Answer:
ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably.

Atomicity:
A transaction must be an atomic unit of work; either all of its data modifications are performed, or none of them is performed.

Consistency:
When completed, a transaction must leave all data in a consistent state. For example, all rules must be applied to the transaction's modifications to maintain all data integrity.

Isolation:
Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either recognizes data in the state it was in before another concurrent transaction modified it, or it recognizes the data after the second transaction has completed, but it does not recognize an intermediate state.

Durability:
After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

8. What is Two-Phase Commit?

Keyword:
ensure the integrity of data in a distributed transaction
commit-request phase, commit phase

Answer:
Two-Phase Commit (2PC) is designed to ensure the integrity of data in a distributed transaction.
Two-Phase Commit mechanism consists of two phases:
a. The commit-request phase (or voting phase), in which a coordinator process attempts to prepare all the transaction's participating processes (named participants) to take the necessary steps for either committing or aborting the transaction and to vote, either "Yes": commit (if the transaction participant's local portion execution has ended properly), or "No": abort (if a problem has been detected with the local portion).
b. The commit phase, in which, based on voting of the participants, the coordinator decides whether to commit (only if all have voted "Yes") or abort the transaction (otherwise), and notifies the result to all the participants. The participants then follow with the needed actions (commit or abort) with their local transactional resources and their respective portions.

More Advanced SQL interview questions and answers: SQL Interview Notes

  • How to create a View from multiple tables?
  • What are the advantages and disadvantages of views?
  • What is Sequence in SQL?
  • What is Cursor in SQL?
  • What is the difference between Stored Procedure and Function in SQL?
  • Explain some ways to optimize stored procedures.
  • How to invoke a trigger on demand?
  • What is a Transaction in SQL?
  • What is Lock in SQL?
  • What is Isolation Level in SQL?
  • ......

SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  




JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play


Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.

SQL DDL & DML interview questions and answers

1. What is the difference between TRUNCATE, DELETE and DROP?

Keyword:
DELETE removes some or all rows based on WHERE clause, can ROLLBACK;
TRUNCATE removes all rows, cannot ROLLBACK;
DROP removes a table, cannot ROLLBACK.

Answer:
DELETE is a DML statement used to remove some or all rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Delete operation will cause all DELETE triggers on the table to fire.

TRUNCATE is a DDL statement used to remove all rows from a table. TRUNCATE operation cannot be rolled back and no triggers will be fired, so it is faster and doesn't use as much undo space as a DELETE.

DROP is a DDL statement used to remove a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. DROP operation cannot be rolled back.


2. What is the difference between WHERE clause and HAVING clause?

Keyword:
HAVING specifies a search condition for an aggregate, used after a GROUP BY.

Answer:
WHERE clause is used to specify a search condition for the rows returned. WHERE can be used with SELECT, UPDATE and DELETE. WHERE is used before a GROUP BY clause.
HAVING clause is used to specify a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used after a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

An example of using WHERE without GROUP BY: get all departments whose department id is greater than 2
SELECT department_id, department_name
FROM departments
WHERE department_id > 2

An example of using HAVING and aggregation function: get all departments with sales greater than $1000
SELECT department, SUM(sales)
FROM orders
GROUP BY department
HAVING SUM(sales) > 1000;

3. How to find all employees containing the word "Tom", regardless of whether it was TOM, Tom or tom?

Answer:
Use LIKE operator and UPPER() function to build the WHERE condition:
SELECT * FROM employee WHERE UPPER(employee_name) LIKE '%TOM%'


4. How to find the highest salary in each department from employee table?

Keyword:
MAX, GROUP BY

Answer:
Use MAX function and GROUP BY clause:
SELECT department_id, MAX(salary) AS max_salary FROM employee GROUP BY department_id;


5. How to select TOP n records from a table?

Answer:
In SQL Server, use SELECT TOP N clause:
SELECT TOP n * FROM employee;

In Oracle, use RUWNUM pseudo-column:
SELECT * FROM employee WHERE ROWNUM <= n;

In MySQL / PostgreSQL, use LIMIT N clause:
SELECT * FROM employee LIMIT n;


6. How to convert data types in SQL?

Keyword:
CAST()
CONVERT()

Answer:
To convert an expression of one data type to another, we can use CAST() or CONVERT() function.
The syntax for CAST:
CAST(expression AS data_type [(length)])
The syntax for CONVERT:
CONVERT(data_type [(length)], expression[, style])

For example, the following query find the records that have a 3 in the first digit of their price:
SELECT product_name, price
FROM product
WHERE CAST(price AS int) LIKE '3%';

or:
SELECT product_name, price
FROM product
WHERE CONVERT(int, price) LIKE '3%';

7. How to get department information and department total salary from table employee and department where total salary greater than 10,000?

Keyword:
INNER JOIN + GROUP BY + HAVING

Answer:
Let's assume employee and department table structures are as follow:
employee table: employee_id, first_name, last_name, salary, department_id
department table: department_id, department_name

To get the result, use SUM() function, INNER JOIN, GROUP BY clause and HAVING clause:
SELECT e.department_id, d.department_name, SUM(e.salary)
FROM employee e INNER JOIN department d ON e.department_id = d.department_id
GROUP BY e.department_id
HAVING SUM(e.salary) > 10000;

8. How to add and remove columns in an existing table?

Keyword:
ALTER TABLE tablename ADD COLUMN / DROP COLUMN

Answer:
Use the ALTER TABLE to add and remove columns in an existing table.

For example, to add a new column "department_id" with default value "1" to employee table:
ALTER TABLE employee ADD COLUMN department_id INTEGER DEFAULT 1 NOT NULL;
To remove the column "department_id" from employee table:
ALTER TABLE employee DROP COLUMN department_id;

9. How to find the nth highest record in a table?

Answer:
Let's assume we have an employee table and we need to find the nth highest salary from this table.

In SQL Server, use subquery + DISTINCT + TOP:
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP n salary FROM employee ORDER BY salary DESC) e ORDER BY salary;

In Oracle, use ROW_NUMBER() function:
SELECT salary FROM (SELECT e.salary, row_number() OVER (ORDER BY salary DESC) rn FROM employee e) WHERE rn = n;

In MySQL / PostgreSQL, use LIMIT clause:
SELECT salary FROM employee ORDER BY salary DESC LIMIT n - 1, 1;

10. How to copy data from one table to another table?

Keyword:
INSERT INTO SELECT
SELECT INTO

Answer:
INSERT INTO SELECT statement is used to copy data from one table to an existing table.

For example:
INSERT INTO employee_backup SELECT * FROM employee;
INSERT INTO user (user_name, address) SELECT name, address FROM employee;

SELECT INTO statement is used to copy data from one table to a new table.
For example:
SELECT * INTO employee_backup FROM employee;
SELECT employee_id, employee_name INTO employee_backup FROM employee WHERE department_id = 1;

More SQL DDL & DML interview questions and answers: SQL Interview Notes

  • What is the difference between EXSITS and IN?
  • How to get the current date and time in SQL?
  • How to combine two columns into one column in a SQL query?
  • How to get department information and department total salary from table employee and department?
  • How to find duplicate records in a table?
  • How to create FOREIGN KEY Constraint on a table?
  • How to create an index on a table?
  • How to use Subquery with EXISTS?
  • ......

SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  




JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play


Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.

SQL Basic Concepts interview questions and answers

1. What is Index?

Keyword:
A data structure that improves the speed of data retrieval operations,
Avoid full table scan,
Need extra storage space.

Answer:
An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.


2. What are the differences between Clustered Index and Nonclustered Index?

Keyword:
Clustered Index determines the physical storage order of records.
Nonclustered Index stores the column's value and a pointer to the actual record.
One clustered index per table, multiple nonclustered indexes per table.

Answer:
Clustered indexes sort and store the records in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the records themselves can be sorted in only one order.
The only time the records in a table are stored in sorted order is when the table contains a clustered index. If a table has no clustered index, its records are stored in an unordered structure called a heap.

Nonclustered indexes have a structure separate from the records. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the record that contains the key value. There can be more than one nonclustered index per table.

Clustered indexes are faster to read than non clustered indexes as records are physically stored in index order. Nonclustered indexes are quicker for insert and update operations than a clustered index.

3. What is the difference between Primary Key Constraint and Unique Constraint?

Keyword:
A table can have multiple unique constraints, only one primary key.
unique constraints allows NULL value.

Answer:
You can use unique constraints to make sure that no duplicate values are entered in specific columns that do not participate in a primary key. Although both a unique constraint and a primary key constraint enforce uniqueness, use a unique constraint instead of a primary key  constraint when you want to enforce the uniqueness of a column, or combination of columns, that is not the primary key.
Multiple unique constraints can be defined on a table, whereas only one primary key constraint can be defined on a table.
Also, unlike primary key constraints, unique constraints allow for the value NULL. However, as with any value participating in a unique constraint, only one null value is allowed per column.
A unique constraint can be referenced by a foreign key constraint.


4. What is INNER JOIN?

Keyword:
return only matched rows in both tables

Answer:
INNER JOIN is a commonly used join operation. It returns all rows from both tables only when there is a match between the columns. If there are rows in one table that do not have matches in other table, these records will NOT be returned.

For example, a INNER JOIN query on table employee and table department:
SELECT * FROM employee
INNER JOIN department
ON employee.department_id = department.department_id;


5. What is LEFT OUTER JOIN?

Keyword:
return left table all rows + right table matched rows

Answer:
LEFT OUTER JOIN (or simply LEFT JOIN) returns all rows from the left table, with the matching rows in the right table. For the unmatched rows in the left table, the value for each column of the right table is NULL.

For example, a LEFT OUTER JOIN query on table employee and table department:
SELECT * FROM employee
LEFT OUTER JOIN department
ON employee.department_id = department.department_id;


6. What is RIGHT OUTER JOIN?

Keyword:
return right table all rows + left table matched rows

Answer:
RIGHT OUTER JOIN (or simply RIGHT JOIN) returns all rows from the right table, with the matching rows in the left table. For the unmatched rows in the right table, the value for each column of the left table is NULL.

For example, a RIGHT OUTER JOIN query on table employee and table department:
SELECT * FROM employee
RIGHT OUTER JOIN department
ON employee.department_id = department.department_id;

7. What is the difference between JOIN and UNION?

Answer:
A Join is used for displaying columns with the same or different names from different tables. The output displayed will have all the columns shown individually.
The UNION set operator is used for combining data from two tables which have columns with the same data type. When a UNION is performed the data from both tables will be collected in a single column having the same data type.

8. What is the difference between CHAR and VARCHAR?

Keyword:
fix length vs variable length

Answer:
CHAR is a fixed-length character data type. The storage size of the CHAR value is equal to the maximum size for this column.
VARCHAR is a variable-length character data type. The storage size of the VARCHAR value is the actual length of the data, not the maximum size for this column.

Use CHAR when the data entries in a column are expected to be the same size, such as phone number column. Use VARCHAR when the data entries in a column are expected to vary considerably in size, such as description column.

More SQL Basic Concepts interview questions and answers: SQL Interview Notes

  • What are DBMS and RDBMS?
  • How do indexes work?
  • What is Foreign Key?
  • What is Check Constraint?
  • What is INTERSECT in SQL?
  • Explain general data types in SQL.
  • What is the difference between TINYINT, SMALLINT, INT and BIGINT?
  • ......

SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  




JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play


Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


Friday, September 26, 2014

JavaScript jQuery questions and answers

1. Explain jQuery main features.

Answer:
jQuery includes the following features:
DOM element selections, traversal and modification;
DOM manipulation based on CSS selectors;
HTML Event methods;
Effects and animations;
AJAX;
Extensibility through plug-ins;
Utilities - such as user agent information, feature detection;
Multi-browser support.

2. How to include jQuery in your web pages?

Keyword:
<script> tag
CDN

Answer:
There are two ways to include jQuery:
a. Download jQuery library and add the jQuery file in HTML <script> tag in <head> section.
For example:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-{version}.min.js"></script>
</head>

b. Include jQuery from a CDN.
For example, use jQuery from Google CDN:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/{version}/jquery.min.js">></script>
</head>

3. What is the different between window.onload and $(document).ready?

Keyword:
window.onload: after all content (css, images) of web page loaded,
$(document).ready: after DOM loaded, before css, images loaded.

Answer:
window.onload is a built-in Javascript event that occurs when all content of the web page has been loaded, including css, images, etc.

$(document).ready is jQuery event that occurs as soon as the HTML DOM is loaded, before css, images and other resources are loaded.

We can add multiple document.ready() function in a page, while we can add only one window.onload function.

4. What is jQuery.noConflict?

Keyword:
relinquish jQuery's control of the $ variable

Answer:
jQuery.noConflict is used to relinquish jQuery's control of the $ variable.
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict().

Example:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
//......
//Use jQuery for jQuery code
jQuery(document).ready(function(){
   jQuery( "div p" ).hide();
});
</script>

5. Explain different selectors in jQuery.

Keyword:
element selector, id selector, class selector, attribute selector, etc

Answer:
jQuery offers a powerful set of selectors for selecting and manipulating HTML element(s).

a. All Selector ("*")
$("*") Selects all elements

b. Element Selector ("element")
Selects all elements with the given tag name.
Example:
$("p") Select all <p> elements on a page

c. ID Selector ("#id")
Selects a single element with the given id attribute.
Example:
$("#book") Select the element with id="book"

d. Class Selector (".class")
Selects all elements with the given class.
Example:
$(".author") Select all elements with class="author"

e. Attribute Selector
Selects elements that have the specified attribute with a value matches a certain matching rule.
Example:
$( "input[value='Submit']" ) Select all input elements that "value" attribute equals "Submit"
$( "input[name^='share']" ) Select all input elements that "name" attribute starts with "share"

f. Child Selector ("parent > child")
Selects all direct child elements specified by "child" of elements specified by "parent". Example:
$( "ul.nav > li" ) Select all list items that are children of <ul class="nav">

6. How to hide/show HTML element in jQuery?

Keyword:
.hide(), .show(), .toggle()

Answer:
Use .hide(), .show(), .toggle() methods. For example:
$("showButton").click(function(){
  $("div").show();
});
$("hideButton").click(function(){
  $("div").hide();
});
$("toggleButton").click(function(){
  $("div").toggle();
});

7. How to update HTML element text in jQuery?

Keyword:
.text(), .html()

Answer:
Use .text() or .html() methods.
.text(): Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
Example:
$("button1").click(function(){
  $("#nav1").text("Question");
});

.html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
Example:
$("button1").click(function(){
  $("#nav1").text("<b>Keyword</b>");
});

8. What are the differences between .empty(), .remove() and .detach() methods in jQuery?

Answer:
.empty(): Remove all child nodes of the set of matched elements from the DOM. This method removes not only child elements, but also any text within the set of matched elements.

.remove(): Similar to .empty(). This method removes the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): Similar to .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

9. How to make Ajax request in jQuery?

Keyword:
.ajax(),
.getJSON(), .load(), .get(), .post()

Answer:
jQuery offers a couple of methods to make Ajax request:

.ajax(): Perform an asynchronous HTTP (Ajax) request. It is jQuery's low-level AJAX implementation. All jQuery AJAX methods use this method internally. This method is mostly used for requests where the other methods cannot be used.
$.ajax({
  type: "POST",
  url: "http://",
  data: data,
  success: function(){...},
  error : function(){...},
  complete : function(){...},
  dataType: "json"
});

.getJSON(): Load JSON-encoded data from the server using a GET HTTP request.

.load(): Load data from the server and place the returned HTML into the matched element.

.get(): Load data from the server using a HTTP GET request.

.post(): Load data from the server using a HTTP POST request.

More JavaScript jQuery interview questions and answers: JavaScript Interview Notes

  • What is the meaning of symbol $ in jQuery?
  • How to use multiple jQuery version on the same page?
  • What is CDN? Why use it?
  • How to handle events in jQuery?
  • What are the differences between .bind(), .live(), .delegate() and .on()?
  • How to add HTML element in jQuery?
  • How to check if an element is empty in jQuery?
  • What are global Ajax event handlers in jQuery?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


JavaScript JSON, XML & Ajax questions and answers

1. Explain JSON data types.

Keyword:
Number, String, Boolean, Array, Object, null

Answer:
JSON has the following basic data types:
a. Number — a signed decimal number that may contain a fractional part and may use exponential E notation.
b. String — a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
c. Boolean — either of the values true or false.
d. Array — an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.
e. Object — an unordered associative array (name/value pairs). Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
f. null — An empty value, using the word null.

Example:
{
    "id": 1,
    "name": "iraylab",
    "active": true,
    "apps": [
        {"name": "JavaScript Interview Notes", "version":"1.0"},
        {"name": "Java Interview Notes", "version":"1.5"}
    ]
}

2. How to convert JSON text to JavaScript object?

Keyword:
eval(),
JSON.parse()

Answer:
There are two ways to convert a JSON text into an object:

var myJSONtext = '{"id":1, "name":"JavaScript Interview Notes"}';

a. Use the eval() method:
var myObject = eval('(' + myJSONtext + ')');

b. Use JSON object and its parse() method:
try{
    var myObject = JSON.parse(myJSONtext);
} catch(e){
    console.log("Parse error:", e);
}

3. What is JSONP?

Answer:
JSONP (JSON with padding) is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on <script> tags.

JSONP wraps up a JSON response into a JavaScript function and sends that back as a Script to the browser. A script is not subject to the Same Origin Policy and when loaded into the client, the function acts just like the JSON object that it contains.

4. How to parse an XML Document in JavaScript?

Keyword:
Use browser built-in DOM parser

Answer:
All modern browsers have a built-in XML parser. Firefox, Chrome, and IE 9 support DOMParser object. For IE<9, we need to use loadXML() method.

For example:
var xmlStr = "<app><title>JavaScript Interview Notes</title><author>iraylab</author></app>";
var xmlDoc;
if (window.DOMParser) {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"application/xml");
}
else { // Internet Explorer < 9
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.loadXML(txt);
}

5. How to manipulate XML Document in JavaScript?

Keyword:
XMLDocument object

Answer:
XMLDocument object is a container object for an XML document, it provides a series of methods manipulate XML Document.

a. To create a new empty XMLDocument object, use the createDocument method;
b. To build an XMLDocument object from a string, use the DOMParser object. In IE<9, use loadXML method;
c. To build an XMLDocument object from a file or from a response of an HTTP request, use the XMLHttpRequest object and its responseXML property;
d. To get the root element of an XML document, use the documentElement property;
e. To retrieve an element in an XML document, use the firstChild, lastChild, nextSibling and previousSibling properties, the getElementsByTagName method and the childNodes collection.

6. What is Ajax?

Keyword:
Asynchronous JavaScript and XML,
XMLHttpRequest,
XML, JSON

Answer:
Ajax is Asynchronous JavaScript and XML. Ajax is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications.

Ajax uses the XMLHttpRequest object to communicate with server-side scripts. It can make requests to the server and update portions of a page without reloading the whole page.

Ajax can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files.

7. What is XMLHttpRequest?

Answer:
XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script.  XMLHttpRequest is used heavily in AJAX programming.

In JavaScript, XMLHttpRequest is an object. XMLHttpRequest makes sending HTTP requests very easy.  You simply create an instance of XMLHttpRequest, open a URL, send the request and handler the response when readyState changes.

8. How to make cross-browser Ajax request using XmlHttpRequest?

Keyword:
new XMLHttpRequest()
new ActiveXObject("Microsoft.XMLHTTP") for IE

Answer:
Modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object, we can create XMLHttpRequest object directly. For old versions of Internet Explorer (IE5 and IE6), we need to create an ActiveX Object.

//Create cross-browser XmlHttpRequest instance:
var xhr;
if(window.XMLHttpRequest) { // Modern browsers, like IE8, firefox, etc
    xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){ // for IE 6
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
   
if(xhr) {
    //Register or define callback function:
    xhr.onreadystatechange = function(){
        if(xhr.readyState==4 && xhr.status==200) {
           //handle response
        }
    }
    //Send request:
    xhr.open("GET", "http://www.iraylab.com/sample", true);
    xhr.send();
}

More JavaScript JSON, XML & Ajax interview questions and answers: JavaScript Interview Notes

  • What is JSON?
  • Can you add comments to JSON?
  • How to convert JavaScript object to JSON text?
  • What are the difference between JSON and XML?
  • List some technologies used by Ajax?
  • What are the advantages and disadvantages of using Ajax?
  • Explain XMLHttpRequest object common properties.
  • Explain different type of ready state in XMLHttpRequest object.
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Thursday, September 25, 2014

JavaScript Function, Scope & Closure questions and answers

1. What is Scope in JavaScript?

Keyword:
global scope, local scope

Answer:
In JavaScript, scope refers to the region of your code in which it is defined.
Variables declared outside of a function definition are global variables and have global scope;
Variables declared within a function are local variables and have local scope. Function parameters also count as local variables and have local scope.

For example:
var scope = "global";         // Declare a global variable
function checkscope() {
    var scope = "local";      // Declare a local variable with the same name
    return scope;             // Return the local value, not the global one
}
checkscope()                  // => "local"

2. Explain JavaScript Scope Chain.

Answer:
In JavaScript, every chunk of code (global code or functions) has a scope chain associated with it. This scope chain is a list or chain of objects that defines the variables that are “in scope” for that code. When JavaScript needs to look up the value of a variable x, it starts by looking at the first object in the chain. If that object has a property named x, the value of that property is used. If the first object does not have a property named x, JavaScript continues the search with the next object in the chain. If the second object does not have a property named x, the search moves on to the next object, and so on. If x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a ReferenceError occurs.

In top-level JavaScript code, the scope chain consists of a single object: the global object. In a non-nested function, the scope chain consists of two objects: the object that defines the function, and the global object. In a nested function, the scope chain has three or more objects.

3. What is the difference between var x = 1 and x = 1?

Answer:
var x = 1 declares variable x in current scope. If the declaration is in a function, x is a local variable. If the declaration is outside of function, x is a global variable.

x = 1 tries to resolve x in the scope chain: if found, it performs assignment. If not found, it creates x property on a global object.

4. What are Function Scope and Hoisting?

Keyword:
variables declared within a function are visible before they are declared

Answer:
JavaScript doesn't support block scope, in which variables are not visible outside of the block (within curly braces). Instead, JavaScript uses function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function.

With function scope, all variables declared within a function are visible throughout the body of the function, even visible before they are declared. This feature is called hoisting: JavaScript code behaves as if all variable declarations in a function are “hoisted” to the top of the function.

For example:
var scope = "global";
function f() {
    console.log(scope);  // Outputs "undefined", not "global"
    var scope = "local"; // Variable initialized here, but defined everywhere
    console.log(scope);  // Outputs "local"
}

5. How is the "this" determined in event handler?

Answer:
When the "this" is used in a event handler function, the "this" is set to the element the event fired from.
For example:
//<div class="intro">Intro</div>
var element = document.querySelector('.intro');
var showThis = function () {
  console.log(this);  //"this" refer to <div class="intro">Intro</div>
};
element.addEventListener('click', showThis, false);

When the code is called from an in–line handler, the "this" is set to the DOM element on which the listener is placed.
For example:
<button onclick="alert(this.tagName);">This</button>
The above alert shows "Button"

When the code is called from an inner function, the "this" isn't set and it refers to the global/window object.
For example:
<button onclick="alert((function(){return this}()));">This</button>
The above alert shows "[object window]"

6. What is the difference between call() method and apply() method?

Keyword:
call() requires a parameter list,
apply() requires an array of parameters.

Answer:
call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes the this value within function body.

f.call(o);
f.apply(o);
These two lines equal to:
o.m = f; // Make f a temporary method of o.
o.m(); // Invoke it, passing no arguments.
delete o.m; // Remove the temporary method.

The main difference between them is that apply() lets you invoke the function with arguments as an array; call() requires the parameters be listed explicitly.
f.call(o, 1, 2);
f.apply(o, [1,2]);

f.call(o, a, b, c); // Fixed number of arguments
f.apply(o, arguments); // Forward current function's arguments to o directly

7. What is Closure in JavaScript?

Keyword:
the function defined in the closure remembers the environment in which it was created

Answer:
A closure is a function that refer to independent (free) variables. In other words, the function defined in the closure remembers the environment in which it was created.

A closure is created when an inner function is made accessible from outside of the function that created it. This typically occurs when an outer function returns an inner function.  When this happens, the inner function maintains a reference to the environment in which it was created, which means that it remembers all variables and their values that were in scope at the time.

For example:
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In the above example, add5 and add10 are two closures. They share the same function body definition, but store different environments. In add5's environment, x is 5, while for add10, x is 10.

8. How to emulate private methods with closures?

Answer:
Private methods are methods that can only be called by other methods inside the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.

For example:
var myCounter = (function() {
  // private variable
  var _counter = 0;

  // private method
  function doCount(val) {
    _counter += val;
  }

  return {
    increment: function() {
      doCount(1);
    },
    decrement: function() {
      doCount(-1);
    },
    value: function() {
      return _counter;
    }
  };
})();

console.log(myCounter.value()); /* Prints 0 */
myCounter.increment();
myCounter.increment();
alert(myCounter.value()); /* Prints 2 */
myCounter.decrement();
alert(myCounter.value()); /* Prints 1 */

For the above code, the function returns an object with three methods: increment, decrement and value. They have access to the private method doCount and private variable _counter. But the outer world can not directly access them.

More JavaScript Function, Scope & Closure interview questions and answers: JavaScript Interview Notes

  • Explain the "this" keyword in JavaScript?
  • How is the "this" determined in prototype method?
  • How to find the min/max number in an array?
  • What does Function.prototype.bind() method do?
  • What is the arguments object?
  • What is the difference between setTimeout() and setInterval()?
  • What is Immediately-invoked function expression in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Object-Oriented JavaScript questions and answers

1. What is the difference between Classic Inheritance and Prototypical Inheritance?

Keyword:
Classic Inheritance: class and object
Prototypical Inheritance: object, no class

Answer:
In Classic Inheritance, there are two types of abstraction: class and object. To create an object, first define the structure of the object, using a class declaration, then instantiate the class to create a new object. Objects created in this manner have their own copies of all instance attributes, plus a link to the single copy of each of the instance methods. Java and C# use classic inheritance.

In Prototypical Inheritance, there is only one type of abstraction: object. We create an object directly, instead of defining the structure through a class. The object can be reused by new objects. JavaScript use prototypical inheritance.


2. What are the different ways to create an object in JavaScript?

Keyword:
object literal,
constructor function,
Object.create method

Answer:
There are three typical ways to create an object:

a. Using object literal
An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces.
For example:
var myObject = {
    property1 : "www.iraylab.com",
    property2 : {
       nestedProperty1 : "JavaScript"
    }
};

b. Using constructor function
Define the object type by writing a constructor function. Then, create an instance of the object with new keyword.
For example:
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var myCar = new Car("BMW", "X5", 2014);

c. Using the Object.create method
With ECMAScript 5, we can a static function Object.create() to create an object.
The Object.create() method creates a new object with the specified prototype object and properties: Object.create(prototype [, propertiesObject ])

For example:
var obj = Object.create(null, {
     make: "BMW",
     model: "X5",
     year: 2014
});

3. How to access the properties of an object?

Keyword:
dot notation .
bracket notation []

Answer:
There are two ways to access the properties of an object.

var car = {
    make: "BMW",
    year: 2014
};

a. Using the dot notation: .
var m = car.make; // get property value
car.make = "GM";  // set property new value

b. Using the bracket notation: []
var m = car["make"];
car["make"] = "GM";


4. How to define public and private properties/methods in an object?

Keyword:
private: var
public: this

Answer:
In a JavaScript object, properties/methods defined with var keyword can only be accessed inside the object;
properties/methods defined with this keyword can be accessed from outside the object.
For example:
function Car (maker, model, year) {
    //public properties and methods:
    this.maker = maker;
    this.model = model;
    this.year = year;
    this.getInfo = function() {
        return "Car info: maker=" + this.maker + ", model="+ this.model +", year=" + this.year;
    };
    //private properties and methods:
    var color;
    var getColor = function() {
        return "color=" + color;
    };

    //access a private method inside the object
    this.getDetailedInfo = function() {
        return this.getInfo() + ", " + getColor();
    }
}


5. How to add custom methods and properties to an object?

Keyword:
use prototype

Answer:
To add properties and methods to an object, we can modify its prototype property.

For example:
function Car (maker, model, year) {
    this.maker = maker;
    this.model = model;
    this.year = year
}

//add new property and new method:
Car.prototype.color = "Black";
Car.prototype.getRating = function() {
    return 1;
};


6. How to create a namespace in JavaScript?

Answer:
In JavaScript, there is no the concept of namespace, we can create global object to emulate namespace.

For example, the following code create a namespace "iraylab.JSModule" and create two functions inside this namespace:

var iraylab = iraylab || {};
iraylab.JSModule = {
    add: function(a, b) {
        return a + b;
    },
    subtract: function(a, b) {
        return a -b;
    }
};

7. How to implement inheritance in JavaScript?

Keyword:
use prototype and constructor function

Answer:
JavaScript is a class-free, object-oriented language, we can implement prototypal inheritance by using prototype and constructor function.

The following is an example to implement this kind of inheritance.
a. Define super class:
function Vehicle () {}

b. Define sub class:
function Car (maker, model, year) {
    this.maker = maker;
    this.model = model;
    this.year = year
}

c. Set up inheritance:
Car.prototype = new Vehicle;

d. Extend super class using prototype:
Vehicle.prototype.getInfo = function(){
    console.log("This is a vehicle.");
}

e. Sub class override super class's method:
Car.prototype.getInfo = function() {
    console.log("This is a car.");
};

8. How to implement Singleton Pattern in JavaScript?

Answer:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In JavaScript, we can implement a Singleton as follows:

var Singleton = (function () {
  var instance;

  function init() {

    //define private methods and variables here...
    function privateMethod(){
        console.log( "a private method" );
    }
    var privateVariable = "a private variable";

    return {

      // Public methods and variables
      publicMethod: function () {
        console.log( "a public method" );
      },

      publicProperty: "a public property"
    };
  };

  return {
    // Get the Singleton instance if one exists or create one if it doesn't
    getInstance: function () {
      if ( !instance ) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Use the singleton class:
var mySingleton = Singleton.getInstance();
......

More Object-Oriented JavaScript interview questions and answers: JavaScript Interview Notes

  • What is constructor in JavaScript?
  • How to list all properties of an object itself?
  • How to define static properties and methods in an object?
  • What is the global object in JavaScript?
  • What is prototype in JavaScript?
  • What is the difference of using prototype and "this" to define a method?
  • How to handle error in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play