smallseo.info

javascript interview questions

Top javascript frequently asked interview questions

How do I return the response from an asynchronous call?

I have a function foo which makes an Ajax request. How can I return the response from foo?

I tried to return the value from the success callback as well as assigning the response to a local variable inside the function and return that one, but none of those ways actually return the response.

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result;
}

var result = foo(); // It always ends up being `undefined`.

Source: (StackOverflow)

Detecting an undefined object property

What's the best way of checking if an object property in JavaScript is undefined?


Source: (StackOverflow)

$(this) selector and children?

I have a layout similar to this:

<div id="..."><img src="..."></div>

and would like to use a jQuery selector to select the child img inside the div on click.

To get the div, I've got this selector:

$(this)

How can I get the child img using a selector?


Source: (StackOverflow)

Remove a particular element from an array in JavaScript?

I have an array of integers, which I'm using the .push() method to add to.

Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);

I have to use core JavaScript - no frameworks are allowed.


Source: (StackOverflow)

Check checkbox checked property

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if($('#isAgeSelected').attr('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

How do I successfully query the checked property?


Source: (StackOverflow)

How do I remove a property from a JavaScript object?

Say I create an object as follows:

var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to remove the property regex to end up with the following new myObject?

var myObject = {"ircEvent": "PRIVMSG", "method": "newURI"};

Source: (StackOverflow)

Include a JavaScript file in another JavaScript file?

Is there something in JavaScript similar to @import in CSS that allows you to include a JavaScript file inside another JavaScript file?


Source: (StackOverflow)

Checking a checkbox with jQuery?

I'd like to do something like this to tick a checkbox using jQuery:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

Does such a thing exist?


Source: (StackOverflow)

var functionName = function() {} vs function functionName() {}

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.

The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?


Source: (StackOverflow)

Why does Google prepend while(1); to their JSON responses?

Why does Google prepend while(1); to their (private) JSON responses?

For example, here's a response while turning a calendar on and off in Google Calendar:

while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false'],
  ['remindOnRespondedEventsOnly','true'],
  ['hideInvitations_remindOnRespondedEventsOnly','false_true'],
  ['Calendar ID stripped for privacy','false'],['smsVerifiedFlag','true']]]]

I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.

I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.

What's going on here?


Source: (StackOverflow)

Validate decimal numbers in JavaScript - IsNumeric()

What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

  1. Clarity. Solution should be clean and simple.
  2. Cross-platform.

Test cases:

 01. IsNumeric('-1') => true
 02. IsNumeric('-1.5') => true
 03. IsNumeric('0') => true
 04. IsNumeric('0.42') => true
 05. IsNumeric('.42') => true
 06. IsNumeric('99,999') => false
 07. IsNumeric('0x89f') => false
 08. IsNumeric('#abcdef')=> false
 09. IsNumeric('1.2.3') => false
 10. IsNumeric('') => false
 11. IsNumeric('blah') => false

Source: (StackOverflow)

How can I get query string values in JavaScript?

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?


Source: (StackOverflow)

Href attribute for JavaScript links: "#" or "javascript:void(0)"?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}
<a rel='nofollow' href="#" onclick="myJsFunc();">Run JavaScript Code</a>

or

function myJsFunc() {
    alert("myJsFunc");
}
 <a rel='nofollow' href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>


Source: (StackOverflow)

Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?

I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

Is there a performance benefit to replacing == with ===?

Any performance improvement would be welcomed as many comparison operators exist.

If no type conversion takes place, would there be a performance gain over ==?


Source: (StackOverflow)

How can I check if one string contains another substring?

How can I check if one string contains another substring in JavaScript? Usually, I would expect a String.contains() method, but there doesn't seem to be one. What is a reasonable way to check for this?


Source: (StackOverflow)