12 Sept 2014

10 Always Asked JavaScript Interview Questions and Answers

Q1: How can we submit a form without a submit button? Or how can we submit a form using JavaScript?

Ans: A form can not only be submitted from html code but also from JavaScript code. You need to know the form name at least.Submit() function is used to submit the form instead of submit button.
E.g.
<form id="myForm" action="form_submitted.php">
<a href="javascript: submitMyForm()">Search</a>
</form>
<script>
function submitMyForm() {
document.getElementById("myForm").submit();
/* you can also use below DOM technique, but for that form tag should contain name of the form like this:
<form name=”myForm1”> */
document.forms["myForm1"].submit(); // or
document.myForm1.submit();
}
</script>


Q2: How to check that a variable is a number?

Ans: There is predefined function to check if a variable is a number or not.
isNaN: returns true if the argument is not a number. NAN itself means Not aNumber.
E.g.    isNaN(“hello”) // returns true.
isNaN(145) // returns false.

Q3: How we can create arrays in JavaScript?

Ans: There are two ways of creating arrays in JavaScript. Using,
1. Array literal
2. New keyword
Array literal Syntax:
var cars = [“BMW”, “AUDI”, “MERCEDES”, “HYUNDAI”];
New Keyword syntax:
var cars = new Array(“BMW”, “AUDI”, “MERCEDES”, “HYUNDAI”);
Both of them work exactly the same way, but it’s better to use first one as it is simple, speedy & easily readable.

Additional Information:

Accessing the values from an array, var carName = cars[0];
Modifying the first element, cars[0] = “VOLKSWAGEN”;
Note: Type of Array is object, so arrays are objects in JavaScript.

Q4: What is the data type of variables in JavaScript?

Ans: In JavaScript there are 7 types of data types – 3 primary, 2 composite and 2 special.
Primary(Primitive) – String, Number and Boolean.
Composite(Reference) – Object and Array.
Special – Null and Undefined.
Javascript has dynamic data types, means same variable can be used as different types.
E.g.    
var a;                   // a is undefined
var a = 55;          // a is a Number
var a = “Hello”;  // a is a String

Q5: Are JavaScript Scripts faster than server side scripts?

Ans: Yes, JavaScript is faster than any server side script because it’s written for client side browsers or machines, so it doesn't need web server’s support for execution.

Q6: How JavaScript code can be inserted into a webpage?

Ans: JavaScript can be inserted anywhere in the page – either <body> or in the <head> section, but it should be enclosed within <script></script> tags.
<script>
// some code here…
</script>
You might see in some old codes, ‘type=”text/javascript”’ in the script tag. It is no longer required as JavaScript is the default scripting languages these days in all major browsers.
<script type=”text/javascript”>
// some code here…
</script>
Note: Please remember external scripts shouldn't contain <SCRIPT> tags.

Q7: How to access external JavaScript files?

Ans: To access the external JavaScript file/files you need to add a reference of it in your code. The reference is provided by src attribute.
Syntax:
<script type="text/javascript" src="myscript.js"></script>
Here myscript.js is the external js file to be included.

Q8: What is the sum of this?

a. “1”+2+3
b. 2+5+”5”
c. 3+”7”+1
Ans: There is a simple rule in JavaScript – if you add a number and string, the result will be a string.
So,
“1”+2+3 = 123
2+5+”5” = 75
3+”7”+1 = 371
Remember operations are performed left to right. So if first one is a string, it considers everything after it as a string, so “1”+2+3 equals to 123 rather than 15.

Q9: How to resolve the JavaScript code rendering issue in old browsers? Or How to hide JavaScript code from old browsers that don’t support JavaScript?

Ans: This question is not much relevant these days as almost all browsers these days are quite advanced and support JavaScript. Still you should know about it. One can comment whole JavaScript code inside the SCRIPT tags.
Syntax:
<script type="text/javascript" language="JavaScript">
<!--
Put your JavaScript code here.
//-->
</script>
Old browsers will interpret JS code as an HTML comment.

Another way is using NOSCRIPT tag. It can be used both in HTML4 & 5 but not supported in XHTML.
The <noscript> tag defines an alternate content for users that have disabled scripts in their browser or have a browser that doesn't support script.
Syntax:
<script>
document.write("Hello")
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
In HTML 4, NOSCRIPT tag can be used only inside <body> element but in HTML 5 it can be used both inside <head> and <body>.

Q10: How to create new objects in JavaScript and assign object properties?

Ans: It’s very easy to create new objects in JavaScript.NEW keyword is used to create objects.
Syntax: varObj = new object(); or varObj = {}

You can also create your own objects and add properties to it.
E.g. var car = {name:”Audi”, model:”A6”, color:”black”, cc:”2500”}

Object properties can be assigned like this.
                Obj[“age”] = 22; or car.model = “R8”;



31 Aug 2014

10 Always Asked PHP Interview Questions and Answers

Q1: What is the difference between PHP 4 and PHP 5?

Ans: One should know the following changes to understand what has changed from PHP 4 to PHP 5.
  • PHP 4 is more of a procedural Language (but it had support for OOP) whereas PHP 5 is an object oriented language (it has more enhanced features of OOP like access specifiers, inheritance etc.). 
  • PHP5 removed register_globals, magic quotes, and safe mode. 
  • PHP 5 introduced many new things like –interfaces, functions, error level (E_STRICT), default extensions (like PDO, SimpleXML, etc.), MySQL extension named MySQLi (Improved MySQL), built in SOAP extension for interoperability with web services. 
  • PHP 5 gave 3 levels of accesses – Public,Private and Protected – which were not in PHP 4 earlier. 
  • PHP 4 was powered by Zend Engine 1.0, while PHP 5 is powered by Zend Engine 2. 
  • Major difference is PHP 5 got a new Object Model.In PHP 4 objects were handled as primitive types (everything was passed by value, including objects) while in PHP 5 objects are referenced by handle, and not by value (objects are passed by reference) 

Q2: What is the difference between $var and $$var? When is $$var used?

Ans: $var is a simple variable. Variables are declared in PHP using the $. So any variable can be declared as $x, $y, etc.
$$var instead is a reference variable. Consider the following example.
$var = “mango”;
$$var = 10;
echo $mango;// output: 10
  $$var is used when you need flexible variable naming.

Q3: What is the difference between require, require_once, include and include_once?

Ans: 
Difference between require and include:
Include: Used to include a file in a PHP code, but upon failure it generates a warning (E_WARNING) and the script will continue, the code will run.
Syntax: include 'filename'; or include(“filename”);

Require: Also used to include a file in a PHP code, but upon failure it generates an error (E_COMPILE_ERROR) and the script will halt.
Syntax: require 'filename'; or require(“filename”);
Remember r & r, error = require.

Difference between require_once and require:

require_once is identical to require the only difference being that if require_once is used, PHP will check if the file has already been included, and if so, it will not include it again.
Syntax: require_once ‘filename’; or require_once(“filename”);
include_once ‘filename’; or include _once(“filename”);
Note: Better to use include ‘filename’ instead of bracket () version;

Q4: What is the difference between GET and POST method?

Ans: These are the two most commonly used HTTP request methods.
GET: It requests data from the source.
POST: it submits data to be processed to a specific source.
Parameters
GET
POST
Caching
GET requests can be cached.
POST request never cached.
Data
Limited data can be sent like 2 kb.
Unlimited
Security
Data shown in url, non-secure
Totally secured
Browser History
GET requests remains in browser history
POST requests don’t.
Safe for password/sensitive data sending?
No
Yes
Can be bookmarked?
Yes
No

Q5: What are various ways of sending data from browser to web server and vice versa?

Ans: Data could be send in many ways.

From browser to web server:

  1. Query string (www.example.com?abc=xyz)
  2. POST method ($_POST)
  3. Sessions ($_SESSION)

From Server to Browser:

  1. GET method ($_GET)
  2. Cookies (A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity)

Q6: What are commonly used HTTP status codes?

Ans: The commonly used HTTP status codes which you will encounter in your daily life are the following:
  • 200 – ok
  • 301 – Moved Permanently
  • 302 – Found
  • 303 – See other
  • 403 – Forbidden
  • 404 – Not found
  • 500 – Internal Server error
  • 502 – Bad Gateway
  • 503 – Service unavailable
There are actually 5 classes of response:
  • 1xx Informational (Request received, continuing process)
  • 2xx Success (Client action was received, understood, accepted & processed successfully)
  • 3xx Redirection (further action needs to be taken to complete the request)
  • 4xx Client error
  • 5xx Server error

Q7: What are various common HTTP header fields?

Ans: HTTP header fields provide information about the request, response or about the object sent in the message body. The common HTTP header fields are:

Client Request headers:

  • Cookie (The Cookie request-header field value contains a name/value pair of information stored for that URL. E.g. Cookie: name=value)
  • Authorization (it contains the authentication credentials for HTTP authentication. E.g. Authorization : credentials)

Server Response headers:

  • Location (used in redirection, or when a new resource has been created)
  • Refresh (used in redirection, or when a new resource has been created.)
E.g. syntax: header("refresh:5;url=wherever.php");
This syntax redirects to the desired page after 5 seconds.
E.g. syntax: header("refresh:0;url=wherever.php");
This syntax redirects to the desired page immediately.

Q8: What is .htaccess and why it is used?

Ans: 
  • .htaccess is directory-level configuration file.
  • The original purpose of .htaccess was to allow per-directory access control. For example requiring a password to access the content.
Common usages:
  • Authorization & authentication.
  • Rewriting URLs.
  • Block users by IP address or domain.
  • Allow a server to control caching by web browsers and proxies.
  • Customized error responses.
  • Enable server-side includes.

Q9: Describe about the different types of error in PHP?

Ans: There are 3 types of errors which are very common in PHP.
  1. Notices: These are run-time notices. These occur if the script found something that might be an error. These errors are not displayed to the user. E.g. Accessing a variable that has not yet been defined.
  2. Warnings: These are serious errors but non-fatal. These errors are by default displayed to the user but they don’t result in script termination. E.g. Attempting to include() a file which does not exist will generate a warning.
  3. Errors: These are fatal and critical errors. They result in script termination and are by default displayed to the user. E.g. Instantiating an object of a non-existent class, or calling a non-existent function.

Q10: What is SESSION and how it is set and unset?

Ans: 
  • Session is a simple way to store data for individual users against a unique session ID.
  • It persist state information between pages.
  • $_SESSION is the global variable which gets set when session is started.
  • Manually sessions can be started using session_start() function.
Registering a variable:
<?php
session_start();
$_SESSION[‘key’] = value;

?>
Un-registering a variable:
<?php
session_start();
unset($_SESSION[‘key’]);

?>
Completely destroy/reset all session data:
<?php
session_destroy();
?>