JavaScript · Programming

Some fun JavaScript Questions

Ok, time to check your JS knowledge.

Questions

  1. What is negative infinity?
  2. What is the result of the expression
    var xd = ''; xd = '1'+2+3;
  3. What is the result of the expression
    var xd = ''; xd = 1+2+'3';
  4. What is the result of the expression
    var xd = ''; xd = 1+'2'+3;
  5. How do you create a new object in JavaScript?
  6. How do you assign object properties?
  7. What’s a way to append a value to an array?
  8. What are JavaScript types?
  9. How do you convert numbers between different bases in JavaScript?
  10. How will you implement getElementById using your own function?

Answers

  1. It’s a number in JavaScript, derived by dividing negative number by zero.

    c = -1/0;
    alert(c); // alerts -Infinity 

    d = 1/0;
    alert(d); // alert Infinity

  2. 123. Since the first argument is string the rest of the arguments get converted to String.
  3. 33. Since the first 2 arguments are numbers they are added. Last one is String so it is concatenated.
  4. 123.

  5. var obj = new Object(); or
    var obj = {};

  6. obj["age"] = 17 or
    obj.age = 17

  7. arr[arr.length] = value;
    or
    arr.push('a');]
  8. Number, String, Boolean, Function, Object, Null, Undefined, Date, Math, Array
  9. 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);
  10. getElementById function, see below.
function getElementById(oElm, strTagName, strIdName) 
{
    if ( oElm == null ) oElm = document;

    if ( strTagName == null ) strTagName = '*';
  
    var arrElements = oElm.getElementsByTagName(strTagName);
    var oElement;

    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];     
    
        if(oElement.id == strIdName){
            return oElement;
        }  
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s