Predefined

Predefined functions are built into the JavaScript language and made readily available for us to use. Let's use a few to get the idea.

File Location

We will be working in the following file:

        └── 1-Fundamentals
            └── 4-Functions
                09-predefined.js <----You will be working in this file.

Predefined Examples

Here are a few examples of predefined functions used commonly in JavaScript:

Name

Purpose

isNaN()

Determines if a value is 'Not a Number'

parseInt()

parses a string argument and returns an int

isNaN()

isNan() is a pre-defined function that checks to see if something is not a number. Let's practice using it by copying the following code. After you copy the code, try to guess what will happen with 1 & 2 in the results.

  function bankDepositAmount(money) {
    if (isNaN(money)) {
      return 'Not a Number!';
    }
    return money + " was deposited into your account.";
  }

  //Calling the function
  var depositOne = bankDepositAmount(1200);
  var depositTwo = bankDepositAmount("one hundred");

  //Printing the result
  console.log(depositOne); //1
  console.log(depositTwo); //2

parseInt()

Another commonly used predefined function is parseInt(). This method is used when you want to convert a string number "6" to an integer 6. Consider the function below:

function convertStringToNumber(x) {
    var parsedNumber = parseInt(x);
    return parsedNumber;
}

var numberOne = convertStringToNumber("1");
var numberTwo = convertStringToNumber("2");

console.log(numberOne);
console.log(numberTwo);

Blending the two

If we're taking input from a user in the form of a string and we want them to enter numbers, what about checking to be sure they enter a number. For instance, what if a user enters XYZ, instead of an actual number. We would need to check to be sure that they have entered a number. Let's take that same function and check to make sure that we have parsed a number. Consider the additional logic below. See if you can answer the question of what happens when we print numberThree.

function convertStringToNumber(x) {
    var parsedNumber = parseInt(x);
    if (isNaN(parsedNumber)) { 
    return "Sorry, that is not a number" 
    }
    return parsedNumber;
}

var numberOne = convertStringToNumber("1");
var numberTwo = convertStringToNumber("2");
var numberThree = convertStringToNumber("XYZ"); 

console.log(numberOne);
console.log(numberTwo);
console.log(numberThree); //What will happen here?

Additonal Practice

There are too many predefined functions in JavaScript for you to go and study. Here's a reference guide. You don't need to memorize them. Know that they are there.

What you might want to do is go pick 3-5 of them and write some code that uses some of these functions.

Last updated