Interview Questions
Interview Questions
Interview Questions
Q5. What are the advantages of HTTP 2.0 over HTTP 1.1?
Ans. The major advantages are: headers compression, push notification, intelligent packet streaming
management and parallel loading of page elements over a single TCP connection.
Q6. How do you take into account SEO, maintainability, UX, performance, and security when you’re
building a web application?
Ans. Explain how you prioritise your actions as per the requirements of the organisation. If your
organisation handles vital data, then security will be your top priority. If it is a medium-sized online
business, SEO and UX might be your top priority and so on.
Q8. What’s the best way to integrate 5 different stylesheets into a website?
Ans. It usually depends on how the site is laid out. However, in most cases combining the stylesheets
into single a one is the best approach. You can use Gulp to do so.
Q15. What is the difference between null value and undefined value?
Ans. Undefined means a variable has been declared but has not yet been assigned a value. On the other
hand, null is an assignment value.
Q16. What are the web technologies that you are proficient in?
Ans. As already mentioned, you must have expert skills in three technologies: HTML5, CSS3 and
JavaScript. Apart from that, you should be able to have at least some working knowledge of some of
the other technologies like popular frameworks, APIs and database management.
Q17. What are the different types of pop-up boxes available in JavaScript? Explain them.
Ans. There are three types of pop-up boxes:
1. Alert – it just displays a message with an OK button.
2. Confirm – it pops up a confirmation message window with OK and Cancel button.
3. Prompt – it pops up a dialog box asking user input followed confirmation buttons.
Q20. By which mechanism in JavaScript can you detect the operating system on a client machine?
Ans. The operating system on a client system can be known by using the JavaScript property
navigator.appVersion.
The above web developer interview questions and answers will help you to get an understanding of the
type of questions you can expect in such interviews. However, if you need to gain expert-level skills to
clear the technical round of interviews in any organisation, you should enrol in a certification course.
Naukri Learning offers you a variety of online web development courses which you can enrol in and
get certified to improve your chances of clearing an interview and getting a career boost.
Q21. Which one do you use the most, CSS Animations or JavaScript Animations?
Ans. Both. CSS animation and JavaScript animation are the two primary ways of creating web
animations. As per the project requirement and the kind of the desired effect, I have used both of them.
Q22. Have you used Git for pushing live changes on the website?
Ans. Yes, Git is a great help to streamline live updates on the website. For this, I made use of a post-
receive hook. Through this, I was able to copy updates from remote server repo and update it onto the
live site.
Q24. As a web developer, how do you optimise your site’s loading time?
Ans. As a developer, I will optimize the site by –
• Implementing caching
• Minifying CSS, HTML, and JavaScript codes
Q26. Have you gone through our website? Please mention what you didn’t like about the site?
Ans. Now, this is a tricky question and here the interviewer is checking your skills to identify what is
good as per you and as a developer how in-depth knowledge do you have about the site’s
functionality. So, the first thing is that you must visit their website before appearing for the interview
as this will show your interviewer that you are serious about the role and at the same time you are
well-prepared. Next, you need to do is observe some good points about the site from a developer’s
point of view and also make a checklist of pitfalls. Note, please mention only genuine points where
your expertise can be of help.
Q27. How do you handle a client who is unhappy with your team’s web delivery?
Ans. For every company, the client is the king and no one wants to lose his or her clients at any cost.
Therefore, when appearing for a web developer interview round, you must be well prepared as the
recruiter can shoot this question. You can start by narrating any previous incident that is related to
client handling. Define the issues the client was facing, and later narrate the solutions, which you or
your team had performed to help the client. This will let the recruiter know that you have the
capability to handle and nurture clients.
Q29. What will you do when an image or a hyperlink is not displaying correctly?
Ans. Many times it happens that some images are not properly displayed on the page and that severely
affects the SEO and if happens multiple times, it hampers the overall rankings. So, I keep on checking
things like missing href and alt tags.
Q-4. What Are Various Elements That Provide Better Structuring In HTML5?
Following HTML5 elements focus on improving the structuring.
<article> – This element allows to specify an article.
<aside> – It allows to view content other than the page content.
<bdi> – It lets a part of text getting formatted in a different direction from other text.
<command> – It displays a button element which processes a command upon user action.
<details> – It adds additional details that a user can show or hide.
<dialog> – It initializes a dialog box or popup window.
<figure> – This element can show illustrations, diagrams, photos, and code listings.
<figcaption> – It adds a caption for the image specified by a <figure> element.
<footer> – This tag appends a footer to a document.
<header> – This tag inserts a header into a document.
<hgroup> – If a page includes multiple headings, then this tag groups them into a set of <h1>
to <h6> elements.
Q-6. What Does Canvas Mean In HTML? And What Is Its Default Border Size?
Canvas is an HTML5 element which can draw graphics on the fly with the help of JavaScript. The
<canvas> element can only contain graphics. It supports a no. of methods for drawing paths, boxes,
circles, text, and images.
By default, It has no border. However, it allows using CSS to change the border style.
Q-8. Does HTML5 Provide Drag And Drop Facility? How Do You Set An Image As Draggable?
To set an image as draggable, initialize the draggable attribute with true.
<img draggable="true">
<p id="selector">...</p>
<div class="sampleclass">....</div>
Q-7. What Is The Difference Between An ID Selector And The Class Selector?
An ID Selector finds and modifies the style to only a single element whereas a class selector may
apply to any no. of HTML elements.
Q-14. What Is CSS Box Model And What Are Its Components?
The CSS Box Model represents a box that confines every HTML element such as a text box, a menu
or a button. It has primarily four core components.
Margin – It refers to the topmost layer of the box.
Border – The padding and content options work around the Border. Changing the background
color can also affect the Border.
Padding – It defines spacing around the box.
Content – It represents the actual content to be shown.
Q-15. What Are Media Queries In CSS3 And Why Do You Use Them?
Media queries are one of the latest features of CSS3 used to define responsive styles for devices of
different shapes and sizes.
They are the powerful CSS tool which makes it easy to create responsive design for tablets, desktop,
mobiles devices. They can help to adjust the Height, Width, Viewport, Orientation, and Resolution.
@media screen and (min-width: 480px) {
body {
background-color: #ffffff;
}
}
body {
font-family: 'myCustomFont', Fallback, Ariel;
}
Q-3. What Is The Difference Between Undefined Value And Null Value?
<undefined> Vs. <null> value
1. A variable will have <undefined> value if it has a declaration but not assigned any value.
2. A variable will yield a <null> value if assigned with null.
3. <undefined> is a type itself whereas <null> is an object.
4. <undefined> value is set via JavaScript engine whereas null value is set directly in the code.
Q-4. How Do You Change The Style/Class On Any Element From JavaScript?
Following JavaScript will modify the style/class of an HTML element.
document.getElementById(“input”).style.fontSize = “10”;
-or-
document.getElementById(“button”).className = “classname”;
Q-8. What Is The Difference Between <Alert()> And <Confirm()> Popup Boxes?
The <alert()> method displays a message in a popup box and has only one <Ok> button.
But the <confirm()> method asks for confirmation from the user so that it can get the opinion of
visitors. It has two buttons, i.e., <Yes> and <No>.
In short, <alert()> popup is to display the messages to the users whereas the <confirm()> dialog is
useful for knowing the choices of the visitors.
function myFunction() {
var myLocalVar = "I'm Local";
}
B) Global Scope
Declaring a variable anywhere on the page would mean that we can access it from any of the functions
on that page.
var myGlobalVar = "I'm Global";
function myFunction() {
//
//
*/
Q-11. How Do You Distinguish Between An Undefined And Undeclared Variable?
Undefined refers to a variable which has declaration but not initialized yet. However, an undeclared
variable is one which has a reference in the code without being declared.
Example
var iExistButUndefined;
alert(iExistButUndefined); // undefined
alert(iMNotDeclared); // accessing an undeclared variable
Q-12. What Are == And === Operators In JavaScript And How Do They Differ?
== – Equal to operator
=== – Equal value and equal type operator
Both of the above operators belong to the Comparison Operator Category. However, the equality
operator <==> only checks for the value whereas the strict equality operator <===> checks for the
values as well as types.
Q-15. What Is The Mechanism To Detect The Operating System On The Client Machine?
The following JavaScript property gives back the operating system version on the client machine. It
returns the OS version string.
navigator.appVersion
</script>
2. By Creating An Instance Of The Object (Using New Keyword).
The syntax of creating an object:
var objectname=new Object();
Here, the new keyword is used to create the object.
Let’s take an example.
<script>
std.id=1114;
std.name="Ram Bajaj";
std.subject="Physics";
</script>
3. By Using An Object Constructor.
In this method, we create a function with arguments. The value of each of these arguments can be
assigned to the current object by using this keyword.
This keyword refers to the current object.
Let’s take an example of creating an object using the object constructor technique.
<script>
function std(id,name,subject){
this.id=id;
this.name=name;
this.subject=subject;
</script>
Q-2. What Does A Scope Mean In JavaScript?
The scope determines the accessibility of variables, objects, and functions in particular part of your
code.
In JavaScript, the scope is of two types.
1. Global Scope.
A variable defined outside a function comes under the Global scope. Variables defined inside the
Global scope are accessible from any part of the code. Let’s see an example.
var name = 'TechBeamers';
function logName() {
function sampleFunction() {
// Local Scope #1
function sample2Function() {
// Local Scope #2
}
}
// Global Scope
function sample3Function() {
// Local Scope #3
}
// Global Scope
Q-3. What Is <This> In JavaScript?
All the OOPs languages use ‘this’ keyword to refer to an object that is currently instantiated by the
class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies,
with how a function call happens.
Global Scope.
If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’
is the top-level object which represents the document, location, history and a few other useful
properties and methods. Let’s take a sample code.
window.Obj= "I represent the window object";
alert(window.Obj);
function TestFunction() {
TestFunction();
Call Object Methods.
When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It
is similar to any class-based language.
window.Obj = "I'm the window object";
function TestFunction() {
this.Verify1 = function() {
};
TestFunction.prototype.Verify2 = function() {
};
var tf= new TestFunction();
tf.Verify1();
tf.Verify2();
Q-4. What Is The Prototype Property In JavaScript?
Every JavaScript function has a prototype property (by default this property is null), that is mainly
used for implementing inheritance. We add methods and properties to a function’s prototype so that it
becomes available to instances of that function. Let’s take an example that calculates the perimeter of
a rectangle.
function Rectangle(x, y) {
this.x = x;
this.y = y;
Rectangle.prototype.perimeter = function() {
outerFunc("arg1", "arg2");
Q-6. Why Is “Self” Needed Instead Of “This” In JavaScript?
Inner functions in JavaScript have access to all of the variables defined in the outer function. However,
“this” variable is an exception. Since the nested function is just a regular function and not an object
method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following
example.
var aProperty = 'global';
var myObject = {
outerFun: function() {
this.aProperty = 'local';
setTimeout(function() {
}, 1);
};
Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get
a reference to the object, that is available inside the nested function. We assign the object from “this”,
to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by
other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local
object. Following is the sample code.
var myObject = {
outerFun: function() {
this.aProperty = 'local';
setTimeout(function() {
}, 1);
};
Q-7. What Is An Anonymous Function And When Should You Use It?
Anonymous functions are functions that are dynamically declared at runtime. They’re called
anonymous functions because they don’t have a name like normal functions.
We use the function operator to declare an anonymous function, instead of the function declaration.
Also, the function operator can be used to create a new function, wherever it’s valid to put an
expression. For example, we declare a new function to be supplied as an argument to a function call or
to assign a property of another object.
Here’s a typical example of a named function.
function testFunction()
{
alert("Welcome!!");
}
testFunction();
Here’s the same example created as an anonymous function.
var testFunction= function()
{
flyToTheMoon();
Following are the key usage of anonymous functions.
Code brevity.
Use them in
Callbacks, and
Event handlers.
Scope management.
They are useful in the following scenario.
To create a temporary/private scope.
In Closures and Recursions.
Q-8. What Is The Difference Between “==” And “===”?
These are the operators provided by JavaScript – strict equality and Type converting equality.
Strict equality (===) returns true if the values which it is going to compare have the same data type.
Taking an example, “2” will not be equal to 2 i.e. (“2″===2) will return false.
Secondly, Type converting equality (==), automatically converts the variable to value irrespective of
the data type. Taking an example, here “2” will be equal to 2 i.e. (“2″===2) will return true.
Summarizing it, double equal (==) is an autotype converting equality operator while three equals
(===) is a strict equality operator, i.e., it will not convert values automatically.
Q-9. What Are JavaScript Data Types?
JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the
data types in each of the categories.
Primary Data Types.
String
Number
Boolean
Composite Data Types.
Object
Array
Special Data Types.
Null
Undefined
Q-10. What Is Prototypal Inheritance In JavaScript?
Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other
classes.
In JavaScript, the inheritance is prototype-based. It means that there are no classes. Instead, there is an
object that inherits from another object.
JavaScript provides three different types of Prototypal Inheritance.
1. Delegation (I.E., The Prototype Chain).
A delegate prototype is an object that serves as a base for another object. When you inherit from a
delegate prototype, the new object gets a reference to the prototype.
When we try to access any property, it first checks in the properties owned by the object. If that
property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist
there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it
reaches the <Object.prototype> i.e., the root delegate for most of the objects.
2. Concatenative Inheritance (I.E. Mixins, Object.Assign()).
It is the process of inheriting the features of one object to another by copying the source objects
properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the
JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.
3. Functional (Not To Be Confused With Functional Programming).
In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is
called a factory function. Functional inheritance produces an object from a factory and also extends it,
by assigning properties.
Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them
are equally useful in their ability to enable composition. It provides a has-a, uses-a, or can-do
relationship as compared to the is-a relationship created with class inheritance.
Q-11. What Is Asynchronous Programming? Why Is It Important In JavaScript?
In Asynchronous programming, the engine runs in an event loop. On encountering a blocking
operation, a request gets fired, and the code keeps running without blocking for the result. When its
execution completes, and the response is ready, it fires an interrupt, which causes an event handler to
be run, where the control flow continues. In this way, a single program thread can handle many
concurrent operations in asynchronous programming.
The user interface is asynchronous by nature and spends most of the time, waiting for user input to
interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the
server works by waiting for a network request in a loop. Thus, it accepts more incoming requests,
while the first one is getting handled.
It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining
the performance on the server.
Q-12. What Is Variable Typing In JavaScript?
JavaScript is very loosely typed language. It means that the variables are declared without a type. Its
type is determined once a value is assigned to it. It can change as the variable appears in different
contexts.
It’s in contrast to the strongly typed languages that require type declarations.
Consider the following examples.
/* JavaScript Example (loose typing) */
myGlobalList.first = "test";
2. Enclose all of your code in a self-executing method/function so that any variable declared inside
remain in the function scope.
(function(){
var test = "myvar";
})();
Q-22. What Are The Different Objects Used In JavaScript?
JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following
are the objects, used in JavaScript that shows the relationship of one object to another.
Window Object.
It is the topmost object in the hierarchy. It refers to the content area of the browser window that
consists of HTML documents. Each frame is also a window that has some actions inside it.
Document Object.
A Document object represents the HTML document that the window will display. It has various
properties that refer to other objects, which allow access to and modification of content in the
document.
Form Object.
A form object is used to take user data as input for processing. It corresponds to an HTML input form
constructed with the <FORM>…</FORM> tag.
Q-23. What Do We Achieve By Deferring The Loading Of JavaScript?
During the page load operation, by default, the parsing of the HTML code remains paused until the
execution of the script has not stopped.
Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web
page.
By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading
of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed
faster.
In this way, it makes the page load quicker, without the average user even realizing that some
JavaScript load after the DOM has loaded.
Let’s see an example.
<script>
</script>
<script defer="defer">
</script>
<script>
</script>
Here the middle block will execute once the page has loaded even though it appears before the last
block.
Q-24. What Is The Strict Mode In JavaScript?
Strict Mode imposes a layer of constraint on JavaScript. It provides the following enhancements.
JavaScript will throw an error if we try to use the elements of a deprecated language.
To use a variable, it has become mandatory to declare it.
It disallows duplicate property and parameter names.
The eval() method is safer to use, but still considered evil in some cases.
It deprecates the “with” statement.
JavaScript will throw an error if we try to assign a value to a read-only property.
It decreases the global namespace pollution.
To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the
“strict” directive determines its scope. If used at the beginning of the js file, its scope is global.
However, if we declare strict mode at the first line in the function block, its scope restricts to that
function only.
Q.25- What Are Event Handlers In JavaScript And How To Use Them?
JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the
part of the HTML document object model (DOM). An event can take place in one of the following
cases.
Due to user actions on a web page.
<onclick()>, <onmouseover()>, <onkeydown()>
Some events are callbacks triggered by the browser when a page changes its state.
<onload()>, <onunload()>, <onresize()>
Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event.
To use a handler function, we can assign it to the desired event as an attribute of the target HTML
element. Please follow the below example.
<HTML>
<BODY>
<FORM>
</FORM>
</BODY>
</HTML>
Q-26. What Does A JavaScript Function Result When It Has No Return Statement?
If a function doesn’t use the return statement, then it returns undefined as the return value.
However, the browser won’t print anything in its console as it ignores if the expression returns an
undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll
print exact value.
function test(){}
console.log(encodedURI);
Output.
http://www.somedomain.com/how%20to%20make%20a%20website%20using%20javaScript
We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the
encodeURI function is used to encode special reserved characters and other non-ASCII characters in
the URI.
Q-28. How Does The <Array()> Differ From <[]> While Creating A JavaScript Array?
Both the <Array()> and <[]> works almost the same in JavaScript.
If we use them as is (i.e., without any argument) to create an array object, then they will result in an
array object of zero length. Also, if we pass a string or a list of strings as arguments, even then the
result will be similar.
However, they differ when the input argument is of integer type. In that case, the <Array(n)>
statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an
array of size <1> and assign <n> as value to the first element.
Q-29. How Does Variable Hoisting Take Place In JavaScript?
In JavaScript, variable declarations are the first piece of code that executes irrespective of their
location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This
functionality which moves the declaration to the top either inside a function or in the global code is
known as hoisting.
out = 2;
var out;
function myfunc() {
var in = "inside"
// some code
// ...
JavaScript will interpret the above in the following manner.
var out;
out = 2;
function myfunc() {
var in;
// some code
in = "inside";
}
Q-30. How Will You Replace All Occurrences Of A String In JavaScript?
We can use String’s <replace()> method to substitute any string. There are the following two ways to
use this method.
Pass The Input String As A Regular Expression.
str = "ghktestlllltest-sdds"
alert(str)
Use RegExp Class To Create A Regular Expression And Pass It.
String.prototype.replaceAll = function(find, replace) {
};
str = "ghktestlllltest-sdds"
alert(str)
Q-2. What Would Happen If The HTML Document Does Not Contain <!DOCTYPE>?
Answer.
It instructs the Web Browser about the version of HTML used for creating the Web page.
If the developer misses declaring the DOCTYPE information in the code, then new features and tags
provided by HTML5, like <article>, <footer>, and <header> will not be supported. Additionally, the
Browser may automatically go into Quirks or Strict Mode.
Q-5. What Are The Various Elements Provided By HTML5 For Media Content?
Answer.
HTML provides the support of following elements for representing the media content.
<audio> – It defines the sound content.
<video> – It represents the video content that needs to be attached to a Web page.
<source> – This tag defines the source of video and audio.
<embed > – It provides a container for an external application.
<track> – It defines text tracks for video and audio.
Q-6. What Are The New Form Elements Made Available In HTML5?
Answer.
When we want to collect some data from the person visiting our site, we use HTML Forms. An
example is, the user has to enter his name, email id when he registers for the first time.
A form takes input from the site visitor and then posts it to a back-end application such as CGI, ASP
Script or PHP script. The back-end application will then perform required processing on the passed
data based on defined business logic inside the application.
There are various form elements available in earlier version of HTML like, text fields, text area fields,
drop-down menus, radio buttons, checkboxes, etc.
HTML5 provides the support of some new Form elements that are as follows.
<datalist> – It represents a list of pre-defined options for input controls.
<keygen> – It defines a key-pair generator field (for forms).
<output> – It represents the result of the calculation.
Q-7. What Is A Semantic Element In HTML5? Also, Explain The Difference Between Semantic And
Non-Semantic Elements?
Answer.
Semantic elements are one of the new features that are part of HTML5. They intend to help the
developers in quickly creating the page structure.
A semantic element has its meaning expressed to both the browser and the developer. Also, all the
modern browsers support this feature. However, it is possible for a developer to train old browsers to
handle unknown elements.
Here is the list of some of the commonly used HTML5 Semantic Elements.
<article>
<figcaption>
<figure>
<header>
<footer>
<nav>
<section>
<article>
<aside>
<summary>
The Difference – Semantic Vs. Non-Semantic.
Semantic – These elements clearly describe their content like <img>, <form>, <table> etc.
Non-semantic – These elements are without any definition. They don’t describe anything about their
structure such as <span> and <div>.
Q-8. What Are The Various Tags Provided For Better Structuring In HTML5?
Answer.
The various tags provided for better structuring in HTML 5 are:
<article> – This tag defines an article.
<aside> – It defines content other than the page content.
<bdi> – This tag isolates a part of the text for formatting in a different direction, from another
text present there.
<command> – It defines a command button to be invoked by the user.
<details> – It outlines the additional details that a user can hide or view as per choice.
<dialog> – It defines a dialog box.
<figure> – This tag specifies content like illustrations, diagrams, photos, code listings, etc.
<figcaption> – It provides a caption for a <figure> element.
<footer> – This tag defines a footer for a document or a section.
<header> – This tag describes a header for a document or a section.
<hgroup> – When there are multiple levels in a heading, it groups a set of <h1> to <h6>
elements.
Q-10. How Can We Retrieve The Geographical Position Of A User Using HTML5?
Answer.
HTML5 provides the support of Geolocation API to retrieve the location of a user.
We can find out the current position of the user using getCurrentPosition() method of this API.
Q-18. Explain The Key Differences Between LocalStorage And SessionStorage Objects?
Answer.
Following are the key differences between localStorage and sessionStorage objects.
The localStorage object stores the data without an expiry date. However, sessionStorage object
stores the data for only one session.
In the case of a localStorage object, data will not delete when the browser window closes.
However, the data gets deleted, if the browser window closes, in the case of sessionStorage
objects.
The data in sessionStorage is accessible only in the current window of the browser. But the
data in the localStorage can be shared between multiple windows of the browser.
Q-19. What Is The Concept Of Application Cache In HTML5? What Are Its Advantages?
Answer.
HTML5 introduced the concept of Application Cache. It means that a web application is cached, and
is accessible without an internet connection.
Following are the key advantages of Application Cache.
Offline browsing – Users can use the application even when they are offline.
Speed – Cached resources load faster as compared to content that gets
downloaded, directly from the server.
Reduced server load – The browser will only download updated/modified resources from
the server.
Q-21. What Is The Difference Between HTMl5 Application Cache And Regular HTML Browser
Cache?
Answer.
Following are the key differences between the two.
In AppCache, we can define all the assets the browser should cache in a manifest file (even the
entire site). For fetching this content, it is not necessary for the user to have accessed it
previously. In other words, Application Cache can prefetch pages that have not been visited at
all and are thereby unavailable in the regular browser cache. However, the browser cache will
only store the pages (and associated assets) the user has visited actually.
The AppCache allows web apps (and websites) to be made available offline, that too, with the
same speed benefits as the regular browser cache could provide only when the user is online.
Q-23. What Are The New Attributes Provided In HTML5 For <Form>?
Answer.
The new attributes provided in HTML5 for <form> are.
autocomplete
It specifies if a form or an input field should have “autocomplete” feature set as on or off.
If autocomplete is set to on, it enables the browser to fill the values, based on the values that
the user starts to enter.
autocomplete works for input types like text, search, URL, tel, email, password, date pickers,
range, and color.
novalidate
It is a boolean attribute.
Its presence signifies that the form-data should not get validated at the time of submission.
Q-24. What Are The New Attributes Provided In HTML5 For <Input> Element?
Answer.
Following are the new attributes provided in HTML5 for <input>.
autofocus
It is a Boolean attribute.
The presence of this attribute means that an <input> element should automatically come into
focus when the page gets loaded.
form
This attribute specifies about all the forms, to which a particular <input> element belongs.
formaction
This attribute defines the URL of a file, that will process the input control after the form gets
submitted.
This attribute is used along with type=”submit” and type=”image”.
Also, it overrides the action attribute of the <form> element.
formenctype
This attribute defines, the method to encode the form data before submitting it to the server.
It gets used with type=”submit” and type=”image”.
Also, it overrides the enctype attribute of the <form> element.
formmethod
It defines the HTTP method used for sending form related data to the action URL.
It gets used with type=”submit” and type=”image”.
It overrides the method attribute of the <form> element.
formnovalidate
It is a boolean attribute.
It gets used with type= “submit”.
It indicates that the validation of the <input> element, should not be done at the time of
submission.
It overrides the novalidate attribute of the <form> element.
formtarget
It specifies a name or a keyword of the area where response received after submitting the form
will be displayed.
It gets used with type=”submit” and type=”image”.
height and width
It specifies the height and width of an <input> element.
It gets used only with <input type=”image”>.
list
It refers to a <datalist> element, which contains a list of pre-defined options for an <input>
element.
min and max
It specifies the minimum and maximum value for an <input> element.
It works with the following input types, number, range, date, datetime, datetime-local, month,
time, and week.
multiple
It is a boolean attribute.
It specifies that the user is allowed to enter more than one value in the <input> element.
It works with the following input types: email and file.
pattern
It specifies a regular expression with which the value of the <input> element gets compared.
It works with the following input types: text, search, URL, tel, email, and password.
placeholder
It displays a short hint that indicates the expected value of an input field.
It works with the following input types: text, search, URL, tel, email, and password.
required
It is a boolean attribute.
It indicates that it is mandatory to fill the particular field, before submitting the form.
step
It specifies the legal number intervals for an <input> element.
It works with the following input types: number, range, date, datetime, datetime-local, month,
time, and week.
Q-25. What Is The Major Difference Between, Transitional And Strict Doctype?
Answer.
Strict – This DTD contains all HTML components and properties. However, it does NOT
INCLUDE presentational or expostulated components (like text style). It does not permit the
use of Framesets.
Transitional – This DTD contains all HTML components and properties, INCLUDING
presentational and belittled components (like textual style). It does not allow the use of
Framesets.
</body>
</html>
The HTML5 audio tag supports following attributes to direct the look and feel and various
functionalities of the control.
autoplay
It is a boolean attribute. If, the value is set the audio track starts playing automatically. The
System will not wait for data loading to complete.
autobuffer
It is a boolean attribute. If set, the audio will automatically begin buffering, even if the
automatic play is not enabled.
controls
If this attribute is present, it will allow the user to control audio playback, including volume,
seeking, and pause/resume playback.
loop
Setting this boolean attribute would automatically restart the audio from the beginning, once it
reaches to the end.
preload
This attribute specifies that the audio will be loaded at page load, and will be ready to run. If
autoplay is present, this attribute will not work.
src
It represents the URL of the audio to embed. Its presence is optional.
Q-28. What Are The HTML Tags Which Get Deprecated In HTML5?
Answer.
Following are the tags that are deprecated in HTML5.
<basefont>
<big>
<center>
<font>
<s>
<strike>
<tt>
<u>
<frame>
<frameset>
<noframe>
<acronym>
<applet>
<isindex>
<dir>
Some attributes from HTML4 are no longer allowed in HTML5 since their functionality is better
handled by CSS. Below are some of the known attributes that got removed and the corresponding
impacted element.
Attribute Removed Element
rev, charset a, link
longdesc, name img
version html
abbr th
scope td
align all block level elements
background body
hspace, vspace img
bgcolor table, tr, td, th
border, cell padding, cell spacing table
height, width td, th
valign table
Q-29. What Is A Meter Tag? What Is The Difference Between Progress Tag And A Meter Tag?
Answer.
The <meter> tag defines a scalar measurement within a known range or a fractional value. We can
also call it a gauge.
Some of the items that can be represented using <meter> tag are Disk usage, the relevance of a query
result, and so on.
Note: The <meter> tag should not be used to indicate progress (as in a progress bar). For progress
bars, use the <progress> tag.
Following example demonstrates the use of the <meter> tag.
<li><meter min="0" max="100" value="25">25%</meter></li>
The <meter> tag provides the support of the following attributes.
min
It is a number. It specifies the minimum value of the range.
max
It is a number. It specifies the maximum value of the range.
low
It is a number. It defines a range that represents <low> value.
high
It is a number. It defines a range that represents “high” value.
value
It is a number. It is a mandatory element. It defines the current value of the gauge.
optimum
It is a mandatory element with a numeric value. It specifies the optimum, or the best value, for
the element. If this value is higher than the “high” value, this indicates that the higher the
value, the better it is. If it’s lesser than the <low> mark, it means that the lower values are
better. If it is, in between, then it indicates that neither high nor low values are good.
form
It specifies one or more forms that define the <meter> element. It has value form_id.
Q-30. Why Do We Need HTML5 Server-Sent Events?
Answer.
HTML5 Server-Sent Events (SSE) is a new way for the web pages to communicate with the web
server. It enables a webpage to get updates from a server automatically. It was possible earlier also,
but for this, the web page needs to ask if any updates were available. The client makes a request and
waits for the server to respond with data. Once the web server provides its response, the
communication is over.
However, there are some situations, where web pages require a long-term connection with the web
server. A typical example is stock quotes on finance websites where price update happens
automatically. Other examples are news feeds, sports results that run continuously on media websites,
Facebook/Twitter updates and so on.
We can achieve the above, using HTML5 using SSE. It enables a web page to hold an open
connection to the web server so that it can send a response automatically at any time. Thus there’s no
need to reconnect and run the same server script from scratch over and over again.
Receive Server-Sent Event Notifications.
The EventSource interface contains the Server-Sent event API. We need to create an EventSource
object to receive the Server-Sent event notifications. Following is the code for the same.
var source = new EventSource("sse_demo.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
Above code performs following steps.
First, create a new EventSource object, and specify the URL of the page sending the updates
(in this example “sse_demo.php”).
Every time an update arrives, onmessage event gets triggered.
When an onmessage event occurs, it places the received data into the element that has <id =
result>.
Server-Side Code Example.
For the above example to work, we need a server capable of sending data updates. The server-side
event stream syntax is simple. Set the “Content-Type” header to “text/event-stream”. Now you can
start sending event streams. Following is the code (demo_sse.php).
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
Following is the explanation of the above code.
Set the “Content-Type” header to “text/event-stream”.
Specify that the page should not cache.
Output the data to send (Always start with “data: “).
Flush the output data back to the web page.
https://www.wisdomjobs.com/e-university/javascript-advanced-interview-questions.html
PHP Interview Questions updated on Feb 2020
312911
1. Who is the father of PHP ?
Rasmus Lerdorf is known as the father of PHP.
<?php
echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
$browser=get_browser(null,true);
print_r($browser);
?>
5. What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent
HTTP requests. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a
complete functional transaction for the same visitor.
6. How can we register the variables into a session?
<?php
session_register($ur_session_var);
?>
7. How many ways we can pass the variable through the navigation between the pages?
sizeof($array_var)
count($array_var)
9. How can we create a database using php?
mysql_create_db();
strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.
For example:strstr("[email protected]","@") will return "@example.com".
stristr() is idential to strstr() except that it is case insensitive.
CRYPT(), MD5()
The mysql_error() message will tell us what was wrong with our query, similar to the message we would
receive at the MySQL console.
CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any initialization that
the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented languages,
such as C++. The destructor method will be called as soon as all references to a particular object are
removed or when the object is explicitly destroyed or in any order in shutdown sequence.
15. Explain the visibility of the property or method.
The visibility of a property or method must be defined by prefixing the declaration with the keywords public,
protected or private.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.
16. What are the differences between Get and post methods.
Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error
The header() function sends a raw HTTP header to a client.We can use herder()
function for redirection of pages. It is important to notice that header() must
be called before any actual output is seen.
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not
supported. Classes are extended using the keyword 'extends'.
21. How can we encrypt the username and password using php?
Split function splits string into array by regular expression. Explode splits a string into array by string.
For Example:explode(" and", "India and Pakistan and Srilanka");
split(" :", "India : Pakistan : Srilanka");
Both of these functions will return an array that contains India, Pakistan, and Srilanka.
23. How do you define a constant?
Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);
25. What does a special set of tags <?= and ?> do in PHP?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
javascript is a client side scripting language, so javascript can make popups and other things happens on
someone’s PC. While PHP is server side scripting language so it does every stuff with the server.
29. What is the difference between the functions unlink and unset?
30. How many ways can we get the value of current session id?
we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also
require other libraries, depending on which image formats you want to work with.
33. How can we get second of the current time using date function?
<?php
$second = date(“s”);
?>
34. What are the Formatting and Printing Strings available in PHP?
35. How can we find the number of rows in a result set using PHP?
The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for creating
dynamic content, communicating with a database server, handling session etc.
It supports multiple databases. The most commonly used database is MySQL which is also free
to use. Many PHP frameworks are used now for web development, such as CodeIgniter,
CakePHP, Laravel etc.
These frameworks make the web development task much easier than before.
Which means PHP does not require to declare data types of the variable when you declare any
variable like the other standard programming languages C# or Java. When you store any string
value in a variable then the data type is the string and if you store a numeric value in that same
variable then the data type is an Integer.
Sample code:
$var = "Hello"; //String
$var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer:
When the value of a variable is used as the name of the other variables then it is called variable
variables. $$ is used to declare variable variables in PHP.
Sample code:
$str = "PHP";
$$str = " Programming"; //declaring variable variables
echo "$str ${$str}"; //It will print "PHP programming"
echo "$PHP"; //It will print "Programming"
Q #5) What are the differences between echo and print?
Answer:
Both echo and print method print the output in the browser but there is a difference between
these two methods.
echo does not return any value after printing the output and it works faster than the print
method. print method is slower than the echo because it returns boolean value after printing the
output.
Sample code:
echo "PHP Developer";
$n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer:
You have to use PHP command in the command line to execute a PHP script. If the PHP file
name is test.php then the following command is used to run the script from the command line.
php test.php
Sample code:
echo gettype(true).''; //boolean
echo gettype(10).''; //integer
echo gettype('Web Programming').''; //string
echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in PHP?
Answer:
You need to change the value of the max_execution_time directive in the php.ini file for
increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the value as
follows,
max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference' in PHP?
Answer:
When the variable is passed as value then it is called pass variable by value.
Here, the main variable remains unchanged even when the passed variable changes.
Sample code:
function test($n) {
$n=$n+10;
}
$m=5;
test($m);
echo $m;
When the variable is passed as a reference then it is called pass variable by reference. Here,
both the main variable and the passed variable share the same memory location and & is used
for reference.
So, if one variable changes then the other will also change.
Sample code:
function test(&$n) {
$n=$n+10;
}
$m=5;
test($m);
echo $m;
Q #13) Explain type casting and type juggling.
Answer:
The way by which PHP can assign a particular data type for any variable is called typecasting.
The required type of variable is mentioned in the parenthesis before the variable.
Sample code:
$str = "10"; // $str is now string
$bool = (boolean) $str; // $bool is now boolean
PHP does not support data type for variable declaration. The type of the variable is changed
automatically based on the assigned value and it is called type juggling.
Sample code:
$val = 5; // $val is now number
$val = "500" //$val is now string
Q #14) How can you make a connection with MySQL server using PHP?
Answer:
You have to provide MySQL hostname, username and password to make a connection with the
MySQL server in mysqli_connect() method or declaring database object of the mysqli class.
Sample code:
$mysqli = mysqli_connect("localhost","username","password");
$mysqli = new mysqli("localhost","username","password");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer:
Many functions are available in PHP to retrieve the data from the MySQL database.
#1) Enable file_uploads directive
Open php.ini file and find out the file_uploads directive and make it on.
file_uploads = On
#2) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data">
</form>
Sample code:
10 and “10” are equal by values but are not equal by data type. One is a string and one is a
number. So, if condition will be false and print “n is not equal to 10”.
$n = 10;
if ($n === "10")
echo "n is equal to 10";
else
echo "n is not equal to 10"; //This will print
Q #34) Which operator is used to combine string values in PHP?
Answer:
Two or more string values can be combined by using ‘.’ operator.
Sample code:
$val1 = "Software ";
$val2 = "Testing";
echo $val1.$val2; // The output is “Software Testing”
Q #35) What is PEAR?
Answer:
The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of cost. It
contains different types of packages from different developers.
Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer:
Different type of errors can occur in PHP.
Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book details to
add the feature of multiple inheritances in PHP.
interface Isbn {
public function setISBN($isbn);
}
interface Type{
public function setType($type);
}
class bookDetails implements Isbn, Type {
private $isbn;
private $type;
public function setISBN($isbn)
{
$this -> isbn = $isbn;
}
public function setType($type)
{
$this -> type = $type;
}
}
Q #38) What are the differences between session and cookie?
Answer:
The session is a global variable which is used in the server to store the session data. When a
new session creates the cookie with the session id is stored on the visitor's computer. The
session variable can store more data than the cookie variable.
Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE
array. Session values are removed automatically when the visitor closes the browser and cookie
values are not removed automatically.
Sample code:
$DBconnection=mysqli_connect("localhost","username","password","dbname");
$productName = mysqli_real_escape_string($con, $_POST['proname']);
$ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the string?
Answer:
There are three functions in PHP to remove the whitespaces from the string.
trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.
Sample code:
$str = " Tutorials for your help";
$val1 = trim($str);
$val2 = ltrim($str);
$val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer:
A cookie file that is stored permanently in the browser is called a persistence cookie. It is not
secure and is mainly used for tracking a visitor for long times.
The disadvantages of this methods are, it doesn't allow persistence between the sessions and,
the user can easily copy and paste the URL and send to another user.
It is a lightweight PHP extension that uses consistence interface for accessing the database.
Using PDO, a developer can easily switch from one database server to the other. But it does not
support all the advanced features of the new MySQL server.
They both include a specific file but on require the process exits with a fatal error
if the file can’t be included, while include statement may still pass and jump to the
next step in the execution.
$a = '1';
$b = &$a;
$b = "2$b";
What are the main error types in PHP and how do they differ?
(Question provided by Agli Pançi)
Notices – Simple, non-critical errors that are occurred during the script
execution. An example of a Notice would be accessing an undefined variable.
Warnings – more important errors than Notices, however the scripts
continue the execution. An example would be include() a file that does not
exist.
Fatal – this type of error causes a termination of the script execution when
it occurs. An example of a Fatal error would be accessing a property of a non-
existent object or require() a non-existent file.
GET displays the submitted data as part of the URL, during POST this
information is not shown as it’s encoded in the request.
Normally GET is used to retrieve data while POST to insert and update.
Traits are a mechanism that allows you to create reusable code in languages like
PHP where multiple inheritance is not supported. A Trait cannot be instantiated
on its own.
It’s important that a developer knows the powerful features of the language (s)he
is working on, and Trait is one of such features.
No, the value of a constant cannot be changed once it’s declared during the PHP
execution.
All objects in PHP have Constructor and Destructor methods built-in. The
Constructor method is called immediately after a new instance of the class is
being created, and it’s used to initialize class properties. The Destructor method
takes no parameters.
Understanding these two in PHP means that the candidate knows the very basics
of OOP in PHP.
PHP Interview Question #12
Understanding of arrays and array related helper functions is important for any
PHP developer.
How would you declare a function that receives one parameter name hello?
If hello is true, then the function must print hello, but if the function doesn’t
receive hello or hello is false the function must print bye.
(Question provided by Oscar Andrés Monroy Medina )
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
?>
In this question, you can evaluate if the developer knows how to declare a
function and how they would manage the fact of the parameter can or cannot be
on the function call. You can also evaluate if the developer knows the if syntax
and how to print text(echo function).
PHP Interview Question #14
<?php
echo array_sum(explode(',',$input));
?>
<?php
if(empty($_POST['email'])){
?>
In this question, the candidate should be evaluated on his/her knowledge about
forms management and validation. There is not unique answer for this question,
but it must be similar to this one.
your wish is printed, and ballCount is reset to 0. How would you implement
this class?
(Question provided by Oscar Andrés Monroy Medina )
<?php
class dragonBall{
private $ballCount;
$this->ballCount=0;
$this->ballCount++;
if($this->ballCount===7){
$this->ballCount=0;
?>
What are the 3 scope levels available in PHP and how would you define
them?
(Question provided by Merlyn Coslett)
What are getters and setters and why are they important?
(Question provided by Merlyn Coslett)
Getters and setters are methods used to declare or obtain the values of
variables, usually private ones. They are important because it allows for a central
location that is able to handle data prior to declaring it or returning it to the
developer. Within a getter or setter one is able to consistently handle data that
will eventually be passed into a variable or additional functions. An example of
this would be a user’s name. If a setter is not being used and the developer is
just declaring the $userName variable by hand, you could end up with results as
such: "kevin", "KEVIN", "KeViN", "", etc. With a setter, the developer can not only
adjust the value, for example, ucfirst($userName), but can also handle situations
where the data is not valid such as the example where "" is passed. The same
applies to a getter – when the data is being returned, it can be modifyed the
results to include strtoupper($userName) for proper formatting further up the
chain.
What does MVC stand for and what does each component do?
(Question provided by Merlyn Coslett)
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the
view. It’s responsible for interpretation of the data sent by the view and dispersing
that data to the appropriate models awaiting results to pass back to the view.
Very little, if any business logic should be occurring in the controller.
The model’s job is to handle specific tasks related to a specific area of the
application or functionality. Models will communicate directly with your database
or other storage system and will handle business logic related to the results.
The view is passed data by the controller and is displayed to the user.
Overall, this question is worth knowing as the MVC design pattern has been used
a lot in the last few years and is a very good design pattern to know. Even with
more advanced flows that go down to repositories and entities, they still are
following the same basic idea for the Controller and View. The Model is typically
just split out into multiple components to handle specific tasks related to
database data, business logic etc. The MVC design pattern helps draw a better
understanding of what is being used, as a whole, in the industry.
How does one prevent the following Warning ‘Warning: Cannot modify
header information – headers already sent’ and why does it occur in the
first place?
(Question provided by Kordian Bruck)
The candidate should not output anything to the browser before using code that
modifies the HTTP headers. Once the developer calls echo or any other code that
clears the buffer, the developer can no longer set cookies or headers. That is
also true for error messages, so if an error happens before using the header
command and the INI directive display_errors is set, then that will also cause
that error to show.
What are SQL Injections, how do you prevent them and what are the best
practices?
(Question provided by Kordian Bruck)
SQL injections are a method to alter a query in a SQL statement send to the
database server. That modified query then might leak information like
username/password combinations and can help the intruder to further
compromise the server.
To prevent SQL injections, one should always check & escape all user input. In
PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is
often forgotten by inexperienced developers. But there are also many other ways
that users can manipulate variables used in a SQL query through cookies or even
uploaded files (filenames). The only real protection is to use prepared statements
everywhere consistently.
Do not use any of the mysql_* functions which have been deprecated since PHP
5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of
the box. mysqli_* are still an option, but there is no real reason nowadays not to
use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine
or Propel to get rid of writing SQL queries all together and use object-relational
mapping which binds rows from the database to objects in the application.
PHP Interview Question #21
$i = 016;
echo $i / 2;
The Output should be 7. The leading zero indicates an octal number in PHP, so
the number evaluates to the decimal number 14 instead to decimal 16.
If you would want to check for a certain type, like an integer or boolean,
the === will do that exactly like one would expect from a strongly typed language,
while == would convert the data temporarily and try to match both operand’s
types. The identity operator ( ===) also performs better as a result of not having to
deal with type conversion. Especially when checking variables for true/false, one
should avoid using == as this would also take into account 0/1 or other similar
representation.
PHP Interview Question #23
An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-
2 here.
What PSR Standards do you follow? Why would you follow a PSR
standard?
(Question provided by Shawn Mayzes)
One should folow a PSR because coding standards often vary between
developers and companies. This can cause issues when reviewing or fixing
another developer’s code and finding a code structure that is different from yours.
A PSR standard can help streamline the expectations of how the code should
look, thus cutting down confusion and in some cases, syntax errors.
Do you use Composer? If yes, what benefits have you found in it?
(Question provided by Shawn Mayzes)
Using Composer is a tool for dependency management. The candidate can
declare the libraries your product relies on and Composer will manage the
installation and updating of the libraries. The benefit is a consistent way of
managing the libraries depended on so less time is spent managing the libraries.
a)hello
b)infinite-loop
c)hi-hello
d)error
View Answer
Answer:b
Explanation: While condition always gives 1.
2. What will be the output of the following PHP code?
1. <?php
2. $i = "";
3. while ($i = 10)
4. {
5. print "hi";
6. }
7. print "hello";
8. ?>
a) hello
b) infinite loop
c) hihello
d) error
View Answer
Answer: b
Explanation: While condition always gives 1.
3. What will be the output of the following PHP code?
1. <?php
2. $i = 5;
3. while (--$i > 0)
4. {
5. $i++; print $i; print "hello";
6. }
7. ?>
a) 4hello4hello4hello4hello4hello…..infinite
b) 5hello5hello5hello5hello5hello…..infinite
c) no output
d) error
View Answer
Answer: b
Explanation: i is decremented in the while loop in the condition check and then incremented back.
4. What will be the output of the following PHP code?
1. <?php
2. $i = 5;
3. while (--$i > 0 && ++$i)
4. {
5. print $i;
6. }
7. ?>
a) 5
b) 555555555…infinitely
c) 54321
d) error
View Answer
Answer: b
Explanation: As it is && operator it is being incremented and decremented continuously.
5. What will be the output of the following PHP code?
1. <?php
2. $i = 5;
3. while (--$i > 0 || ++$i)
4. {
5. print $i;
6. }
7. ?>
a) 54321111111….infinitely
b) 555555555…infinitely
c) 54321
d) 5
View Answer
Answer: a
Explanation: As it is || operator the second expression is not evaluated till i becomes 1 then it goes into a
loop.
6. What will be the output of the following PHP code?
1. <?php
2. $i = 0;
3. while(++$i || --$i)
4. {
5. print $i;
6. }
7. ?>
a) 1234567891011121314….infinitely
b) 01234567891011121314…infinitely
c) 1
d) 0
View Answer
Answer: a
Explanation: As it is || operator the second expression is not evaluated and i is always incremented, in the
first case to 1.
advertisement
a) 1234567891011121314….infinitely
b) 01234567891011121314…infinitely
c) no output
d) error
View Answer
Answer: c
Explanation: The first condition itself fails thus the loop exists.
8. What will be the output of the following PHP code?
1. <?php
2. $i = 0;
3. while ((--$i > ++$i) - 1)
4. {
5. print $i;
6. }
7. ?>
a) 00000000000000000000….infinitely
b) -1-1-1-1-1-1-1-1-1-1…infinitely
c) no output
d) error
View Answer
Answer: a
Explanation: (–$i > ++$i) evaluates to 0 but -1 makes it enters the loop and prints i.
9. What will be the output of the following PHP code?
1. <?php
2. $i = 2;
3. while (++$i)
4. {
5. while ($i --> 0)
6. print $i;
7. }
8. ?>
a)210
b)10
c)no output
d)infinite loop
View Answer
Answer:a
Explanation: The loop ends when i becomes 0.
10. What will be the output of the following PHP code?
1. <?php
2. $i = 2;
3. while (++$i)
4. {
5. while (--$i > 0)
6. print $i;
7. }
8. ?>
a) 210
b) 10
c) no output
d) infinite loop
View Answer
Answer: d
Explanation: The loop never ends as i is always incremented and then decremented.
1. What is DBMS?
2. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS store the
data into the collection of tables, which is related by common fields between the
columns of the table. It also provides relational operators to manipulate the data
stored into the tables.
3. What is SQL?
SQL stands for Structured Query Language , and it is used to communicate with
the Database. This is a standard language used to perform tasks such as retrieval,
updation, insertion and deletion of data from a database.
4. What is a Database?
Database is nothing but an organized form of data for easy access, storing,
retrieval and managing of data. This is also known as structured form of data
which can be accessed in many ways.
A table is a set of data that are organized in a model with Columns and Rows.
Columns can be categorized as vertical, and Rows are horizontal. A table has
specified number of column called fields but can have any number of rows which is
called record.
Example:.
Table: Employee.
A Unique key constraint uniquely identified each record in the database. This
provides uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But not, in
the case of Unique Key.
There can be many unique constraint defined per table, but only one Primary key
constraint defined per table.
A foreign key is one table which can be related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key
with the primary key of another table.
9. What is a join?
This is a keyword used to query data from more tables based on the relationship
between the fields of the tables. Keys play a major role when JOINs are used.
There are various types of join which can be used to retrieve data and it depends
on the relationship between tables.
Inner Join.
Inner join return rows when there is at least one match of rows between the tables.
Right Join.
Right join return rows which are common between the tables and all rows of Right
hand side table. Simply, it returns all the rows from the right hand side table even
though there are no matches in the left hand side table.
Left Join.
Left join return rows which are common between the tables and all rows of Left
hand side table. Simply, it returns all the rows from Left hand side table even
though there are no matches in the Right hand side table.
Full Join.
Full join return rows when there are matching rows in any one of the tables. This
means, it returns all the rows from the left hand side table and all the rows from the
right hand side table.
The normal forms can be divided into 5 forms, and they are explained below -.
This should remove all the duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.
Meeting all requirements of the first normal form. Placing the subsets of data in
separate tables and Creation of relationships between the tables using primary
keys.
This should meet all requirements of 2NF. Removing the columns which are not
dependent on primary key constraints.
Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.
14. What is a View?
Unique Index.
This indexing does not allow the field to have duplicate values if the column is
unique indexed. Unique index can be applied automatically when primary key is
defined.
Clustered Index.
This type of index reorders the physical order of the table and search based on the
key values. Each table can have only one clustered index.
NonClustered Index.
NonClustered Index does not alter the physical order of the table and maintains
logical order of data. Each table can have 999 nonclustered indexes.
A database Cursor is a control which enables traversal over the rows or records in
the table. This can be viewed as a pointer to one row in a set of rows. Cursor is
very much useful for traversing such as retrieval, addition and removal of database
records.
A DB query is a code written in order to get the information back from the
database. Query can be designed in such a way that it matched with our
expectation of the result set. Simply, a question to the Database.
A subquery is a query within another query. The outer query is called as main
query, and inner query is called subquery. SubQuery is always executed first, and
the result of subquery is passed on to the main query.
Example: When a new student is added to the student database, new records
should be created in the related tables like Exam, Score and Attendance tables.
DELETE command is used to remove rows from the table, and WHERE clause
can be used for conditional set of parameters. Commit and Rollback can be
performed after delete statement.
TRUNCATE removes all rows from the table. Truncate operation cannot be rolled
back.
25. What are local and global variables and their differences?
Local variables are the variables which can be used or exist inside the function.
They are not known to the other functions and those variables cannot be referred
or used. Variables can be created whenever that function is called.
Global variables are the variables which can be used or exist throughout the
program. Same variable declared in global cannot be used in functions. Global
variables cannot be created whenever that function is called.
Constraint can be used to specify the limit on the data type of table. Constraint can
be specified while creating or altering the table statement. Sample of constraint
are.
NOT NULL.
CHECK.
DEFAULT.
UNIQUE.
PRIMARY KEY.
FOREIGN KEY.
Data Integrity defines the accuracy and consistency of data stored in a database. It
can also define integrity constraints to enforce business rules on the data when it
is entered into the application or database.
Clustered index is used for easy retrieval of data from the database by altering the
way that the records are stored. Database sorts out rows by the column which is
set to be clustered index.
A nonclustered index does not alter the way it was stored but creates a complete
separate object within the table. It point back to the original table rows after
searching.
30. What is Datawarehouse?
Cross join defines as Cartesian product where number of rows in the first table
multiplied by number of rows in the second table. If suppose, WHERE clause is
used in cross join then the query will work like an INNER JOIN.
User defined functions are the functions written to use that logic whenever
required. It is not necessary to write the same logic several times. Instead, function
can be called or executed whenever needed.
Scalar Functions.
Inline Table valued functions.
Multi statement valued functions.
Scalar returns unit, variant defined the return clause. Other two types return table
as a return.
Collation is defined as set of rules that determine how character data can be
sorted and compared. This can be used to compare A and, other language
characters and also depends on the width of the characters.
Disadvantage is that it can be executed only in the Database and utilizes more
memory in the database server.
SQL clause is defined to limit the result set by providing condition to the query.
This usually filters some rows from the whole set of records.
A stored procedure which calls by itself until it reaches some boundary condition.
This recursive function or procedure helps programmers to use the same set of
code any number of times.
UNION operator is used to combine the results of two tables, and it eliminates
duplicate rows from the tables.
MINUS operator is used to return rows from the first query but not from the second
query. Matching records of first and second query and other rows from the first
query will be displayed as a result set.
INTERSECT operator is used to return rows returned by both the queries.
ALIAS name can be given to a table or column. This alias name can be referred in
WHERE clause to identify the table or column.
Example-.
Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex.
StudentID
Here, st refers to alias name for student table and Ex refers to alias name for exam
table.
TRUNCATE removes all the rows from the table, and it cannot be rolled back.
DROP command removes a table from the database and operation cannot be
rolled back.
Example -.
45. How can you create an empty table from an existing table?
Example will be -.
Here, we are copying student table to another table with the same structure with
no rows copied.
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
47. How to fetch alternate records from a table?
Records can be fetched for both Odd and Even row numbers -.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1
49. What is the command used to fetch first 5 characters of the string?
Example -.