http://www.ng-newsletter.com/posts/validations.html
This blog contains the all info about the angularjs javascript jquery with some examples ane some interview questions
Tuesday, March 25, 2014
Monday, March 24, 2014
angularjs important links
http://blog.liftoffllc.in/2013/10/angularjs-form-dos-donts.html
http://andru.co/building-a-simple-single-page-application-using-angularjs
http://outbottle.com/angularjs-a-crash-course-in-processing-ajax-json/
https://spring.io/guides/gs/consuming-rest-angularjs/
http://slides.yearofmoo.com/fitc-dec-2013-slides/index.html#/27
http://angular-ui.github.io/bootstrap/
http://www.ideyatech.com/2013/11/angularjs-intro/
http://andru.co/building-a-simple-single-page-application-using-angularjs
http://outbottle.com/angularjs-a-crash-course-in-processing-ajax-json/
https://spring.io/guides/gs/consuming-rest-angularjs/
http://slides.yearofmoo.com/fitc-dec-2013-slides/index.html#/27
http://angular-ui.github.io/bootstrap/
http://www.ideyatech.com/2013/11/angularjs-intro/
Friday, March 21, 2014
angularjs
For linking to pages, we’ll use the
In angularjs after url we pass the parameters .ie done using the #. i.e for appending the parameter along with the url we use the # in angularjs.
#
. We don’t want the browser to think we are actually travelling to about.html or contact.html.In angularjs after url we pass the parameters .ie done using the #. i.e for appending the parameter along with the url we use the # in angularjs.
angularjs $routeProvider
$routeProvider, it provide the route based on the path i.e we have url after that that alongwith url then after slash we place or pass the parameter based on that parameter we
load the url and controller. i.e $routeprovider related with the ng-view in the index page, i.e it loads the data inside the ng-view.
$scope.servicesName = $routeParams.serviceName || constants.allCaches;
as per the above statemet $routeParams is used to get the parameter from the url. in the above example serviceName is the parameter name given the app.js i.e insidethe $routeprovider
load the url and controller. i.e $routeprovider related with the ng-view in the index page, i.e it loads the data inside the ng-view.
$scope.servicesName = $routeParams.serviceName || constants.allCaches;
as per the above statemet $routeParams is used to get the parameter from the url. in the above example serviceName is the parameter name given the app.js i.e insidethe $routeprovider
To make the ajax calls we use the $http in angularjs
$http is a obejct it has several methods like get, post, delete
The below is the example of creating the service:
.service('clusterresult', function($http){
this.getResult = function (){
return $http.get('DataFiles/clusterDetails.json');
};
this.getItems = function () {
return $http.get('DataFiles/items.json');
}
})
In the above example clusterresult is the name of the service, in other we also called it as a class.
so inside this service we creted the method or function to return or get teh data.
so to access the data we need to call the service name.method or function name, so as per the above example clusterresult.getResult()
service name is a class inside that we create the methods.
creating the controller with dependency injection:
.controller('homeController',['$scope','clusterresult',function($scope,clusterresult,$http){ ............ }]);
in the above example homeController is the name of the controller and
inside the [] square brackets '$scope','clusterresult' are dependencies that means these are available to controller,we can make use of them as parameters inside the function
i.e function($scope,clusterresult,$http), here the names we mentioned at both places are same. we can also give the names as we like inside the function
i.e function(a,b) here a refer the '$scope' and b refer the 'clusterresult'.
so these are available for the function we used as a parameters
The below is the example of creating the service:
.service('clusterresult', function($http){
this.getResult = function (){
return $http.get('DataFiles/clusterDetails.json');
};
this.getItems = function () {
return $http.get('DataFiles/items.json');
}
})
In the above example clusterresult is the name of the service, in other we also called it as a class.
so inside this service we creted the method or function to return or get teh data.
so to access the data we need to call the service name.method or function name, so as per the above example clusterresult.getResult()
service name is a class inside that we create the methods.
creating the controller with dependency injection:
.controller('homeController',['$scope','clusterresult',function($scope,clusterresult,$http){ ............ }]);
in the above example homeController is the name of the controller and
inside the [] square brackets '$scope','clusterresult' are dependencies that means these are available to controller,we can make use of them as parameters inside the function
i.e function($scope,clusterresult,$http), here the names we mentioned at both places are same. we can also give the names as we like inside the function
i.e function(a,b) here a refer the '$scope' and b refer the 'clusterresult'.
so these are available for the function we used as a parameters
Thursday, March 20, 2014
Different types of layouts
Adaptive design:
based on device the content will change or components based on device the features may vary of the application from backend it will operated. i.e based on useragent of the browser.
Elastic Layout: the wbsite or web application looks same in all devices irrespective of size of the window.
i.e here they uses the 100% width, so it adapt same in every device or desktop. here we don't use the media queries.
Responsive Layout: The web site components may vary from device to device. i.e menu in dsktop is horizontal the same in menu is vertical and few of the componets may hide or few of them styles are changed. this is all done by using the media queries.
based on device the content will change or components based on device the features may vary of the application from backend it will operated. i.e based on useragent of the browser.
Elastic Layout: the wbsite or web application looks same in all devices irrespective of size of the window.
i.e here they uses the 100% width, so it adapt same in every device or desktop. here we don't use the media queries.
Responsive Layout: The web site components may vary from device to device. i.e menu in dsktop is horizontal the same in menu is vertical and few of the componets may hide or few of them styles are changed. this is all done by using the media queries.
what are the new elements in html5 except semantic?
New Media Elements
Tag Description
<audio> Defines sound or music
content
<video> Defines video or movie
content
<source> Defines sources for
<video> and <audio>
<track> Defines tracks for
<video> and <audio>
<embed> Defines containers for
external applications (like plug-ins)
New Form Elements
Tag Description
<datalist> Defines pre-defined
options for input controls
<keygen> Defines a key-pair
generator field (for forms)
<output> Defines the result of a
calculation
reference
link:http://www.w3schools.com/html/html5_new_elements.asp
what is localstorage with example ?
application cache with example ?
What is parseint in javascript ?
JavaScript parseInt() Function. The
parseInt() function parses a string and returns an integer.
what are draw backs of jquery mobile?
var a = true && help;
alert ('a'); what is the output?
var a = true ^^ help;
alert ('a'); what is the output?
if (i=0, i<5, i++;){
var = 20;
}
alert ();
What are css3 selectors?
:first-of-type p:first-of-type Selects
every <p> element that is the first <p> element of its
parent 3
:last-of-type p:last-of-type Selects
every <p> element that is the last <p> element of its
parent 3
:only-of-type p:only-of-type Selects
every <p> element that is the only <p> element of its
parent 3
:only-child p:only-child Selects every
<p> element that is the only child of its parent 3
:nth-child(n) p:nth-child(2) Selects
every <p> element that is the second child of its parent 3
:nth-last-child(n) p:nth-last-child(2) Selects
every <p> element that is the second child of its parent,
counting from the last child 3
:nth-of-type(n) p:nth-of-type(2) Selects
every <p> element that is the second <p> element of its
parent 3
:nth-last-of-type(n) p:nth-last-of-type(2) Selects
every <p> element that is the second <p> element of its
parent, counting from the last child 3
:last-child p:last-child Selects every
<p> element that is the last child of its parent 3
:root :root Selects the document's root
element 3
:empty p:empty Selects every <p>
element that has no children (including text nodes) 3
:target #news:target Selects the
current active #news element (clicked on a URL containing that anchor
name) 3
:enabled input:enabled Selects every
enabled <input> element 3
:disabled input:disabled Selects every
disabled <input> element 3
:checked input:checked Selects every
checked <input> element 3
:not(selector) :not(p) Selects every
element that is not a <p> element 3
::selection ::selection Selects the
portion of an element that is selected by a user
What are pseudo classes for p tag?
:first-letter p:first-letter Selects
the first letter of every <p> element 1
:first-line p:first-line Selects the
first line of every <p> element 1
:first-child p:first-child Selects
every <p> element that is the first child of its parent 2
:before p:before Insert content before
the content of every <p> element 2
:after p:after Insert content after
every <p> element 2
:lang(language) p:lang(it) Selects
every <p> element with a lang attribute equal to "it"
(Italian) 2
element1~element2 p~ul Selects every
<ul> element that are preceded by a <p> element 3
Quicker mode in html?
If we are not specify the doctype in
our htmlpage, we may not get the same output in all pages I.e the
browser moves to quicker mode.
Css3 gradients?
Web workers?
Diff between undefined and null?
Many a times we often get confused on
whats the difference between UNDEFINED and NULL.
undefined means a variable has been
declared but has not yet been assigned a value. On the other hand,
null is an assignment value. It can be assigned to a variable as a
representation of no value.
Also, undefined and null are two
distinct types: undefined is a type itself (undefined) while null is
an object.
Unassigned variables are initialized by
JavaScript with a default value of undefined. JavaScript never sets a
value to null. That must be done programmatically.
Datatypes in javascript?
Numerical, string, boolean, undefined,
null
how to draw a line in canvas ?
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"
width="300" height="150" style="border:1px
solid #d3d3d3;">
Your browser does not support the HTML5
canvas tag.</canvas>
<script>
var
c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();
</script>
</body>
</html>
How to show the second page as the
default page in a jQuery mobile Multi-page template structure?
This part will prevent normal page
load. Don't forget, like in my example mobileinit MUST be initialized
before jQuery Mobile is initialized. Below code is used to stop
showing the first page in the jqm spa application.
$(document).on("mobileinit",function()
{
$.mobile.autoInitializePage =
false;
});
to show the second page by hiding the
first page we have to use the below code
$(document).ready(function() {
window.location.hash = 'home';
$.mobile.initializePage();
});
In the above home
is the id of the second page in the application.
What is flex model in html5?
What is
flexibility?
The box-flex style
property defines if a child of a flexbox should be flexible or
inflexible, and helps to define its flexibility ratio relative to its
siblings. Let's demonstrate what that actually means. First, let's
start with three boxes.
<div
id="flexbox">
<p>child
1</p>
<p>child
2</p>
<p>child
3</p>
</div>
Now, we want them
to lay out horizontally next to each other, and their heights should
always match, regardless of the content in each. How would you
currently tackle this? Most, without thinking, would simply float
these paragraphs, perhaps adding overflow:hidden; to the parent in
order to clear the floats. Nothing very special. But we could also do
it quite easily with flexbox:
#flexbox {
display: box;
box-orient:
horizontal;
}
In the above code,
we’re simply telling the parent to behave according to this flexbox
model, and to lay out all its children along the horizontal axis. No
floats. Yay.
The widths of the
children remain as specified (or their inherent width if not
specified). This means that if the total widths of all the children
is less than the total width of the parent, we’ll get something
like this:
By default,
children of a flexbox remain inflexible. That might seem a little
odd, but it's it gives a chance for the children to opt into the
flexible experience. But what if you wanted children one and two to
have specific widths and child three to adjust itself depending on
the available space within the parent? Flexbox to the rescue:
#flexbox {
display: box;
box-orient:
horizontal;
}
#flexbox >
p:nth-child(3) {
box-flex: 1;
}
Here, we’re
telling the last child to become flexible, and to take up available
space. Since we’ve only allocated space to one element, it will
take up all of the available space:
The 3rd child
element, having flex, takes up the available space.
Note that the
element only becomes flexible along the orientation axis of the box;
in this case the element becomes flexible horizontally.
The value for
box-flex is relative. So if we were to make the second and third
children flexible:
#flexbox {
display: box;
box-orient:
horizontal;
}
#flexbox >
p:nth-child(2),
#flexbox >
p:nth-child(3) {
box-flex: 1;
}
These would each
take up the same amount of available space, in fact dividing the
available space equally between them.
2 of the 3 child
elements share the available space in the parent element.
Now we could also
play with setting the box-flex of children 1, 2, and 3 to be 1, 2, 3
respectively and they would then absorb the extra space of their
parent in that ratio. But instead, lets put this into action.
document.ready function replacing in
jquery mobile or what is eualent to $(document).ready in jqm?
$(document).on('pageinit', function(){
});
$(document).on('pageinit') vs
$(document).ready()
The first thing you learn in jQuery is
to call code inside the $(document).ready() function so everything
will execute as soon as the DOM is loaded. However, in jQuery Mobile,
Ajax is used to load the contents of each page into the DOM as you
navigate. Because of this $(document).ready() will trigger before
your first page is loaded and every code intended for page
manipulation will be executed after a page refresh. This can be a
very subtle bug. On some systems it may appear that it works fine,
but on others it may cause erratic, difficult to repeat weirdness to
occur.
Classic jQuery syntax:
$(document).ready(function() {
});
To solve this problem (and trust me
this is a problem) jQuery Mobile developers created page events. In a
nutshell page events are events triggered in a particular point of
page execution. One of those page events is a pageinit event and we
can use it like this:
$(document).on('pageinit', function() {
});
We can go even further and use a page
id instead of document selector. Lets say we have jQuery Mobile page
with an id index:
<div data-role="page"
id="index">
<div data-theme="a"
data-role="header">
<h3>
First Page
</h3>
<a href="#second"
class="ui-btn-right">Next</a>
</div>
<div data-role="content">
<a href="#"
data-role="button" id="test-button">Test
button</a>
</div>
<div data-theme="a"
data-role="footer" data-position="fixed">
</div>
</div>
To execute a code that will only
available to the index page we could use this syntax:
$('#index').on('pageinit', function() {
});
Pageinit event will be executed every
time page is about be be loaded and shown for the first time. It will
not trigger again unless page is manually refreshed or ajax page
loading is turned off. In case you want code to execute every time
you visit a page it is better to use pagebeforeshow event.
Here's a working example :
http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.
Few more notes on this question. No
matter if you are using 1 html multiple pages or multiple html files
paradigm it is advised to separate all of your custom javascript page
handling into a single separate js file. This will note make your
code any better but you will have much better code overview,
especially while creating a jQuery Mobile application.
There's also another special jQuery
Mobile event and it is called mobileinit.When jQuery Mobile starts,
it triggers a mobileinit event on the document object. To override
default settings, bind them to mobileinit. One of a good examples of
mobileinit usage is turning off ajax page loading, or changing
default ajax loader behavior.
$(document).on("mobileinit",
function(){
//apply overrides here
});
Page events transition order
First all events can be found here:
http://api.jquerymobile.com/category/events/
Lets say we have a page A and a page B,
this is a unload/load order:
page B - event pagebeforecreate
page B - event pagecreate
page B - event pageinit
page A - event pagebeforehide
page B - event pagebeforeshow
page A - event pageremove
page A - event pagehide
page B - event pagebeforeshow
page B - event pageshow
For better page events understanding
read this:
pagebeforeload, pageload and
pageloadfailed are fired when an external page is loaded
pagebeforechange, pagechange and
pagechangefailed are page change events. These events are fired when
a user is navigating between pages in the applications.
pagebeforeshow, pagebeforehide,
pageshow and pagehide are page transition events. These events are
fired before, during and after a transition and are named.
pagebeforecreate, pagecreate and
pageinit are for page initialization.
pageremove can be fired and then
handled when a page is removed from the DOM
Page loading jsFiddle example:
http://jsfiddle.net/Gajotres/QGnft/
If AJAX is not enabled, some events may
not fire.
Prevent page transition
If for some reason page transition
needs to be prevented on some condition it can be done with this
code:
$(document).on('pagebeforechange',
function(e, data){
var to = data.toPage,
from = data.options.fromPage;
if (typeof to === 'string') {
var u =
$.mobile.path.parseUrl(to);
to = u.hash || '#' +
u.pathname.substring(1);
if (from) from = '#' +
from.attr('id');
if (from === '#index' &&
to === '#second') {
alert('Can not transition
from #index to #second!');
e.preventDefault();
e.stopPropagation();
// remove active status on
a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active
ui-focus ui-btn');;
}
}
});
This example will work in any case
because it will trigger at a begging of every page transition and
what is most important it will prevent page change before page
transition can occur.
Here's a working example:
Prevent multiple event
binding/triggering
jQuery Mobile works in a different way
then classic web applications. Depending on how you managed to bind
your events each time you visit some page it will bind events over
and over. This is not an error, it is simply how jQuery Mobile
handles its pages. For example, take a look at this code snipet:
$(document).on('pagebeforeshow','#index'
,function(e,data){
$(document).on('click',
'#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example:
http://jsfiddle.net/Gajotres/CCfL4/
Each time you visit page #index click
event will is going to be bound to button #test-button. Test it by
moving from page 1 to page 2 and back several times. There are few
ways to prevent this problem:
Solution 1
Best solution would be to use pageinit
to bind events. If you take a look at an official documentation you
will find out that pageinit will trigger ONLY once, just like
document ready, so there's no way events will be bound again. This is
best solution because you don't have processing overhead like when
removing events with off method.
Working jsFiddle example:
http://jsfiddle.net/Gajotres/AAFH8/
This working solution is made on a
basis of a previous problematic example.
Solution 2
Remove event before you bind it:
$(document).on('pagebeforeshow',
'#index', function(){
$(document).off('click',
'#test-button').on('click', '#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example:
http://jsfiddle.net/Gajotres/K8YmG/
Solution 3
Use a jQuery Filter selector, like
this:
$('#carousel
div:Event(!click)').each(function(){
//If click is not bind to #carousel
div do something
});
Because event filter is not a part of
official jQuery framework it can be found here:
http://www.codenothing.com/archives/2009/event-filter/
In a nutshell, if speed is your main
concern then Solution 2 is much better then Solution 1.
Solution 4
A new one, probably an easiest of them
all.
$(document).on('pagebeforeshow',
'#index', function(){
$(document).on('click',
'#test-button',function(e) {
if(e.handled !== true) // This
will prevent event triggering more then once
{
alert('Clicked');
e.handled = true;
}
});
});
Working jsFiddle example:
http://jsfiddle.net/Gajotres/Yerv9/
javascript objects
In JavaScript not every data is an
object. There exist a few primitive types, like strings,
numbers and boolean which are not objects. For each of this
types there exists a constructor which outputs an object with similar
behavior: Number, String and Boolean. To confuse matters, one
actually can call methods on primitive types - they will be converted
to the corresponding objects during this operation, and then
converted back. For instance one can do
var a = 4.1324;
a.toFixed(1) // outputs 4.1
Yet if you try to compare primitive
types and objects with strict equality, the difference shows up
var a = new Number(4);
var b = 4;
a === b; // False!!!
typeof a; // 'object'
typeof b; // 'number'
Actually of one tries to compare
objects, they turn out to be different anyway:
var a = new Number(4);
var b = new Number(4);
a === b; // False!!!
(From a conceptual point of view I sort
of understand the distinction. Objects can have additional
properties, hence the should not compare to equal unless they are
actually the same. So if we want to have 4 === 4 we need to use a
type which is not an object. But this dilemma is faced by any
sufficiently dynamic programming language, yet Javscript is the only
one I know where there are two types - one objectful and one not -
for numbers or strings.)
Passing by Reference vs Passing
by Value
It is critical to know whether a
variable you are accessing has been passed by reference or value. Not
knowing the difference can lead to spaghetti code and odd behavior
that is difficult to troubleshoot.
Q:In JavaScript, are objects passed by
reference or by value?
A:By reference
Explanation:
In JavaScript, all objects are passed
by reference. When you make a change to a reference to an object, you
change the actual object. Primitive types are passed by value.
JavaScript Interview Questions:
Object-Oriented JavaScript
in Object-Oriented JavaScript.
Object Properties and Methods
In JavaScript, Objects have two things:
properties and methods. Methods are simply properties that have a
function assigned to them.
Q: What do you call an object’s
property when it has been assigned to a function
A: A “method”
Q: True of False: A function can
have its own properties and methods.
A: True
Explanation:
Functions inherit from Object. You can
add properties and methods to a function at any time. Run the
following code in your JavaScript console and you will see this
behavior:
//create a function
function foo(){};
//assign a property
foo.color = 'red';
//assign a method
foo.sayHello = function(){
alert("hello!");
};
//inspect the object
console.dir(foo); //inspect the
properties and methods of off
//execute the method
foo.sayHello();// "hello!"
//overwrite a method
foo.sayHello = function(){
alert("this is a different
message");
};
//execute the method
foo.sayHello();// "his is a
different message"
Object Syntax
There are different ways to access the
properties of an object: bracket notation and dot notation. Care must
be taken when deciding which syntax to implement as their behavior
differs.
Q: What is the difference between
using dot notation and bracket notation when accessing an object’s
property?
A: If using dot notation, the property
must be a string and refer to a property that exists. When using
bracket notation, any valid JavaScript expression that produces a
value can be used inside the brackets, such as a variable or an an
array element.
Hint:
These are all valid lines of code:
foo = bar.name;
foo = bar["name"];
foo = bar[5 + 5];
foo = bar[ baz() ];
foo = bar[ baz[i] ];
Q: What is important to remember about
the last property’s value in a JavaScript object literal?
A : The last property’s value should
not be followed by a comma.
Hint: Most browsers will let you get
away with it if you forget, but Microsoft Internet Explorer will
complain about the extra comma.
Q: Given the following code, what
is very likely the reason that the programmer made the first letter
of “Foo” a capital letter?
?
1
2
3
var Foo = function(){
this.foo = "bar";
}
A: Foo is meant to be used as a
constructor function
Q: Given the following code, how
would you instantiate the function “Foo” and assign it to the
variable “bar”?
?
1
var Foo = function(){}
A:
?
1
var bar = new Foo();
Here is a jsFiddle.net example:
http://jsfiddle.net/vs2Fg/
Creating Objects
There is more than one way to create an
object in JavaScript. Which method you chose depends on the type of
Object you need to create. For example, there is a difference between
an Object Literal and and instance object in JavaScript. Also, while
arrays are instances of the Array() constructor, they are still
considered object.
Q:What are two ways in which the
variable “foo” can be assigned to an empty object?
A:
var foo = new Object();
var foo = {};
Explanation:
When creating a new empty object, you
can instantiate the Object() constructor, or you can simply create an
empty object literal. In either case, you can then add properties to
the new object.
Here is a jsFiddle.net example:
http://jsfiddle.net/W6X2T/
Q: True or False: When you create
an object literal, you must first instantiate the Object()
constructor
A: False
Explanation:
In order to create an Object Literal,
you assign a variable to an object. The syntax is as simple as var
foo = {}. A constructor function is used when creating an instance
object, which is a different process.
Q: True of False: You can only
instantiate a JavaScript constructor function once.
A: False
Explanation: You can make as many
instances as you want.
Q:When using the addEventListener()
method to create a click-handler for a DOM element, what is the value
of “this” inside of the callback you specify?.
A:The DOM element that was clicked.
Helpful Links:
The value of this within the handler
Javascript – Advanced event
registration models
Different Types of Objects
There is more than one type of object
in JavaScript. Some examples are: Functions, Arrays, DOM objects and
Date objects. Even NULL is technically an object, although it cannot
be mutated.
Q: True or False: A JavaScript
array is not an object
A: False
Explanation: JavaScript arrays are
objects. They inherit from the JavaScript Object, and have methods
and properties that are specific to arrays such as “length” and
“sort”
Here is a jsFiddle.net example:
http://jsfiddle.net/D2REh/
Q: If a string is a primitive
value, why does it have a split() method?
A:
Because any string has a wrapper object
that provides numerous methods for that type.
Explanation:
Although primitive JavaScript values do
not enjoy the “first-class” nature of objects, they have wrapper
objects that temporarily “wrap” the primitive value and provide
various methods. Once a primitive wrapper’s method has finished
executing, that primitive value is un-wrapped and returned to its
normal primitive state.
Helpful Links:
Wrapper Objects | Javascript: The
Definitive Guide
Minitech: The difference between
primitive types and their object wrappers
Q: What is the name of the object
that refers to the application used to view a web page?
A:
The “navigator” object
Q: Which object.property combination
provides a reference to the protocol used to view the current web
page?
A:
location.protocol
Q: True or False: The object
returned by the document.getElementsByTagName() method is an array
A:
False
Explanation:
The object returned by the
document.getElementsByTagName() method is an “HTMLCollection”.
This is an array-like object that has a “length” property, can be
enumerated, but is not an actual JavaScript array.
Helpful Links:
document.getElementsByTagName – Web
API reference | MDN
HTMLCollection – Web API reference |
MDN
Scope
Although the concept of scope in
JavaScript pertains specifically to the visibility of variables, it
is difficult to master object-oriented JavaScript without also
mastering scope. The two work hand-in-hand, laying the groundwork for
a very powerful and expressive language.
Q: True or False: An object literal
can be used to create private variables.
A:
False. Only functions can be used in
JavaScript to create privacy
Explanation:
All of the properties of a object
literal are public and can be easily mutated. The only way to create
private variable in JavaScript is by using a function. You can make a
property of an object literal a function (i.e. a “method”), and
use private variables in that function, but the named property will
always be public.
Q: If you omit the “var” keyword
when creating a variable in a function, it becomes a property of what
object?
A:
The window object
Explanation:
When omitting the “var” keyword,
the variable you create becomes an “implied global”. But implied
globals are not variables in a function. An implied global actually
becomes a property of the window object. Although the window object
is considered the “global” scope, it is an object, and any
variable declared in the global scope (intentionally or otherwise),
becomes a property of the window object.
Helpful Link:
Browser’s implied globals / Stoyan’s
phpied.com
Context
In JavaScript, context pertains to the
object within which a function is executed. Understanding context is
a critical step towards writing advanced Object-Oriented JavaScript.
Q: What is the difference between a
constructor function and a non-constructor function with respect to
the word “this”
A: In a non-constructor function,
“this” refers to the global context or if the function is
executed inside of another function, it refers to the context of the
outer function. In the instance object that is returned by a
constructor function, “this” refers to the context of that
function.
Explanation: JavaScript constructors
are more useful when you understand how they behave differently from
normal JavaScript functions and Object Literals.
Here is a jsFiddle.net example:
http://jsfiddle.net/nyFyE/
Passing by Reference vs Passing by
Value
It is critical to know whether a
variable you are accessing has been passed by reference or value. Not
knowing the difference can lead to spaghetti code and odd behavior
that is difficult to troubleshoot.
Q:In JavaScript, are objects
passed by reference or by value?
A:By reference
Explanation:
In JavaScript, all objects are passed
by reference. When you make a change to a reference to an object, you
change the actual object. Primitive types are passed by value.
Here is a jsFiddle.net example:
http://jsfiddle.net/pmMLc/
Object Mutation
One of the things that makes JavaScript
so expressive is its dynamic nature. Objects can be mutated at any
time during the execution of your script. Those who come to
JavaScript from conventional object-oriented languages such as C++
and Java sometimes find this behavior odd. One you become comfortable
to working in this manner, you can start to tap into the deeper
aspects of the language.
Q: True or False: Once you create
an object, you can add, remove or change properties of that object at
any time.
A: True
Explanation: JavaScript object are
mutable.
Here is a jsFiddle.net example:
http://jsfiddle.net/n3kR4/
Object Inheritance
JavaScript is a prototype-based
language, which means that it differs from conventional
object-oriented languages such as Java or C++. For example, when you
create an array, it inherits from the Array constructor, which
in-turn inherits from Object. You can create your own inheritance
chain using the JavaScript prototype object.
Q: What is the name of the
property that allows you to add properties and methods to an object,
as well as every object that inherits from it?
A: The ‘prototype’ property.
Explanation:
Understanding JavaScript Prototypes. |
JavaScript, JavaScript…
Q: How do you determine if a
JavaScript instance object was created from a specific constructor or
not?
A: Use the instanceof operator
Helpful links for the JavaScript
instanceof operator:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof
http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript
http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/
http://javascript.gakaa.com/operators-instanceof.aspx
Constructors
When instantiated, constructors return
an instance of themselves. It is important to understand the nature
of an instance object as it differs from an object literal in a
number of ways.
Q: Can a JavaScript constructor
return a primitive value (e.g. a number or a string)?
A: No.
Explanation:
A JavaScript constructor can only
return an object. When no return value is specified, it returns an
instance of itself. If an object is specified as the return value,
then that object is the return value. If any value other than an
object is specified as the return value, then it returns an instance
of itself.
This chapter describes the
predefined objects in core JavaScript: Array, Boolean, Date,
Function, Math, Number, RegExp, and String.
What is the relationship between
ECMAScript, Javascript and Jscript?
Javascript is the original name when the language was developed by
Netscape.
JScript is Microsoft's name of their own implementation.
ECMAScript is the name of the language standard developed by ECMA,
from the original Javascript implementation.
So, it's just one language, with different implementations.
Primitive Data Types in
javascript
There are three primitive data type of interest to us:
numbers
strings
boolean values
Composite Data Types
All composite data types can be treated as objects, but we normally
categorize them by their purpose as a data type.
Objects:
An object is a collection of named values, called the properties of
that object. Functions associated with an object are referred to as
the methods of that object.
Functions:
A function is a piece of code, predefined or written by the person
creating the JavaScript, that is executed based on a call to it by
name.
Arrays:
An Array is an ordered collection of data values.
JavaScript Object Literals
JavaScript also has two keyword literals that it considers to be
objects. These are null and undefined.
How will you detect the type and
version of a browser?
<script>
txt = "<p>Browser CodeName: " + navigator.appCodeName
+ "</p>";
txt+= "<p>Browser Name: " + navigator.appName +
"</p>";
txt+= "<p>Browser Version: " + navigator.appVersion +
"</p>";
txt+= "<p>Cookies Enabled: " +
navigator.cookieEnabled + "</p>";
txt+= "<p>Browser Language: " + navigator.language +
"</p>";
txt+= "<p>Browser Online: " + navigator.onLine +
"</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent
+ "</p>";
txt+= "<p>User-agent language: " +
navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
output:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36
Cookies Enabled: true
Browser Language: en-US
Browser Online: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48
Safari/537.36
User-agent language: undefined
How do you usually get away with
javascript errors in a web page?
Firefox firebug
Chrome developer tool ctrl+shift+j or f12
internet explorer f12
or http://www.jslint.com/
What is the use of innerHTML
property?
<script>
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3Schools";
document.getElementById('myAnchor').href="http://www.w3schools.com";
document.getElementById('myAnchor').target="_blank";
}
</script>
<a id="myAnchor"
href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()"
value="Change link">
output:
Microsoft chnagelink(it is button), whenever we click on the button
the above function is executed and replace the content inside the
anchor tag
What is pattern?
A pattern is a reusable solution that can be applied to commonly
occurring problems in software design - in our case - in writing
JavaScript web applications.
Simply put, a design pattern is a reusable software solution to a
specific type of problem that occurs frequently when developing
software. Over the many years of practicing software development,
experts have figured out ways of solving similar problems. These
solutions have been encapsulated into design patterns. So:
Types of Design Patterns
Creational patterns focus on ways to create objects or
classes. This may sound simple (and it is in some cases), but large
applications need to control the object creation process.
Structural design patterns focus on ways to manage
relationships between objects so that your application is architected
in a scalable way. A key aspect of structural patterns is to ensure
that a change in one part of your application does not affect all
other parts.
Behavioral patterns focus on communication between
objects.
"1" == 1; true
"1" === 1; false
"1" == true; true
"1" === false; false
current
version of javascript?
- relased in 2 years back
What’s relationship between JavaScript and ECMAScript? -
ECMAScript is yet another name for JavaScript (other names include
LiveScript). The current JavaScript that you see supported in
browsers is ECMAScript revision 3.
What are JavaScript types? - Number, String, Boolean,
Function, Object, Null, Undefined.
How do you convert numbers between different bases in JavaScript?
- Use the parseInt() function, that takes a string as the first
parameter, and the base as a second parameter. So to convert
hexadecimal 3F to decimal, use parseInt ("3F", 16);
What does isNaN function do? - Return true if the argument is
not a number.
What is negative infinity? - It’s a number in JavaScript, derived
by dividing negative number by zero.
What boolean operators does JavaScript support? - &&,
|| and !
What does "1"+2+4 evaluate to? - Since 1 is a
string, everything is a string, so the result is 124.
How about 2+5+"8"? - Since 2 and 5 are integers,
this is number arithmetic, since 8 is a string, it’s concatenation,
so 78 is the result.
What looping structures are there in JavaScript? - for, while,
do-while loops, but no foreach.
How do you create a new object in JavaScript? - var obj = new
Object(); or var obj = {};
How do you assign object properties? - obj["age"] =
17 or obj.age = 17.
What’s a way to append a value to an array? -
arr[arr.length] = value;
What is this keyword? - It refers to the current object.
Q: What
are Javascript closures?When would you use them?
A:
A closure is the local variables for a function – kept alive after
the function has returned, or
A closure is a stack-frame which is not deallocated when the
function returns.
A closure takes place when a function creates an environment that
binds local variables to it in such a way that they are kept alive
after the function has returned. A closure is a special kind of
object that combines two things: a function, and any local variables
that were in-scope at the time that the closure was created.
The following code returns a reference to a function:
function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}
Closures reduce the need to pass state around the application. The
inner function has access to the variables in the outer function
so there is no need to store the information somewhere that the inner
function can get it.
This is important when the inner function will be called after the
outer function has exited. The most common example of this is when
the inner function is being used to handle an event. In this case you
get no control over the arguments that are passed to the function so
using a closure to keep track of state can be very convenient.
How do I
append to an array in Javascript?
Use the push() function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
// display all values
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
If you're only appending a single variable, then your method works
just fine. If you need to append another array, use concat(...)
method of the array class:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar3);
Will spit out "1,2,3,4,5,6"
- The append() method inserts specified content at the end of the selected elements.
Q:
Replace the string "the lazy dog" with the string "the1
lazy2 dog3".
A:
// there are several ways to do this, .split or .replace both have
good solutions to this
var statement = "The the lazy dog";
var statement_new = statement.split(' ').map(function(word, index) {
return word + index;
}).join(' ');
// OR
var i = 1,
sta = "The lazy dog";
sta.replace(/\w+/g, function(word) {
return word + i++;
});
//another method
'the lazy dog'.split(' ').reduce(function (p, c, i){ return (!+p ? p
+ ' ' : '') + c + (i + 1) }, 1)
javascript interview questions
what
is literal notation in javascript
An
object literal is a comma separated list of name value pairs wrapped
in curly braces. In JavaScript an object literal is defined as
follows:
var
myObject = {
sProp:
'some string value',
numProp:
2,
bProp:
false
};
Object
literals are used as a means of encapsulating data, enclosing it in a
tidy package to minimize the use of global variables which can cause
problems when combining code.
Applying
style to form elements?
input[type=text]
{
background-color:
#BFBDBD;
border:solid
1px #BFBDBD;
color:
#979797;
height:
28px;
padding-left:10px;
width:
191px;
box-shadow:
2px 2px 0 #828181 inset;
}
input[type=button]
{
background-color:
#1E1E1E;
color:
#979797;
height:
24px;
width:
103px;
color:
#bbbbbb;
text-transform:uppercase;
box-shadow:-1px
2px #6E6B6A inset;
}
input[type=button],
input[type=text]
{
border:
0;
border-radius:5px;
font-family:
Sansation,Arial;
}
CSS
Apply border to all input elements except checkbox
input:not([type=checkbox])
{
border:
1px solid #039;
}
Whar
are css3 selectors?
Overview
of CSS 3 selector syntax Selector type Pattern Description
Substring
matching attribute selector
E[att^=”val”]
Matches any E element whose att attribute value begins with “val”.
Substring
matching attribute selector
E[att$=”val”]
Matches any E element whose att attribute value ends with “val”.
Substring
matching attribute selector
E[att*=”val”]
Matches any E element whose att attribute value contains the
substring “val”.
Structural
pseudo-class
E:root
Matches the document’s root element. In HTML, the root element is
always the HTML element.
Structural
pseudo-class
E:nth-child(n)
Matches any E element that is the n-th child of its parent.
Structural
pseudo-class
E:nth-last-child(n)
Matches any E element that is the n-th child of its parent, counting
from the last child.
Structural
pseudo-class
E:nth-of-type(n)
Matches any E element that is the n-th sibling of its type.
Structural
pseudo-class
E:nth-last-of-type(n)
Matches
any E element that is the n-th sibling of its type, counting from the
last sibling.
Structural
pseudo-class
E:last-child
Matches any E element that is the last child of its parent.
Structural
pseudo-class
E:first-of-type
Matches any E element that is the first sibling of its type.
Structural
pseudo-class
E:last-of-type
Matches any E element that is the last sibling of its type.
Structural
pseudo-class
E:only-child
Matches any E element that is the only child of its parent.
Structural
pseudo-class
E:only-of-type
Matches any E element that is the only sibling of its type.
Structural
pseudo-class
E:empty
Matches any E element that has no children (including text nodes).
Target
pseudo-class
E:target
Matches an E element that is the target of the referring URL.
UI
element states pseudo-class
E:enabled
Matches any user interface element (form control) E that is enabled.
UI
element states pseudo-class
E:disabled
Matches any user interface element (form control) E that is
disabled.
UI
element states pseudo-class
E:checked
Matches any user interface element (form control) E that is checked.
UI
element fragments pseudo-element
E::selection
Matches the portion of an element E that is currently selected or
highlighted by the user.
Negation
pseudo-class
E:not(s)
Matches any E element that does not match the simple selector s.
General
sibling combinator
E
~ F Matches any F element that is preceded by an E element.
<div
id="nav-primary"></div>
<div
id="content-primary"></div>
<div
id="content-secondary"></div>
<div
id="tertiary-content"></div>
<div
id="nav-secondary"></div>
By
using the substring matching attribute selectors you can target
combinations of these structural parts of the document.
The
following rule will set the background colour of all div elements
whose id begins with “nav”:
div[id^="nav"]
{ background:#ff0; }
In
this case the selector will match div#nav-primary and
div#nav-secondary.
To
target the div elements whose id ends with “primary”, you could
use the following rule:
div[id$="primary"]
{ background:#ff0; }
This
time the selector will match div#nav-primary
How
to add css to buttons?
input[type="button"],
input[type="submit"] {
color:#050;
font:
bold 84% 'trebuchet ms',helvetica,sans-serif;
background-color:#fed;
border:1px
solid;
border-color:
#696 #363 #363 #696;
}
button
{
color:#050;
font:
old 84% 'trebuchet ms',helvetica,sans-serif;
background-color:#fed;
border:1px
solid;
border-color:
#696 #363 #363 #696;
}
To
grab all three kinds of buttons:
button,
input[type="button"], input[type="submit"] {
color:#050;
font:
bold 84% 'trebuchet ms',helvetica,sans-serif;
background-color:#fed;
border:1px
solid; ha
border-color:
#696 #363 #363 #696;
}
What
is siblings means ?
siblings
means simply brothers and sisters realation ship, for example we are
having following div's
<div
id="main">
<img
src=""/>
<div
id="one"></div>
<div
id="two"></div>
<div
id="three"></div>
<a
href=""></a>
</div>
so
in the above what are the siblings of div id="two " is?
the
above and below all elements id="one", id="three"
img and anchor tag all are siblings of that div id="two".
Subscribe to:
Posts (Atom)