Interview Questions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 78

Web Development Interview Questions

Q1. What is a pseudo-class?


Ans. It is a CSS technique which sets the style when an element changes its state. E.g. style changes
when mouse hover, different styles for visited or unvisited links, etc

Q2. What is Namespacing in JavaScript?


Ans. It is usually not a good practice to use global variables in programming languages including
JavaScript. However, you may be forced to use global variables sometimes. So, JavaScript introduces
the concept of namespacing which ties down a part of the code and register it with a unique name.

Q3. How can you reduce page loading time?


Ans. These are the following ways you can reduce web page loading time: reduce image size, remove
unnecessary widgets, HTTP compression, placing CSS at the top and script referencing at the bottom
or external files, reduce lookups, minimise redirects and caching.

Q4. What is CORS?


Ans. Cross-Origin Resource Sharing (CORS) is a mechanism that enables different resources on a web
page to be requested from another domain outside the domain from which the request originated.

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.

Q7. What are the new form elements introduced in HTML5?


Ans. The new form elements introduced in HTML5 are:
• <datalist> – specifies a list of options for input controls.
• <keygen> – generates an encryption key.
• <output> – defines the result of an expression.

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.

Q9. What’s the difference between Canvas and SVG?


Ans. Canvas is an HTML5 element which can draw graphics on the fly with the help of JavaScript.
SVG (Scalable Vector Graphics) is used to display vector-based graphics on the web.

Q10. What is the default border size of a Canvas?


Ans. There is no default border size of a Canvas. You can adjust using CSS.

Q11. What is the difference between ID and Class selector?


Ans. ID selector finds and modifies the style to any single element while Class selector can do to any
number of elements.
Q12. What is your preferred development environment?
Ans. This question is not about checking if you are perfect for the same environment as the
organisation works but to measure if you are flexible to work in any environment. So, give them a hint
that you are able to adapt to any environment with the core skills that you have.

Q13. Which are the new APIs provided by HTML5?


Ans. The new APIs are media API, text track API, application cache API, data transfer API, user
interaction API, command API, constraint validation API and history API.

Q14. What are your key responsibilities in your current organisation?


Ans. Are you working in specific development areas? Do you only support the maintenance and
upkeep of a website? Or Are you involved in all major steps in development including fixing bugs? Do
not leave out any responsibilities which you think can help in leveraging your candidacy for the role.

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.

Q18. What is Scope in JavaScript? Name the different types of Scopes.


Ans. The scope defines the accessibility of the functions and variables in an application. There are two
types of scopes: local and global.

Q19. What is the difference between ‘==’ and ‘===’ operators?


Ans. Though both of them belongs to the comparison operator category, the ‘==’ operator checks the
value whereas, the ‘===’ operator checks both the value and the type.

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.

Cases when CSS animations work well:


• When the transitions are simple. For example, toggling within the element states.
• When the UI elements are self-contained. Like in showing a tooltip.

Cases when JavaScript animations work well:


• When advanced animation effects are expected in the project, like bouncing, stop pause, etc.
• When a superior level of control is required, JS animation works well.
• Helpful when drawing in HTML canvas.

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.

Q23. Which web development tools do you use?


Ans. There are several web development tools available and being into the role of a web developer, I
have used multiple of them like:
• GitHub to work together with a team on a particular project.
• CodeKit to minify, combine, and syntax-check in JavaScript.
• JS to structure the web application and even develop a one-page application.
• CodePen to deploy a website and build test cases.
• Grunt for automating repetitive tasks.

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

Q25. How is HTML different from XHTML?


Ans. HTML and XHTML are both known for writing web pages. But, HTML is extended from SGML
tagging whereas XHTML is an application of Extensible Markup Language (XML).
HTML has three components – element tag pair (start tag and end tag), attributes of the element
within the tag, and content in the form of both text and graphics. Whereas XHTML includes only a
single root element which includes lower case elements and the value that is assigned should be
closed, nested, and must be surrounded by quotation marks. Looking at the difference, XHTML is
more expressive when compared to HTML.

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.

Q28. What do you know about HTTP/3?


Ans. HTTP/3 is the new third-generation HTTP standard that was recently made available in late
2019. It is known for its new standards, fast, reliable, and secure connection. HTTP/3 promises faster
web experience as it uses QUIC. This new internet transport protocol introduces first-class citizens.
Brands like Google and Facebook are now using QUIC because of its swift abilities to speed up the
web.

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.

Q30. Do you have any experience in developing multilingual websites?


Ans. It is not necessary that you hold experience in developing multilingual sites but you must know
the basics of how it is done. You can tell the recruiter the process that involves Unicode encoding and
usage of the ‘lang’ attribute.

Q-1. What Are The New DocType And Charset In HTML5?


The DocType element communicates the HTML version to the browser. It usually appears in the first
line of code of an HTML page. Unlike the earlier versions/standards of HTML, DocType has got a
simplified format in HTML5.
<!doctype html>
The CharSet is a new meta tag attribute in HTML5 which configures the character encoding.
<meta charset=”UTF-8″>

Q-2. What All New Form Elements Got Introduced In HTML5?


Here is the list of new form elements available in HTML5.
 <datalist> – It specifies a list of options for input controls.
 <keygen> – This tag generates an encryption key.
 <output> – It defines the result of an expression.

Q-3. Which Of The HTML5 Elements Support Media Content?


Following HTML5 elements supports media content.
 <audio> – It specifies sound content.
 <video> – It links to a video.
 <source> – This tag specified the source of video and audio links.
 <embed> – It acts as a container for external applications.
 <track> – This element defines tracks for video and audio.

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-5. What Is SVG And Why Do You Use It?


SVG is an acronym for Scalable Vector Graphics as recommended by W3C.
 Its purpose is to display the vector-based graphics over the Web.
 The graphics use an XML format.
 SVG graphics are of higher quality and does not lose it even when resized.
 All elements and attributes of SVG support animation.

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-7. How Does Canvas Differ From SVG?


Here are a few points elaborating the differences between Canvas and SVG.
 Canvas depends on the resolution whereas SVG doesn’t.
 It does not allow event handlers whereas SVG does provide the support for event handlers.
 Canvas is ideal for graphic-intensive games whereas SVG doesn’t intend for gaming.
 It works well for small rendering areas whereas SVG may perform better for large rendering
areas like Google map.

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">

Q-9. What Is HTML5 Web Storage?


HTML5 brought this new ability to store web pages within the browser cache. This web storage is not
only faster than the cookies but secured too. It is capable of storing a large amount of data without
compromising the performance of the website.
Also, note that the cached data is not must for every server request. Instead, it gets utilized only when
the page asks for it. And the web page which receives the data stored can access it.

Q-10. What Is The Difference Between LocalStorage And SessionStorage Objects?


Following points describes the differences between the localStorage and sessionStorage objects.
 The <localStorage> object doesn’t have an expiry for the stored data whereas the
<sessionStorage> object keeps it only for a single session.
 The <localStorage> object doesn’t have a provision to delete the data upon closing of browser
window whereas the <sessionStorage> object clears it simultaneously with the window closing down.
Web Developer Interview Questions – Part2.

CSS3 Interview Questions.

Q-1. How Does CSS3 Differ From CSS?


CSS3 is the most recent version of CSS. It has introduced a bunch of new tags to give a better user
experience. Some of the features are rounded corners, animation, custom layout, and media queries.

Q-2. How Does CSS3 Support Responsive Web Designing?


CSS3 has come up with a media query feature. It supports RWD (Responsive Web Design) and does
help in making a website responsive.

Q-3. What Is A CSS Selector?


A CSS selector is an expression following the CSS rules and used to select the element we want to
style. And CSS selector syntax means how we write or use those selectors in the CSS editor.
Please note that a CSS selector can help you find or select HTML elements based on their name, id,
class, attribute, and more.

Q-4. What Are The Different Types Of CSS?


Below are the different types of CSS.
 Embedded – It adds the CSS styles using the <style> attribute.
 Inline – It adds the CSS to the HTML elements.
 Linked/External – It adds an external CSS file to the HTML document.

Q-5. What Is An ID Selector?


The ID selector uses the “ID” attribute of the target HTML element to select it. The constraint to work
is that the ID should be unique within a page so that the selector can point it out correctly.
To build an ID selector expression, start with a hash (#) character, followed by the id of the element.
Here is an example which selects a paragraph element using its ID.
#sample {padding: 10px;}

<p id="selector">...</p>

Q-6. What Does The Class Selector Mean?


In CSS, a class selector is an expression which begins with a full stop (“.”) and followed by the name
of a class. The class attribute could be a space-separated list of items, and one of those must match
with the class name specified in the selector.
Here is an example which selects a div and modified its style.
.sampleclass {font-family: Ariel; font-size: 10; background: green;}

<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-8. What Is Grouping In CSS3?


Grouping makes it possible to apply the same style to multiple HTML elements (Classes/Tag/ID)
within a single declaration. It happens by specifying all the selectors separated by commas.
#page p, ul { padding-top: 10px; margin: 0; }
Q-9. What Are Child Selectors In CSS?
A child selector looks up for the child of some element. To form a child selector, we need two or more
selectors separated by “greater than” symbol.
Let’s take an example. We have a <ul> tag inside a paragraph. Here, <ul> is the child of the paragraph
element. So, to apply the CSS styles, we can use the following syntax.
p > ul { font-size:15px; }

Q-10. How Do You Make Border Rounded With CSS3?


Yes, in CSS3, there is a <border-radius> property which allows creating an element with rounded
corners. We can apply the same style to all the sides and make the corners round.
The <border-radius> property has four individual properties <border-top-left-radius>, <border-top-
right-radius>, <border-bottom-left-radius> and <border-bottom-right-radius>.

Q-11. What Is Webkit In CSS3? And Why Is It Used?


Webkit is a core software component which is responsible for rendering HTML and CSS in browsers
like Safari and Chrome. There are other similar rendering engines like Gecko for Mozilla, Presto for
Opera, and Edge for IE.
To enable Webkit on a web page, it requires prefixing the <-webkit> keyword with CSS values.
Here is an example of CSS using the Webkit feature.
.box_shadow {
-webkit-box-shadow: 0px 0px 5px 0px #ffffff;
box-shadow: 0px 0px 5px 0px #ffffff;
}

Q-12. How Do You Enable Pagination Using CSS3?


Making use of a <ul-li> structure, we can allow Pagination with CSS3.
<div class="main_container">
<div class="pagination">
<ul>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li class="active"><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>
</div>
</div>

Q-13. What Are Transitions In CSS3?


CSS3 transitions help to create a super easy and fast animation effect. They not only give us control to
change the value of a property but also let it proceed slowly for the given duration.
We can use the following CSS properties.
transition, transition-delay, transition-duration, transition-property, and transition-timing-function.

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;
}
}

Q-16. What Are Pseudo-Classes In CSS?


A Pseudo-Class is a CSS technique to set the style when the element changes its state.
For example
 Edit the style upon mouse hover event.
 Set the style when an element gets focus.
 Apply different styles for visited/unvisited links.
selector:pseudo-class {
property:value;
}

Q-17. What Is The Use Of Float Property In CSS?


With the help of float property, we can control the position and layout of elements on a web page.
For example, it can define the placement of a <div> either to the right or left side.
Also, to note that it doesn’t interfere with the elements appearing before.
div {
float: left;
}
Q-18. Which Property Do You Use To Modify The Face Of A Font In CSS?
First of all, please note that both the terms <@font-face> and <font-family> refers to changing the font
of an HTML element. However, there is a slight difference between the two.
1. The <@font-face> is a CSS rule that facilitates the use of custom fonts on a web page.
2. The <font-family> is a CSS property which specifies the font for a web element.
Also, to change the font or face of a font, we need to set the <font-family> property. Please see the
below example.
@font-face {
font-family: myCustomFont;
src: url(sansation_light.woff);
}

body {
font-family: 'myCustomFont', Fallback, Ariel;
}

Q-19. How Do You Add Comments In CSS?


It is just the same in CSS as we do in JavaScript. Place the comments inside the enclosing /* and */.

Q-20. What Is Z-Index And How Does It Work?


The z-index is a CSS property which defines the stack order of web elements. Higher order elements
will appear before any lower order element.
Note – The z-index only applies to the positioned elements. For example, position:absolute,
position:relative, or position:fixed.
div {
position: absolute;
left: 10px;
top: 10px;
z-index: -1;
}

Web Developer Interview Questions – Part3

JavaScript Interview Questions

Q-1. What Are The Core Data Types Available In JavaScript?


Below is the list of data types available in JavaScript.
 Number
 Object
 String
 Boolean
 Function
 Null
 Undefined

Q-2. What Is Difference Between <Window.Onload> And <OnDocumentReady>?


The <onload> event doesn’t invoke until the page gets finished loading of CSS and images. It could
cause a significant delay in rendering of the web page.
As a web developer, we have to ensure the page should load as quick as possible. The event
<onDocumentReady> lets us only wait for the DOM to initialize instead of delaying any action
required.

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-5. What Is Namespacing In Javascript And Where Is It Used?


Using global variables is a bad practice in most programming languages including JavaScript. But
sometimes, it is not possible to avoid global variables. So JavaScript introduces the concept of
namespacing which ties down a part of the code and register it with a unique name.
A namespace is just an object in JavaScript that acts as a container for methods, properties, and other
types. It encourages modularity and reusability in a web application.
Q-6. How Does JavaScript Handle Automatic Type Conversion?
As per ECMA Script standard, JavaScript is dynamic as well as weakly typed language with first-class
functions which means – “A JavaScript function can accept other functions as arguments.”
Also, it does support auto-type conversion. Whenever an operator or a statement doesn’t get a value of
the expected type, then the conversion takes place automatically.
Q-7. What Are Different Types Of Popup Boxes Available In JavaScript?
JavaScript allows the following types of dialog boxes.
 Alert – It just has a <Ok> button to proceed.
 Confirm – It pops up a window showing up <Ok> and <Cancel> buttons.
 Prompt – It gives a dialog asking for user input followed by showing <Ok>/<Cancel> buttons.

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.

Q-9. What Is Scope In JavaScript?


The general meaning of scope is the accessibility of functions and variables in an application. Usually,
we use them in two ways, i.e., Local and Global.
A) Local Scope
If we declare a function or variable inside a function, then we can access it only inside that function.
// code here can not use myLocalVar

function myFunction() {
var myLocalVar = "I'm Local";

// code here can use myLocalVar

}
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";

// code here can use myGlobalVar

function myFunction() {

// code here can use myGlobalVar

Q-10. What Types Of Comments Does JavaScript Support?


There are two ways to insert comments in JavaScript code.
For single line comment, we can use // (double forward slash).
For multiline comment, we enclose comments using /* */.
/*

//

//

*/
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-13. What Relates JavaScript With ECMA Script?


ECMA Script is another technical name for JavaScript as it is also known as LiveScript. The current
JavaScript that you may see running in browsers is ECMA Script revision 6.

Q-14. What Is The Mechanism To Submit A Form Using Javascript?


We can call the following method to submit a form using JavaScript.
document.forms[0].submit();

0 -> index of the form


Note – if we have more than one form, then the first one stays at index 0, next is at index 1 and so on.

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

Q-16. What Is The Function Of Delete Operator In JavaScript?


The delete operator clears all the variables and objects used on the web page. But it leaves the
variables declared using the var keyword as is.

Q-17. What Is The Use Of <This> Keyword In JavaScript?


The <this> keyword refers to the current object in the program. It is usually available inside a method
for referencing the current variable or current object.

Q-18. What Does The <TypeOf> Operator Do In JavaScript?


The <typeof> operator give back the type of a variable in the form of a string.

Q-19. How Do You Make Generic Objects In JavaScript?


JavaScript provides a new operator to produce generic objects.
Follow the below example creating a generic object.
var obj = new object();

Q-20. What Does The “Defer” Attribute Do In JavaScript?


The <defer> attribute is primarily of boolean type. It delays executing a javascript until the page
completes the parsing process.
Below is the example of JavaScript code deferring a sample script.
<script src="/mysample.js" defer></script>
JavaScript Interview Questions And Answers

Q.1- What’s An Object In Javascript And How Do We Create Them?


A JavaScript object is an entity having state and behavior (properties and method). Since JavaScript is
an object-based language, it treats everything as an object.
JavaScript is a template-based language. It doesn’t need to define a class for creating an object instead
creates it directly
JavaScript supports the following three ways to create objects.
1. By Object Literal.
The syntax of creating an object using object literal is as follows.
object={property1:value1, property2:value2.....propertyN:valueN}
Here, property and value get separated by a colon “:” sign.
Let’s take an example.
<script>

std={id:1114, name:"Ram Bajaj", subject:"Physics"}

document.write(std.id+" "+std.name+" "+std.subject);

</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>

var std=new Object();

std.id=1114;

std.name="Ram Bajaj";

std.subject="Physics";

document.write(std.id+" "+std.name+" "+std.subject);

</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;

s=new std(1114,"Ram Bajaj","Physics");

document.write(s.id+" "+s.name+" "+s.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';

console.log(name); // logs 'TechBeamers'

function logName() {

console.log(name); // 'name' is accessible here and everywhere else

logName(); // logs 'TechBeamers'


2. Local Scope.
Variables defined inside a function comes under the Local scope. Different functions can use a
variable with the same name. It is because these variables are strictly bound to the function that
defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.
// Global Scope

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);

alert(this.Obj); // I'm the window object

alert(window === this); // true


The Scenario Of A Function Call.
In the case of a function call, ‘this’ refers to the global object.
window.Obj = "I represent the window object";

function TestFunction() {

alert(this.Obj); // I'm the window object

alert(window === this); // true

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.Obj = "I'm the Test object";

this.Verify1 = function() {

alert(this.Obj); // I'm the Test object

};

TestFunction.prototype.Verify2 = function() {

alert(this.Obj); // I'm the Test object

};
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() {

return 2 * (this.x + this.y);

var rect = new Rectangle(4, 2);

console.log(rect.perimeter()); // outputs '12'


Q-5. What Is Closure In JavaScript?
A closure is a JavaScript function defined inside another function. And that’s why it gets a special
privilege to access three types of scope which are as follows.
 Internal Scope, i.e., the variables defined between its curly brackets
 Outer Function Scope, i.e., the variables of the enclosing function
 Global Scope, i.e., variables defined as globals
Please note that a closure can not only access the outer function variables but also see its parameters.
But it can’t call the object of the outer function’s arguments. However, it can directly call the outer
function’s parameters.
Here is a code example describing closure by adding a function inside another function.
function outerFunc(arg1, arg2) {
var param = "I'm closure. ";

// Inner function accessing outer function variables and parameters


function innerFunc() {
return arg1 + arg2 + " " + param;
}
return innerFunc();
}

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() {

console.log(this.aProperty); // outputs 'global'

}, 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() {

var self = this;

this.aProperty = 'local';

setTimeout(function() {

console.log(self.aProperty); // outputs 'local'

}, 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()
{

alert("Zoom! Zoom! Zoom!");


}

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) */

var a = 13; // Number declaration

var b = "thirteen"; // String declaration

/* Java Example (strong typing) */

int a = 13; // int declaration

String b = "thirteen"; // String declaration


Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type
‘Number’ and var ‘b’ will be of type ‘String’.
Q-13. What Are The Different Ways To Create An Array In JavaScript?
There are two main ways to create an array in JavaScript.
1. Using An Array Initializer (Array Literal).
The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square
brackets.
Let’s see some examples.
var myArray1 = [1,2,3,4,5] // an array with 5 elements

var myArray2 = [5] // an array with 1 element

var myArray3 = [true,'Hi',[7]] // element types need not be the same.


2. Using The Array Constructor.
The Array constructor method has three different syntaxes. If we call the constructor with two or more
arguments, it declares an array with array elements also initialized. If we provide only one argument to
the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the
constructor without any argument creates an array with its length set to zero with elements not
initialized.
Let’s see some examples.
var myArray4 = new Array(1,2,3,4,5) // an array with 5 elements

var myArray5 = new Array(20) // an empty array of length 20

var myArray6 = new Array() // an empty array of length 0


Q-14. What Are JavaScript Cookies?
A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets
stored locally by the browser at the user end. Cookies are needed because HTTP protocol which
arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to
keep track of the activities performed by the user at an earlier point in time. One way to resolve this
issue is by using cookies. It contains the following data.
 A name-value pair containing the actual data
 An expiry date after which the cookie is no longer valid
 The domain and path of the server it should be sent to
When a request arrives at the server for a web page that maintains a cookie, the server appends the
cookie to the HTTP header to send it across. The server-side programs can then read out the
information included in it and decide that you have the right to view the page or not and other user
preferences.
Thus, every time you visit the site that maintains the cookies, your information is available there.
Q-15. Which Built-In Method Adds One Or More Elements To The End Of An Array And Returns
The New Length Of The Array?
The push() method adds one or more elements to the end of an array and returns the new length of the
array.
Q-16. What Is The Naming Conventions For The Variables In JavaScript?
We have to follow the below rules while naming the variables in JavaScript.
 Do not use any of the JavaScript reserved keywords as a name for your variable. For example,
the “break” or “boolean” is the JavaScript keywords, and if used as variable names, it’s invalid.
 JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or
the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
 Also, JavaScript variable names are case sensitive. For example, test and Test are two different
variables.
Q-17. How Will You Create A Cookie Using JavaScript?
The simplest way to create a cookie is to assign a string value to the <document.cookie> object.
Its syntax is as follows.
document.cookie = "key1 = value1; key2 = value2; expires = date";
Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.
If we provide a valid value for the date or time, then the cookie will expire at the given date or time,
and it will not be accessible after that.
Q-18. How To Read A Cookie Using JavaScript?
To read a Cookie, we have to access the value of the <document.cookie> object. This
<document.cookie> string maintains a list of <name = value> pairs that is separated with semicolons.
Where,
"name" is the name of a cookie and

"value" is its string value.


We use String <split()> function to break the <document.cookie> Object to sub-strings. Each of these
sub-strings contains a key-value pair which represents the information related to a Cookie.
Q-19. How To Delete A Cookie Using JavaScript?
To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are
made to read a deleted Cookie then, nothing is returned.
Q-20. How Do You Submit A Form Using JavaScript?
We use the following in the web page code to submit a form.
document.forms[0].submit();
Here <0> refers to the index of the form. If we have more than one forms on a web page, then the
index for the first one will be “0”, for the second form, its value will be “1” and so on.
Q-21. Why Should You Not Prefer To Use Global Variables In JavaScript And How Can You Prevent
It?
The principal issue in using a global variable is that someone else can create another variable with the
same name. And you may not know it until the duplicate could overwrite the value of your variable.
To avoid using globals, follow any of the following approaches.
1. Create a single global variable that holds all your other variables.
var myGlobalList = {};

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>

// this piece of code runs first

</script>

<script defer="defer">

//do stuff, but defer it (runs last)

</script>

<script>

//do more stuff (runs second)

</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>

<INPUT TYPE=”button” VALUE=”Test” onClick=”window.alert ('Event Handler')”>

</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(test()); // will print 'undefined'


Q-27. What Is EncodeURI() Function?
The encodeURI() function is used to encode a URI. This function encodes all special characters,
except these < , / ? : @ & = + $ #>.
Let’s See An Example.
var uri="//www.techbeamers.com/how to make a website using javaScript";

var encodedURI = encodeURI(uri);

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"

str = str.replace(/test/g, '');

alert(str)
Use RegExp Class To Create A Regular Expression And Pass It.
String.prototype.replaceAll = function(find, replace) {

var target = this;

return target.replace(new RegExp(find, 'g'), replace);

};

str = "ghktestlllltest-sdds"

str = str.replaceAll('test', '');

alert(str)

Q-1. What Are The New Features Introduced In HTML5?


Answer.
HTML5 introduces a number of new elements and attributes that help in building an attractive
webSite, that we see nowadays.
It supports following new features.
 New Semantic Elements – These are like <header>, <footer>, and <section>.
 Forms 2.0 – It contains improvements to HTML web forms. It has introduced new attributes
for the <input> tag.
 Persistent Local Storage – With HTML5, it is possible to achieve this, without resorting to
third-party plugins.
 WebSocket – It facilitates setting up a bidirectional communication for web applications.
 Server-Sent Events(SSE) – These events got introduced in HTML5. The direction of the flow
of the execution of these events is from the server to the Web Browser.
 Canvas – It supports a two-dimensional drawing surface that is programmable using
JavaScript.
 Audio & Video – It allows embedding audio or video on the web pages without resorting to
third-party plugins.
 Geolocation – It facilitates the visitors to share their physical location with the web application.
 Microdata – It allows building our personal vocabulary beyond HTML5 and extends our web
pages with those custom semantics.
 Drag and drop – It supports to Drag and drop the items from one location to another location
on the same Web page.

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-3. What Is A Tag In HTML?


Answer.
A tag instructs the Browser about how to format the HTML properly. When you write an HTML page,
you enter tags for many reasons to change the appearance of text, to show a graphic, or to make a link
to another page. HTML uses symbols like “<” and “>” to enclose the tags. And symbol “\” for closing
the tag.

Q-4. What Is The Difference Between HTML Elements And Tags?


Answer.
HTML elements communicate to the Browser how to represent the text. They become HTML tags
when enclosed within angular brackets <>.

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-9. How Can We Get The Geographical Position Of A User In HTML5?


Answer.
Yes, HTML5 can retrieve the location of a user with the use of Geolocation API. It provides
getCurrentPosition() method to get the user’s current position.
Q-10. Describe Form Input Types In HTML5?
Answer.
HTML5 is the new standard for HTML that provides 13 new input types for forms. Using these new
input types, we can create more interactive and easy-to-use web forms. It also provides better data
validation, input control, color picker controls and many others.
The new input types for forms provided by HTML5 are as follows.
 color – It’s applicable for HTML elements that represent color.
 date – It allows the user to select a date.
 DateTime – It enables the user to select a date and time (with time zone).
 DateTime-local – It allows the user to select a date and time (without time zone).
 email – It is applicable for input fields that contain an e-mail address.
 month – It permits the user to select a month and year.
 number – It is applicable for input fields that accept a numeric value. It allows setting
restriction on the data type of the number, this field takes.
 range – It is applicable for input fields that accept a value from a range of numbers. It allows
setting restriction on the data type of the number, this field takes.
 search – It gets used for search fields.
 tel – It defines a field for entering a telephone number.
 time – It allows the user to select a time.
 URL – It is applicable for the input fields that contain a URL address.
 week – It allows the user to select a week and a year.

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-11. What Is HTML5 Graphics?


Answer.
In HTML5, there are two types of graphics.
Scalable Vector Graphics (SVG).
 The HTML5 <svg> element is a container for SVG graphics. It provides several methods for
drawing boxes, paths, text, circles, and graphic images.
 SVG is beneficial as nowadays, people are using high-resolution devices (iPads and Monitors),
so it becomes impressive as designs, logos, and charts scale according to the requirement,
maintaining the picture quality.
 SVG is XML based, which means that every element is available within the SVG DOM. It
treats every shape as an object. If the user changes the attributes of any SVG object, the
browser will automatically re-render the shape.
Canvas.
 It is a rectangular area on the HTML page for drawing graphics on the fly, using JavaScript.
 The default size of the canvas is 300 PX × 150 PX (width × height).
 The HTML tag <canvas> is a container for the Canvas graphics. Canvas gets executed on the
pixel by pixel basis.
 In Canvas, browser forgets the graphic, after drawing it. If the user tries to modify it, the entire
scene needs to be redrawn, including all the objects present in the graphic.

Q-12. Explain The Key Differences Between SVG And Canvas?


Answer.
 Canvas is resolution dependent while SVG is not.
 Canvas does not provide any support for event handlers while SVG does provide the support
for event handlers.
 Canvas is suitable for graphic-intensive games while SVG is not suitable for gaming.
 Canvas is suitable for small rendering areas while SVG is suitable for large rendering areas like
Google maps.
 Canvas provides a less interactive animated user interface. Whereas, the interface provided by
SVG is very highly interactive.

Q-13. How Can We Create A New HTML Element?


Answer.
We can even create new elements for the document as follows.
<script>
document.createElement﴾"myElement"﴿
</script>
It can be used in the HTML as.
<myElement>hello</myElement>

Q-14. What Is The Use Of Drag And Drop In HTML5?


Answer.
Drag and Drop (DnD) is a powerful User Interface concept, which enables the user to copy, reorder
and delete any number of items, just with the help of mouse click. To do this, the user has to click and
hold the mouse button over an element, drag to the required location, and finally release the button to
drop the element there.
With HTML4, developers have to either do complex Javascript programming or use other Javascript
frameworks like jQuery to achieve this functionality.
HTML 5 introduced a Drag and Drop (DnD) API that provides the support of all the fundamental DnD
operations to the browser. Thus making it easy for the developers to code it.
Latest versions of all the main browsers, like Chrome, Firefox, and Safari, support this DnD API of
HTML5.
Drag And Drop Events.
Many events get triggered during various stages of the drag and drop operation. These events are listed
below.
 dragstart – it gets triggered when the user starts dragging a draggable object.
 dragenter – it gets triggered when the user has dragged the draggable element over the target
element.
 drag – it gets fired when the object is getting dragged.
 dragend – it gets fired when the user releases the mouse button after dragging an object.
 dragleave – This event gets triggered when the mouse leaves an element while a drag is
occurring.
 dragover – This event gets fired when the mouse moves over an element while a drag is
occurring.

Q-15. What Is HTML5 Web Storage?


Answer.
HTML5 Web Storage, also known as DOM Storage is a way to preserve state on either the client or
server which makes it much easier to work against the stateless nature of HTTP. It allows the web
pages to store the data locally in the user’s browser.
Following are the advantages of HTML5 Web Storage.
 It can store 5 to 10 MB data. That is far more than what cookies allow.
 HTML5 never transfers Web storage data with any HTTP request. Thus creating less overhead
than cookies and in turn, increase the performance of the application.
 Apps can work both online and offline.
 This API is easy to learn and use.
Q-16. What Are The Different Types Of Web Storage Provided By HTML5?
Answer.
There are two types of Web Storage.
1. Session Storage
As its name indicates, it stores data of current session only. The data stored in Session Storage clears
on closing the browser.
Following methods are available to access Session Storage.
 Use setItem() function to store data in Session Storage
sessionStorage.setItem (‘key’,’value’);
For Example.
sessionStorage.setItem (‘username’,’Meenakshi’)
 Use getItem() function to retrieve data from Session Storage
sessionStorage.getItem(‘key’);
For Example.
var username= sessionStorage.getItem(‘username’);
 We can only store String in Session Storage. To save the objects in Session, first, convert the
object into JSON string and then store this string in Session Storage as in the following.
sessionStorage.setItem (‘object’, JSON.stringify(object));
 If JSON string gets stored in Session Storage, then first convert it into an object as follows.
var object=JSON.parse(sessionStorage.getItem(‘object’));
 Use removeItem() function to delete a particular key from Session Storage.
sessionStorage.removeItem(‘key’);
2. Local Storage
Local Storage is the second type of HTML Web Storage. It stores data as KEY/VALUE pair.
Following functions are available to access Local Storage.
 Use setItem() function to store data in Local Storage
localStorage.setItem (‘key’,’value’);
 Use getItem() function to retrieve data from Local Storage
localStorage.getItem(‘key’);

Q-17. What Is The Need Of Introducing Local Storage In HTML5?


Answer.
Before HTML5, LocalStores was done with Cookies. They are not very good for large amounts of
data, because, with every request, it passes this data to the server, making it very slow and ineffective.
However, HTML5 does not pass this data on every server request. It uses the data ONLY when
required. In HTML5, it is possible to store large amounts of data without affecting the website’s
performance. Data for different website gets stored in separate areas. However, a particular website
can only access its own data.

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-20. What Is A Manifest File?


Answer.
A Manifest file is a simple text file, that tells the browser what to cache and what not to cache.
A Manifest file contains three Sections as
 CACHE MANIFEST – HTML5 performs the caching of files listed under this section after
they get downloaded for the first time.
 NETWORK – Files listed here, always need a connection to the server. The browser can never
cache them.
 FALLBACK – Files listed here specify the fallback pages, if any page in it is not accessible.

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-22. What Is A Web Worker? How Does It Work?


Answer.
JavaScript will hang the browser if it has to handle UI events, query large amounts of API data for
processing, and manipulate the DOM simultaneously.
Web Workers handle this situation by doing all the high computation tasks without interrupting the
user interface. They do this by running on separate threads. Thus we can say that.
 A web worker is a script, which runs in the background. It exists in external files.
 The user can perform actions like clicking, selecting things and so on. Meanwhile, the Web
worker runs in the background.
 It is appropriate, to use Web worker for CPU intensive tasks.
Since Web workers are in external files, they do not have access to the following JavaScript
objects.
 The window object
 The document object
 The parent object
How Does A Web Worker Work?
A Web worker gets initialized with the URL of a JavaScript file that contains its code. This code sets
event listeners and starts communication with the script that invoked the worker from the main page.
The Syntax is as follows.
var worker = new Worker("sample_prog.js"﴿;
If the javascript file specified in the above code exists, the browser spawns a new worker thread.
Once the Web worker gets spawned, it starts the communication with the parent page, using the
postMessage() method. The Web worker, in turn, returns a message, that gets accessed using the
onmessage() event on the main page.
Let’s take an example, where the script spawns a Web worker to execute a loop having thousands of
iterations. After that, the Web worker returns the calculated value to the HTML page.
<script>
var worker = new Worker('calculateLoop.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + "iterations" );
};
</script>
Below is the code of “calculateLoop.js” file. It makes use of postMessage() API, to pass the
communication back to the HTML page.
for (var i = 0; i <= 1000000000; i += 1){
var j = i;
}
postMessage(j);

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-23. What Is Output Element In HTML5?


Answer.
Output element gets used when you design a form, that displays the result of a computation. Along
with the standard global attributes, <output> also accepts for, form, and name attributes.
Let’s see a simple example of the <output> element that adds two numbers and displays the resulting
value.
<!DOCTYPE html>
<html>
<head>
<title>HTML Output Tag</title>
</head>
<body>
<form oninput="sumresult.value=parseInt(val1.value)+parseInt(val2.value)+parseInt(val3.value)">
<input type="range" name="va1" value="10" /> +
<input type="number" name="val2" value="20" /> +
<input type="number" name="val3" value="40" /><br />
The output is: <output name="sumresult"></output>
</body>
</html>
The form attribute associates the <output> with a form. It displays the output as “70” on the web page.

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.

Q-26. What Is Audio Tag In HTML 5? What Are Its Attributes>


Answer.
This new element allows you to embed audio files in an HTML or XHTML document, without the
need for any plug-ins. The Audio tag is a new tag introduced in HTML5. You can use it to play audio
sound like .mp3, wav, and .ogg.
Using the <source> tag, we can specify media along with media type and many other attributes. An
audio element allows multiple source elements and browser will use the first recognized format.
<!DOCTYPE HTML>
<html>
<body>

<audio controls="controls" >


<source src="URL1" type="audio/mp3" />
<source src="URL2" type="audio/wma" />
<source src="URL3" type="audio/x-wav" />
Your browser does not support the audio element.
</audio>

</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-27. What Is The Use Of <Fieldset> Tag In HTML5?


Answer.
The <fieldset> tag groups related form elements. It is like a box. In other words, it draws a box around
related elements.
It must start with a <legend>tag because the <legend> tag defines the title of the fieldset.
Following is the Syntax of the <fieldset> tag in HTML5.
<fieldset>Controls</fieldset>
All the popularly known browsers provide the support for the <fieldset> tag.
HTML5 supports following attributes with the fieldset tag.
 disabled
 Its value is disabled. It specifies, whether the fieldset will be displayed or not.
 name
 Its value is in the form of text. It defines the name of the fieldset.
 form
 Its value is the name of the form. It specifies the form related to the fieldset.
Let’s see an example, where we create a fieldset in a form. Here we use the <legend> tag to define the
heading for the fieldset.
<html>
<body>
<form>
<fieldset>
<legend>Personal Information</legend>
First Name: <input type="text" />
<br/><br/> Last Name: <input type="text" />
<br/><br/> person_Address: <input type="text" />
<br/><br/> person_Qualification: <input type="text" />
</fieldset>
</form>
</body>
</html>

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.

2. What is the difference between $name and $$name?


$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia
value is singh.

3. What are the method available in form submitting?

GET and POST

4.How can we get the browser properties using 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?

Register the variable into the session


Pass the variable as a cookie
Pass the variable as part of the URL

8. How can we know the total number of elements of Array?

sizeof($array_var)
count($array_var)

 
9. How can we create a database using php?

mysql_create_db();

10. What is the functionality of the function strstr and stristr?

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.

11. What are encryption functions in PHP?

CRYPT(), MD5()

12. How to store the uploaded file to the final location?

move_uploaded_file( string filename, string destination)

13. Explain mysql_error().

The mysql_error() message will tell us what was wrong with our query, similar to the message we would
receive at the MySQL console.

14. What is Constructors and Destructors?

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.

There are some defference between GET and POST method


1. GET Method have some limit like only 2Kb data able to send for request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good for send sensetive request
 

17. What are the differences between require and include?

Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error
 

18.  What is use of header() function in php ?

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.

19. List out the predefined classes in PHP?

Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
 

20. What type of inheritance that PHP supports?

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?

You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");


We can encode data using base64_encode($string) and can decode using base64_decode($string);
 
22. What is the difference between explode and split?

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);
 

24. How do you pass a variable by value in PHP?

Just like in C++, put an ampersand in front of it, like $a = &$b;


 

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

 The output is displayed directly to the browser.


 

26. How do you call a constructor for a parent class?


 parent::constructor($value)
 

27. What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
 

28. What is the difference between PHP and JavaScript?

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?

unlink() deletes the given file from the file system.


unset() makes a variable undefined.
 

30. How many ways can we get the value of current session id?

session_id() returns the session id for the current session.


 

31. What are default session time and path?

default session time in PHP is 1440 seconds or 24 minutes


Default session save path id temporary folder /tmp
 

32. for image work which library?

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?

printf()-    Displays a formatted string


sprintf()-Saves a formatted string in a variable
fprintf()    -Prints a formatted string to a file
number_format()-Formats numbers as strings
 

35. How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link);


$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
Q #1) What is PHP?
Answer:
PHP is one of the popular server-side scripting languages for developing a web application.

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.

Q #2) Why do we use PHP?


Answer:
There are several benefits of using PHP. First of all, it is totally free to use. So anyone can use
PHP without any cost and host the site at a minimal cost.

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.

Q #3) Is PHP a strongly typed language?


Answer:
No. PHP is a weakly typed or loosely typed language.

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

Q #7) How can you declare the array in PHP?


Answer:
You can declare three types of arrays in PHP. They are numeric,
associative and multidimensional arrays.
Sample code:
//Numeric Array
$computer = array("Dell", "Lenavo", "HP");
//Associative Array
$color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green");
//Multidimensional Array
$courses = array ( array("PHP",50), array("JQuery",15), array("AngularJS",20) );
Q #8) What are the uses of explode() and implode() functions?
Answer:
explode() function is used to split a string into an array and implode() function is used to make a
string by combining the array elements.
Sample code:
$text = "I like programming";
print_r (explode(" ",$text));
$strarr = array('Pen','Pencil','Eraser');
echo implode(" ",$strarr);
Q #9) Which function can be used to exit from the script after displaying the error
message?
Answer:
You can use exit() or die() function to exit from the current script after displaying the error
message.
Sample code:
if(!fopen('t.txt','r'))
exit(" Unable to open the file");
Sample code:
if(!mysqli_connect('localhost','user','password'))
die(" Unable to connect with the database");
Q #10) Which function is used in PHP to check the data type of any variable?
Answer:
gettype() function is used to check the data type of any variable.

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.

Few functions are mentioned below:


mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative array.
Sample code:
// Associative or Numeric array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo "Name is $row[0]
";
echo "Email is $row['email']
";
mysqli_fetch_row() – It is used to fetch the records in a numeric array.
Sample code:
//Numeric array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s %s\n",$row[0],$row[1]);
mysqli_fetch_assoc() – It is used to fetch the records in an associative array.
Sample code:
// Associative array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s %s\n",$row["name"],$row["email"]);
mysqli_fetch_object() – It is used to fetch the records as an object.
Sample code:
// Object
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s %s\n",$row->name,$row->email);
Q #16) What are the differences between mysqli_connect and mysqli_pconnect?
Answer:
mysqli_pconnect() function is used for making a persistence connection with the database that
does not terminate when the script ends.
mysqli_connect() function searches any existing persistence connection first and if no
persistence connection exists, then it will create a new database connection and terminate the
connection at the end of the script.
Sample code:
$DBconnection = mysqli_connect("localhost","username","password","dbname");
// Check for valid connection
if (mysqli_connect_errno())
{
echo "Unable to connect with MySQL: " . mysqli_connect_error();
}
mysqli_pconnect() function is depreciated in the new version of PHP, but you can create
persistence connection using mysqli_connect with the prefix p.
Q #17) Which function is used in PHP to count the total number of rows returned by any
query?
Answer:
mysqli_num_rows() function is used to count the total number of rows returned by the query.
Sample code:
$mysqli = mysqli_connect("hostname","username","password","DBname");
$result=mysqli_query($mysqli,"select * from employees");
$count=mysqli_num_rows($result);
Q #18) How can you create a session in PHP?
Answer:
session_start() function is used in PHP to create a session.
Sample code:
session_start(); //Start session
$_SESSION['USERNAME']='Fahmida'; //Set a session value
unset($_SESSION['USERNAME']; //delete session value
Q #19) What is the use of imagetypes() method?
Answer:
image types() function returns the list of supported images of the installed PHP version. You can
use this function to check if a particular image extension is supported by PHP or not.
Sample code:
//Check BMP extension is supported by PHP or not
if (imagetypes() &IMG_BMP) {
    echo "BMP extension Support is enabled";
}
Q #20) Which function you can use in PHP to open a file for reading or writing or for both?
Answer:
You can use fopen() function to read or write or for doing both in PHP.
Sample code:
$file1 = fopen("myfile1.txt","r"); //Open for reading
$file2 = fopen("myfile2.txt","w"); //Open for writing
$file3 = fopen("myfile3.txt","r+"); //Open for reading and writing
Q #21) What is the difference between include() and require()?
Answer:
Both include() and require() function are used for including PHP script from one file to another
file. But there is a difference between these functions.
If any error occurs at the time of including a file using include() function, then it continues the
execution of the script after showing an error message. require() function stops the execution of
a script by displaying an error message if an error occurs.
Sample code:
if (!include(‘test.php’)) echo “Error in file inclusion”;
if (!require(‘test.php’)) echo “Error in file inclusion”;
Q #22) Which function is used in PHP to delete a file?
Answer:
unlink() function is used in PHP to delete any file.
Sample code:
unlink('filename');
Q #23) What is the use of strip_tags() method?
Answer:
strip_tags() function is used to retrieve the string from a text by omitting HTML, XML and PHP
tags. This function has one mandatory parameter and one optional parameter. The optional
parameter is used to accept particular tags.
Sample code:
//Remove all tags from the text
echo strip_tags("<b>PHP</b> is a popular <em>scripting</em> language");
//Remove all tags excluding <b> tag
echo strip_tags("<b>PHP</b> is a popular <em>scripting</em> language","<b>");
Q #24) How can you send HTTP header to the client in PHP?
Answer:
header() function is used to send raw HTTP header to a client before any output is sent.
Sample code:
header('Location: http://www.your_domain/');
Q #25) Which functions are used to count the total number of array elements in PHP?
Answer:
count() and sizeof() functions can be used to count the total number of array elements in PHP.
Sample code:
$names=array(“Asa”,”Prinka”,”Abhijeet”);
echo count($names);
$marks=array(95,70,87);
echo sizeof($marks);
Q #26) What is the difference between substr() and strstr()?
Answer:
substr() function returns a part of the string based on the starting point and length. Length
parameter is optional for this function and if it is omitted then the remaining part of the string from
the starting point will be returned.
strstr() function searches the first occurrence of a string inside another string. The third
parameter of this function is optional and it is used to retrieve the part of the string that appears
before the first occurrence of the searching string.
Sample code:
echo substr("Computer Programming",9,7); //Returns “Program”
echo substr("Computer Programming",9); //Returns “Programming”
Sample code:
echo strstr("Learning Laravel 5!","Laravel"); //Returns Laravel 5!
echo strstr("Learning Laravel 5!","Laravel",true); //Returns Learning
Q #27) How can you upload a file using PHP?
Answer:
To upload a file by using PHP, you have to do the following tasks.

#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">

<input type="file" name="upd" id="upd">

<input type="submit" value="Upload" name="upload">

</form>

#3) Write PHP script to upload the file


if (move_uploaded_file($_FILES["upd"]["tmp_name"], "Uploads/")) {
echo "The file ". basename( $_FILES["upd"]["name"]). " is uploaded.";
} else {
echo "There is an error in uploading.";
}
Q #28) How can you declare a constant variable in PHP?
Answer:
define() function is used to declare a constant variable in PHP. Constant variable declares
without the $ symbol.
Sample code:
define("PI",3.14);
Q #29) Which function is used in PHP to search a particular value in an array?
Answer:
in_array() function is used to search a particular value in an array.
Sample code:
$languages = array("C#", "Java", "PHP", "VB.Net");
if (in_array("PHP", $languages)) {
echo "PHP is in the list";
}
else {
echo "php is not in the list";
}
Q #30) What is the use of $_REQUEST variable?
Answer:
The $_REQUEST variable is used to read the data from the submitted HTML form.
Sample code:
Here, the $_REQUEST variable is used to read the submitted form field with the name
‘username’. If the form is submitted without any value, then it will print as “Name is empty”,
otherwise it will print the submitted value.
<?php
if (isset($_POST['submit'])) {
// collect value of input field
$name = $_REQUEST['username'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
else
{
?>
<form method="post" action="#">
Name: <input type="text" name="username">
<input type="submit" name="submit">
</form>
<?php } ?>
Q #31) What is the difference between for and foreach loop in PHP?
Answer:
for loop is mainly used for iterating a pre-defined number of times and foreach loop is used for
reading array elements or MySQL result set where the number of iteration can be unknown.
Sample code:
//Loop will iterate for 5 times
for ($n = 0; $n <= 5; $n++) {
echo "The number is: $n <br>";
}
Sample code:
//Loop will iterate based on array elements
$parts = array("HDD", "Monitor", "Mouse", "Keyboard"); 
foreach ($parts as $value) {
    echo "$value <br>";
}
</pre>
<span style="color: #ff6600;"><strong>Q #32) How long does a PHP session last for?</strong></sp
 
<strong>Answer:</strong> By default, session data will last for 24 minutes or 1440 seconds in PH
<strong>gc_maxlifetime directive</strong> in php.ini file.
 
To set the session time for 30 minutes, open php.ini file and set the value of <strong>gc_maxlif
 
<strong>gc_maxlifetime = 1800</strong>
 
<strong><span style="color: #ff6600;"><strong>Q #33) What is the difference between “= =” and “
 
<strong><strong>Answer:</strong></strong>
 
“= =” is called an equivalent operator that is used to check only the equivalency of two values
 
<span style="text-decoration: underline;"><strong>Sample code:</strong></span>
 
10 and “10” are equivalent by values. So, if condition will be true and print “n, is equal to 10”
<pre>$n = 10;
if ($n == "10")
echo "n is equal to 10"; //This will print
 
else
echo "n is not equal to 10";
“= = =” is called strictly equivalent operator that is used to check the equivalency of two values by
comparing both data types and values.

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.

Some major error types are mentioned below:


Fatal Errors– The execution of the script stops when this error occurs.
Sample code:
In the following script, f1() function is declared but f2() function is called which is not declared.
The execution of the script will stop when f2() function will call. So, “Testing Fatal Error” will not
be printed.
function f1()
{ echo "function 1";
}
f2();
echo “Testing Fatal Error”;
Parse Errors– This type of error occurs when the coder uses a wrong syntax in the script.
Sample code:
Here, semicolon(;) is missing at the end of the first echo statement.

echo "This is a testing script<br/>"


echo "error";
Warning Errors- This type of error does not stop the execution of a script. It continues the script
even after displaying the error.
Sample code:
In the following script, if the test.txt file does not exist in the current location then a warning
message will display to show the error and print “Opening File” text by continuing the execution.
$handler = fopen("test.txt","r");
echo "Opening File";
Notice Errors- This type of error shows a minor error of the script and continues the execution
after displaying the error.
Here, the variable, $a is defined but $b is not defined. So, a notice of undefined variable will
display for “echo $b” statement and print “Checking notice error” by continuing the script.
Sample code:
$a = 100;
echo $b;
echo "Checking notice error";
Q #37) Does PHP support multiple inheritances?
Answer:
PHP does not support multiple inheritances. To implement the features of multiple inheritances,
the interface is used 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.

Q #39) What is the use of mysqli_real_escape_string() function?


Answer:
mysqli_real_escape_string() function is used to escape special characters from the string for
using a SQL statement

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.

This type of cookie can be declared as follows,

setccookie ("cookie_name", "cookie_value", strtotime("+2 years");

Q #42) How can a cross-site scripting attack be prevented by PHP?


Answer:
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.

Q #43) Which PHP global variable is used for uploading a file?


Answer:
$_FILE[] array contains all the information of an uploaded file.

The use of various indexes of this array is mentioned below:


$_FILES[$fieldName][‘name'] – Keeps the original file name.
$_FILES[$fieldName][‘type'] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size'] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name'] – Keeps the temporary file name which is used to store the
file in the server.
$_FILES[$fieldName][‘error'] – Contains error code related to the error that appears during the
upload.
Q #44) What is meant by public, private, protected, static and final scopes?
Answer:
 Public– Variables, classes, and methods which are declared public can be accessed from
anywhere.
 Private– Variables, classes and methods which are declared private can be accessed by
the parent class only.
 Protected– Variables, classes, and methods which are declared protected can be
accessed by the parent and child classes only.
 Static– The variable which is declared static can keep the value after losing the scope.
 Final– This scope prevents the child class to declare the same item again.
Q #45) How can image properties be retrieved in PHP?
Answer:
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.
Q #46) What is the difference between abstract class and interface?
Answer:
 Abstract classes are used for closely related objects and interfaces are used for unrelated
objects.
 PHP class can implement multiple interfaces but can’t inherit multiple abstract classes.
 Common behavior can be implemented in the abstract class but not an interface.
Q #47) What is garbage collection?
Answer:
It is an automated feature of PHP.
When it runs, it removes all sessions data which are not accessed for a long time. It runs on /tmp
directory which is the default session directory.

PHP directives which are used for garbage collection include:


 session.gc_maxlifetime (default value, 1440)
 session.gc_probability (default value, 1)
 session.gc_divisor (default value, 100)
Q #48) Which library is used in PHP to do various types of Image work?
Answer:
Using GD library, various types of image work can be done in PHP. Image work includes rotating
image, cropping an image, creating image thumbnail etc.

Q #49) What is URL rewriting?


Answer:
Appending the session ID in every local URL of the requested page for keeping the session
information is called URL rewriting.

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.

Q #50) What is PDO?


Answer:
The full form of PDO is PHP Data Objects.

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.

PHP Interview Question #1

What’s the difference between the include() and require() functions?


(Question provided by  Laszlo Levente Mári)

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.

PHP Interview Question #2

How can we get the IP address of the client?


(Question provided by  Laszlo Levente Mári)
This question might show you how playful and creative the candidate is because
there are many options. $_SERVER["REMOTE_ADDR"]; is the easiest solution, but the
candidate can write x line scripts for this question.

PHP Interview Question #3

What’s the difference between unset() and unlink()


(Question provided by  Laszlo Levente Mári)

unset() sets a variable to “undefined” while unlink() deletes a file we pass to it


from the file system.

PHP Interview Question #4

What is the output of the following code:

$a = '1';

$b = &$a;

$b = "2$b";

echo $a.", ".$b;

PHP Interview Tip #2

“During the interview of a potential candidate I am aiming to understand how


updated they are with the new language features as well as their level of
understanding of basic operations. In my opinion, this will define how good a
developer will become in the future.”  ~Agli Pançi, Lead Developer

PHP Interview Question #5

What are the main error types in PHP and how do they differ?
(Question provided by  Agli Pançi)

In PHP there are three main type of errors:

 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.

Understanding the error types is very important as they help developers


understand what is going on during the development, and what to look out for
during debugging.

PHP Interview Question #6

What is the difference between GET and POST?


(Question provided by  Agli Pançi)

 GET displays the submitted data as part of the URL, during POST this
information is not shown as it’s encoded in the request.

 GET can handle a maximum of 2048 characters, POST has no such


restrictions.
 GET allows only ASCII data, POST has no restrictions, binary data are also
allowed.

 Normally GET is used to retrieve data while POST to insert and update.

Understanding the fundamentals of the HTTP protocol is very important to have


for a PHP developer, and the differences between GET and POST are an
essential part of it.

PHP Interview Question #7

How can you enable error reporting in PHP?


(Question provided by  Agli Pançi)

Check if “display_errors” is equal “on” in the php.ini or declare


“ini_set('display_errors', 1)” in your script.
Then, include “error_reporting(E_ALL)” in your code to display all types of error
messages during the script execution.

Enabling error messages is very important especially during the debugging


process as one can instantly get the exact line that is producing the error and can
see also if the script in general is behaving correctly.

PHP Interview Question #8

What are Traits?


(Question provided by  Agli Pançi)

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.

PHP Interview Question #9

Can the value of a constant change during the script’s execution?


(Question provided by  Agli Pançi)

No, the value of a constant cannot be changed once it’s declared during the PHP
execution.

PHP Interview Question #10

Can you extend a Final defined class?


(Question provided by  Agli Pançi)

No, you cannot extend a Final defined class. A Final class or method declaration


prevents child class or method overriding.

PHP Interview Question #11

What are the __construct() and __destruct() methods in a PHP class?


(Question provided by  Agli Pançi)

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

How we can get the number of elements in an array?


(Question provided by  Agli Pançi)

The count() function is used to return the number of elements in an array.

Understanding of arrays and array related helper functions is important for any
PHP developer.

PHP Interview Question #13

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

The value of the variable input is a string 1,2,3,4,5,6,7. How would you get


the sum of the integers contained inside input?
(Question provided by  Oscar Andrés Monroy Medina )

<?php

echo array_sum(explode(',',$input));

?>

The explode function is one of the most used functions in PHP, so it’s important to


know if the developer knows this function. There is no unique answer to this
question, but the answer must be similar to this one.

PHP Interview Question #15

Suppose you receive a form submitted by a post to subscribe to a


newsletter. This form has only one field, an input text field named email.
How would you validate whether the field is empty? Print a message "The
email cannot be empty" in this case.
(Question provided by  Oscar Andrés Monroy Medina )

<?php

if(empty($_POST['email'])){

echo "The email cannot be empty";

?>
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.

PHP Interview Question #15

Suppose that you have to implement a class named Dragonball. This class


must have an attribute named ballCount (which starts from 0) and a
method iFoundaBall. When iFoundaBall is called, ballCount is increased by
one. If the value of ballCount is equal to seven, then the message You can ask

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;

public function __construct(){

$this->ballCount=0;

public function iFoundaBall(){

$this->ballCount++;
if($this->ballCount===7){

echo "You can ask for your wish.";

$this->ballCount=0;

?>

This question will evaluate a candidate’s knowledge about OOP.

PHP Interview Question #16

What are the 3 scope levels available in PHP and how would you define
them?
(Question provided by  Merlyn Coslett)

Private – Visible only in its own class


Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current
class

This is important for any PHP developer to know because it shows an


understanding that building applications is more than just being able to write
code. One must also have an understanding about privileges and accessibility of
that code. There are times protected variables or methods are extremely
important, and an understanding of scope is needed to protect the integrity of the
data in your application along with provide a clear path through the code.
PHP Interview Question #17

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.

This is important for any developer who is looking to enter a team-based /


application development job to know. Getters and setters are often used when
dealing with objects, especially ones that will end up in a database or other
storage medium. Because PHP is commonly used to build web applications,
developers will run across getters and setters in more advanced environments.
They are extremely powerful yet not talked about very much. It is impressive if a
developer shows that he/she knows what they are and how to use them early on.

PHP Interview Question #18

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.

PHP Interview Question #19

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.

PHP Interview Question #20

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

What does the following code output?


(Question provided by  Kordian Bruck)

$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.

PHP Interview Question #22

Why would you use === instead of ==?


(Question provided by  Kordian Bruck)

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

What are PSRs? Choose 1 and briefly describe it.


(Question provided by  Jad Joubran)

PSRs are PHP Standards Recommendations that aim at standardising common


aspects of PHP Development.

An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-
2 here.

PHP Interview Question #24

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.

PHP Interview Question #25

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.

PHP Coding Questions and Answers – While Loops – 2


This set of Tricky PHP Interview Questions & Answers focuses on “While Loops – 2”.

1. What will be the output of the following PHP code?


1. <?php
2. $i = 0;
3. while($i = 10)
4. {
5. print "hi";
6. }
7. print "hello";
8. ?>

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

7. 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) 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?

A Database Management System (DBMS) is a program that controls creation,


maintenance and use of a database. DBMS can be termed as File Manager that
manages data in a database rather than saving it in file systems.

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.

Example: SQL Server.

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.

Standard SQL Commands are Select.

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.

Example: School Management Database, Bank Management Database.

5. What are tables and Fields?

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.

Field: Emp ID, Emp Name, Date of Birth.

Data: 201456, David, 11/15/1960.


6. What is a primary key?

A primary key is a combination of fields which uniquely specify a row. This is a


special kind of unique key, and it has implicit NOT NULL constraint. It means,
Primary key values cannot be NULL.

7. What is a unique key?

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.

8. What is a foreign key?

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.

10. What are the types of join and explain each?

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.

11. What is normalization?

Normalization is the process of minimizing redundancy and dependency by


organizing fields and table of a database. The main aim of Normalization is to add,
delete or modify field that can be made in a single table.

12. What is Denormalization.

DeNormalization is a technique used to access the data from higher to lower


normal forms of database. It is also process of introducing redundancy into a table
by incorporating data from the related tables.

13. What are all the different normalizations?

The normal forms can be divided into 5 forms, and they are explained below -.

 First Normal Form (1NF):.

This should remove all the duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.

 Second Normal Form (2NF):.

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.

 Third Normal Form (3NF):.

This should meet all requirements of 2NF. Removing the columns which are not
dependent on primary key constraints.

 Fourth Normal Form (4NF):.

Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.
14. What is a View?

A view is a virtual table which consists of a subset of data contained in a table.


Views are not virtually present, and it takes less space to store. View can have
data of one or more tables combined, and it is depending on the relationship.

15. What is an Index?

An index is performance tuning method of allowing faster retrieval of records from


the table. An index creates an entry for each value and it will be faster to retrieve
data.

16. What are all the different types of indexes?

There are three types of indexes -.

 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.

17. What is a Cursor?

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.

18. What is a relationship and what are they?

Database Relationship is defined as the connection between the tables in a


database. There are various data basing relationships, and they are as follows:.

 One to One Relationship.


 One to Many Relationship.
 Many to One Relationship.
 Self-Referencing Relationship.

19. What is a query?

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.

20. What is subquery?

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.

21. What are the types of subquery?

There are two types of subquery – Correlated and Non-Correlated.

A correlated subquery cannot be considered as independent query, but it can refer


the column in a table listed in the FROM the list of the main query.

A Non-Correlated sub query can be considered as independent query and the


output of subquery are substituted in the main query.

22. What is a stored procedure?

Stored Procedure is a function consists of many SQL statement to access the


database system. Several SQL statements are consolidated into a stored
procedure and execute them whenever and wherever required.

23. What is a trigger?

A DB trigger is a code or programs that automatically execute with response to


some event on a table or view in a database. Mainly, trigger helps to maintain the
integrity of the database.

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.

24. What is the difference between DELETE and TRUNCATE commands?

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.

26. What is a constraint?

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.

27. What is data Integrity?

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.

28. What is Auto Increment?

Auto increment keyword allows the user to create a unique number to be


generated when a new record is inserted into the table. AUTO INCREMENT
keyword can be used in Oracle and IDENTITY keyword can be used in SQL
SERVER.

Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and Non-Cluster Index?

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?

Datawarehouse is a central repository of data from multiple sources of information.


Those data are consolidated, transformed and made available for the mining and
online processing. Warehouse data have a subset of data called Data Marts.

31. What is Self-Join?

Self-join is set to be query used to compare to itself. This is used to compare


values in a column with other values in the same column in the same table. ALIAS
ES can be used for the same table comparison.

32. What is Cross-Join?

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.

33. What is user defined functions?

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.

34. What are all types of user defined functions?

Three types of user defined functions are.

 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.

35. What is collation?

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.

ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?

Following are different types of collation sensitivity -.


 Case Sensitivity – A and a and B and b.
 Accent Sensitivity.
 Kana Sensitivity – Japanese Kana characters.
 Width Sensitivity – Single byte character and double byte character.

37. Advantages and Disadvantages of Stored Procedure?

Stored procedure can be used as a modular programming – means create once,


store and call for several times whenever required. This supports faster execution
instead of executing multiple queries. This reduces network traffic and provides
better security to the data.

Disadvantage is that it can be executed only in the Database and utilizes more
memory in the database server.

38. What is Online Transaction Processing (OLTP)?

Online Transaction Processing (OLTP) manages transaction based applications


which can be used for data entry, data retrieval and data processing. OLTP makes
data management simple and efficient. Unlike OLAP systems goal of OLTP
systems is serving real-time transactions.

Example – Bank Transactions on a daily basis.

39. What is CLAUSE?

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.

Example – Query that has WHERE condition

Query that has HAVING condition.

40. What is recursive stored procedure?

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.

41. What is Union, minus and Interact commands?

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.

42. What is an ALIAS command?

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.

43. What is the difference between TRUNCATE and DROP statements?

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.

44. What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and return


single values. This can be calculated from the columns in a table. Scalar functions
return a single value based on the input value.

Example -.

Aggregate – max(), count - Calculated with respect to numeric.

Scalar – UCASE(), NOW() – Calculated with respect to strings.

45. How can you create an empty table from an existing table?

Example will be -.

Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same structure with
no rows copied.

46. How to fetch common records from two tables?

Common records result set can be achieved by -.

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 -.

To display even numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

To display odd numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]

48. How to select unique records from a table?

Select unique records from a table by using DISTINCT keyword.

Select DISTINCT StudentID, StudentName from Student.

49. What is the command used to fetch first 5 characters of the string?

There are many ways to fetch first 5 characters of the string -.

Select SUBSTRING(StudentName,1,5) as studentname from student


Select LEFT(Studentname,5) as studentname from student

50. Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % - Matches zero or more characters.


2. _(Underscore) – Matching exactly one character.

Example -.

Select * from Student where studentname like 'a%'


Select * from Student where studentname like 'ami_'

You might also like