Built-in functions

JavaScript provides a number of convenient built-in constants, variables and functions.


Built-in constants

Infinity

This is the value of any division by zero, that is,

    var i = 1/0;

In JavaScript, division by zero does not raise an exception; instead it assigns the Infinity value as the result of the expression. Use isFinite() to test whether a value is finite or not.

NaN

Some functions that are supposed to return a numeric result may return NaN instead. Use isNaN() to check for this.

undefined

This is the value of a variable that does not have a defined value, that is, has not been assigned to.

    var i; 
    // ... 
    if ( i == undefined ) { 
        i = 77; 
    }

In this example, if execution reaches the if statement and i has not been assigned a value, it will be assigned the value 77.

Built-in variables

arguments : Array

This is an array of the arguments that were passed to the function. It only exists within the context of a function.

 function sum() 
    { 
        total = 0; 
        for ( i = 0; i < arguments.length; i++ ) { 
            total += arguments[ i ]; 
        } 
        return total; 
    }

Built-in functions

eval( string : String )

This function parses and executes the contents of the string, taking the text to be valid JavaScript.

 var x = 57; 
    var y = eval( "40 + x" ); // y == 97
isFinite( expression ) : Boolean

Returns true if the expression's value is a number that is within range; otherwise returns false.

isNaN( expression ) : Boolean

Returns true if the expression's value is not a number; otherwise returns false.

        var x = parseFloat( "3.142" ); 
        var y = parseFloat( "haystack" ); 
        var xx = isNaN( x ); // xx == false 
        var yy = isNaN( y ); // yy == true
parseFloat( string : String ) : Number

Parses the string and returns the floating point number that the string represents or NaN if the parse fails. Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.

parseInt( string : String, optBase : Number ) : Number

Parses the string and returns the integer that the string represents in the given base optBase or NaN if the parse fails. If the base is not specified, the base is determined as follows:


  • base 16 (hexadecimal) if the first non-whitespace characters are "0x" or "0X";

  • base 8 (octal) if the first non-whitespace character is "0";

  • base 10 otherwise.

Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.

    var i = parseInt( "24" );       // i == 24 
    var h = parseInt( "0xFF" );     // h == 255 
    var x = parseInt( " 459xyz " ); // x == 459