Categories
JavaScript Tutorials

Pre-defined functions

There are a number of functions that are built into the JavaScript engine and available for us to use. Let’s take a look at some of them. While doing so, you’ll have a chance to experiment with functions, their parameters and return values , and become comfortable in working with them. 

For example:

alert()

The alert() function helps us to display a pop-up dialog box with an optional message text. It is important to note that it waits for the user to close or dismiss the pop-up dialog box.

alert("Welcome to Edupoly");
//alerts "Welcome to Edupoly"

var x = 20;
var y = 30;
alert(x + y);
//alerts 50

console.log()

The console.log() function helps us to print some message or value in the console.

console.log("Edupoly");
//prints "Edupoly" in the console

console.log(1+2);
//prints 3 in the console

var x = 12;
var y = 10;
console.log(x + y);
//prints 22 in the console

console.log("Edu" + "poly");
//prints "Edupoly" in the console

console.log("Good" + " " + "Day");
//prints "Good Day" in the console

confirm()

The confirm() function displays a confirm dialog box and waits for the user to respond to it. Users can either confirm or cancel/dismiss the dialog box. It returns true or false according to the user response.

confirm("Are you sure you want to logout?");
//opens a confirm dialog box
//returns true if user clicks on confirm
//returns false if user clicks on cancel

prompt()

The prompt() function opens a dialog box with a message(if we want) and allows the user to input some value. It waits for the user to provide some value and returns the value as a string. It also has a ‘cancel’ option to dismiss the dialog box.

prompt("Enter a number");

parseInt()

parseInt() takes any type of input (most often a string) and tries to make an integer out of it. If it fails, it returns NaN.

parseInt('123')
//123
parseInt('abc123')
//NaN
parseInt('1abc23')
//1
parseInt('123abc')
//123

parseFloat()

parseFloat() is the same as parseInt() but it also looks for decimals when trying to figure out a number from your input.

parseFloat('123')
//123
parseFloat('1.23')
//1.23
parseFloat('1.23abc.00')
//1.23
parseFloat('a.bc1.23')
//NaN

Assignments

1. Write a program to alert “Hello! Good morning”.

2. Write a program to print your full name in the console.

3. Write a program to print the product of 10 and 20 in the console.

4. Write a program to open a confirm box that asks “Do you want to delete this item?”.

5. Write a program to open a confirm box that asks “Do you want to delete this item?”. If the user confirms it, it should alert “Item deleted”.

6. Use a prompt box that asks the user to enter a number and print the number in the console.

7. Use a prompt box to take a decimal number input from the user and print only the integer part of the number using parseInt().

Quiz

Click on this link for MCQs on JavaScript pre-defined functions: Pre-defined functions MCQs