Category: Miscellaneous

  • JSON

    What is JSON?

    JSON (JavaScript Object Notation) is a text-based data format used to represent objects and data structures. It is language-independent, meaning that it can be used with any programming language. JSON is often used to exchange data between a server and a web application, or between two different web applications.

    JSON Features

    JSON is a language independent data storage format.

    • Language-independent
    • Can be used to represent objects and data structures.
    • Can be used to exchange data between different programming languages.
    • Can be nested within other objects.
    • Can contain any type of data.

    JSON Syntax

    JSON data is represented as key value pairs. Each key value pair is separated by a comma. JSON data is written inside curly braces.

    Following is a simple syntax of JSON &minusl;

    {"key1": value1,"key2": value2,...}

    The key names (key1, key2, ) is always written in double quotes. The JSON data values (value1, value2, ) can contain the following data types −

    • String − A sequence of characters enclosed in double quotes.
    • Number − An integer or a floating-point number.
    • Boolean − Either true or false.
    • Array − An ordered list of values.
    • Object − An unordered collection of key-value pairs.
    • null − Represents the absence of a value.

    JSON Data

    JSON data is written as key value pairs same as a property is written in JavaScript object. Each key value pair consist of key name written in double quotes, followed by a colon, followed by a value.

    "name":"John Doe"

    There is a difference between JSON data and JavaScript object property. The key name in JSON data is always written in double quotes but object property name does not require this.

    JSON Objects

    We can create JSON object by writing the JSON data inside the curly braces. The JSON object can contain multiple key value pairs separated by comma.

    {"name":"John Doe","age":30,"isStudent":false}

    In JavaScript, we can parse the JSON object into a variable −

    let person ={"name":"John Doe","age":30,"isStudent":false}

    In the above example, the JSNO object contains three JSON data.

    JSON Arrays

    JSON arrays are written in brackets. We write JSON data inside the brackets to create a JSON array. An array can contain objects.

    [{"name":"John Doe","age":30,"occupation":"Software Engineer"},{"name":"Jane Doe","age":25,"occupation":"Doctor"}]

    In the above example, an array contains two JSON objects. The array is JSON array. Its a valid type of JSON.

    Accessing JSON Data

    We can access JSON data using the dot or bracket notation.

    Example

    In the example below, we created a JSON object with three key names nameage, and occupation, and parse it into a variable name person. Then we accessed the name using dot notation and age using the bracket notation.

    <html><body><div> Accessing JSON data </div><div id="demo"></div><script>const person ={"name":"John Doe","age":30,"occupation":"Software Engineer"}
    
      document.getElementById("demo").innerHTML ="Name: "+person.name +"&lt;br&gt;"+"Age: "+person.age+"&lt;br&gt;"+"Occupation: "+person.occupation;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Accessing JSON data
    Name: John Doe
    Age: 30
    Occupation: Software Engineer
    

    As we can see in the output, it retrieved the key names "John Doe" and "30".

    JSON Methods

    The following table shows the JSON method and their description −

    Sr.No.Name & Description
    1JSON.parse()It parses a JSON string and creates a JavaScript object.
    2JSON.stringify()It converts a JavaScript object to JSON string.

    JSON vs. JavaScript Object

    The JSON objects are same as the JavaScript object. Both can be converted to each other. But they have some differences −

    JSON is language independent can be used to exchange data between different programming languages but JavaScript object can be used in JavaScript only.

    JSON cant contain functions whereas JavaScript object can contain function as property values

    The key names in JSON data is always written in double quotes but not in JavaScript objects.

    Converting JSON string to JavaScript Objects

    We can convert JSON to a JavaScript object using built-in function JSON.parse(). To do so first we create a JavaScript string containing the JSON object.

    let jsonString ='{"name": "John Doe", "age": 30, "isStudent": false}';

    Then, we use JSON.parse() function to convert string into a JavaScript object −

    const jsonObject =JSON.parse(jsonString);

    Example

    In the example below, we define a string containing a JSON object. Then we use JSON.parse() function to parse the JSON string to a JavaScript object. Finally we displayed first JSON data value.

    <html><body><div> Converting JSON string to JavaScript object</div><div id="demo"></div><script>let jsonString ='{"name": "John Doe", "age": 30, "isStudent": false}';const jsonObject =JSON.parse(jsonString);
    
      document.getElementById("demo").innerHTML = jsonObject.name;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Converting JSON string to JavaScript object
    John Doe
    

    As we can see in the output, the above program converted the JavaScript object to a JSON object.

    Converting JavaScript Object to JSON

    We can use the JavaScript built-in function JSON.stringify() to convert a JavaScript object to a JSON string.

    <html><body><div> Converting JavaScript object to JSON string </div><div id="demo"></div><script>const person ={
    
         name:"John Doe",
         age:30,
         isStudent:false};const jsonString =JSON.stringify(person);
     document.getElementById("demo").innerHTML = jsonString;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Converting JavaScript object to JSON string
    {"name":"John Doe","age":30,"isStudent":false}
  • Browsers Compatibility

    It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in.

    To get information about the browser your webpage is currently running in, use the built-in navigator object.

    Navigator Properties

    There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each.

    Sr.No.Property & Description
    1appCodeNameThis property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer.
    2appVersionThis property is a string that contains the version of the browser as well as other useful information such as its language and compatibility.
    3languageThis property contains the two-letter abbreviation for the language that is used by the browser. Netscape only.
    4mimTypes[]This property is an array that contains all MIME types supported by the client. Netscape only.
    5platform[]This property is a string that contains the platform for which the browser was compiled.”Win32″ for 32-bit Windows operating systems
    6plugins[]This property is an array containing all the plug-ins that have been installed on the client. Netscape only.
    7userAgent[]This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client.

    Navigator Methods

    There are several Navigator-specific methods. Here is a list of their names and descriptions.

    Sr.No.Description
    1javaEnabled()This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false.
    2plugings.refreshThis method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only.
    3preference(name,value)This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only.
    4taintEnabled()This method returns true if data tainting is enabled; false otherwise.

    Browser Detection

    There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user.

    <html><head><title>Browser Detection Example</title></head><body><script type ="text/javascript">var userAgent   = navigator.userAgent;var opera       =(userAgent.indexOf('Opera')!=-1);var ie          =(userAgent.indexOf('MSIE')!=-1);var gecko       =(userAgent.indexOf('Gecko')!=-1);var netscape    =(userAgent.indexOf('Mozilla')!=-1);var version     = navigator.appVersion;if(opera){
    
            document.write("Opera based browser");// Keep your opera specific URL here.}elseif(gecko){
            document.write("Mozilla based browser");// Keep your gecko specific URL here.}elseif(ie){
            document.write("IE based browser");// Keep your IE specific URL here.}elseif(netscape){
            document.write("Netscape based browser");// Keep your Netscape specific URL here.}else{
            document.write("Unknown browser");}// You can include version to along with any above condition.
         document.write("&lt;br /&gt; Browser version info : "+ version );&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    On executing the above program, you will get the output similar to the following

    Please note that you may get some more information about the browser depending upon the type of browser you are using.

  • Image Map

    You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags.

    The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign.

    The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use.

    The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot.

    Example

    The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image.

    <html><head><title>Using JavaScript Image Map</title><script type ="text/javascript">functionshowTutorial(name){
    
            document.myform.stage.value = name
         }&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform"&gt;&lt;input type ="text" name ="stage" size ="20"/&gt;&lt;/form&gt;&lt;!-- Create  Mappings --&gt;&lt;img src ="/images/usemap.gif" alt ="HTML Map" border ="0" usemap ="#tutorials"/&gt;&lt;map name ="tutorials"&gt;&lt;area shape="poly" 
            coords ="74,0,113,29,98,72,52,72,38,27"
            href ="/perl/index.htm" alt ="Perl Tutorial"
            target ="_self" 
            onMouseOver ="showTutorial('perl')" 
            onMouseOut ="showTutorial('')"/&gt;&lt;area shape ="rect" 
            coords ="22,83,126,125"
            href ="/html/index.htm" alt ="HTML Tutorial" 
            target ="_self" 
            onMouseOver ="showTutorial('html')" 
            onMouseOut ="showTutorial('')"/&gt;&lt;area shape ="circle" 
            coords ="73,168,32"
            href ="/php/index.htm" alt ="PHP Tutorial"
            target ="_self" 
            onMouseOver ="showTutorial('php')" 
            onMouseOut ="showTutorial('')"/&gt;&lt;/map&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    You can feel the map concept by placing the mouse cursor on the image

  • Multimedia

    The JavaScript navigator object includes a child object called plugins. This object is an array, with one entry for each plug-in installed on the browser. The navigator.plugins object is supported only by Netscape, Firefox, and Mozilla only.

    Example

    Here is an example that shows how to list down all the plug-on installed in your browser −

    <html><head><title>List of Plug-Ins</title></head><body><table border ="1"><tr><th>Plug-in Name</th><th>Filename</th><th>Description</th></tr><script language ="JavaScript" type ="text/javascript">for(i =0; i<navigator.plugins.length; i++){
    
               document.write("&lt;tr&gt;&lt;td&gt;");
               document.write(navigator.plugins[i].name);
               document.write("&lt;/td&gt;&lt;td&gt;");
               document.write(navigator.plugins[i].filename);
               document.write("&lt;/td&gt;&lt;td&gt;");
               document.write(navigator.plugins[i].description);
               document.write("&lt;/td&gt;&lt;/tr&gt;");}&lt;/script&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Checking for Plug-Ins

    Each plug-in has an entry in the array. Each entry has the following properties −

    • name − is the name of the plug-in.
    • filename − is the executable file that was loaded to install the plug-in.
    • description − is a description of the plug-in, supplied by the developer.
    • mimeTypes − is an array with one entry for each MIME type supported by the plug-in.

    You can use these properties in a script to find out the installed plug-ins, and then using JavaScript, you can play appropriate multimedia file. Take a look at the following example.

    <html><head><title>Using Plug-Ins</title></head><body><script language ="JavaScript" type ="text/javascript">
    
         media = navigator.mimeTypes["video/quicktime"];if(media){
            document.write("&lt;embed src = 'quick.mov' height = 100 width = 100&gt;");}else{
            document.write("&lt;img src = 'quick.gif' height = 100 width = 100&gt;");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    NOTE − Here we are using HTML <embed> tag to embed a multimedia file.

    Controlling Multimedia

    Let us take one real example which works in almost all the browsers −

    <html><head><title>Using Embeded Object</title><script type ="text/javascript">functionplay(){if(!document.demo.IsPlaying()){
    
               document.demo.Play();}}functionstop(){if(document.demo.IsPlaying()){
               document.demo.StopPlay();}}functionrewind(){if(document.demo.IsPlaying()){
               document.demo.StopPlay();}
            document.demo.Rewind();}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;embed id ="demo" name ="demo"
         src ="http://www.amrood.com/games/kumite.swf"
         width ="318" height ="300" play ="false" loop ="false"
         pluginspage ="http://www.macromedia.com/go/getflashplayer"
         swliveconnect ="true"&gt;&lt;form name ="form" id ="form" action ="#" method ="get"&gt;&lt;input type ="button" value ="Start" onclick ="play();"/&gt;&lt;input type ="button" value ="Stop" onclick ="stop();"/&gt;&lt;input type ="button" value ="Rewind" onclick ="rewind();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Animation

    You can use JavaScript to create a complex animation having, but not limited to, the following elements −

    • Fireworks
    • Fade Effect
    • Roll-in or Roll-out
    • Page-in or Page-out
    • Object movements

    You might be interested in existing JavaScript based animation library: Script.Aculo.us.

    This tutorial provides a basic understanding of how to use JavaScript to create an animation.

    JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function.

    JavaScript provides the following two functions to be frequently used in animation programs.

    • setTimeout( function, duration) − This function calls function after duration milliseconds from now.
    • setInterval(function, duration) − This function calls function after every duration milliseconds.
    • clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions.

    JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax.

    // Set distance from left edge of the screen.
    object.style.left = distance in pixels or points; 
    
    or
    
    // Set distance from top edge of the screen.
    object.style.top = distance in pixels or points; 
    

    Manual Animation

    So let’s implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods.

    • We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj.
    • We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes.
    • We are calling initialization function at the time of window load.
    • Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side.

    Example

    Try the following example.

    <html><head><title>JavaScript Animation</title><script type ="text/javascript">var imgObj =null;functioninit(){
    
            imgObj = document.getElementById('myImage');
            imgObj.style.position='relative'; 
            imgObj.style.left ='0px';}functionmoveRight(){
            imgObj.style.left =parseInt(imgObj.style.left)+10+'px';}
            
         window.onload = init;&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form&gt;&lt;img id ="myImage" src ="/images/html.gif"/&gt;&lt;p&gt;Click button below to move the image to right&lt;/p&gt;&lt;input type ="button" value ="Click Me" onclick ="moveRight();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Automated Animation

    In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows −

    Here we have added more methods. So let's see what is new here −

    • The moveRight() function is calling setTimeout() function to set the position of imgObj.
    • We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.

    Example

    Try the following example code.

    <html><head><title>JavaScript Animation</title><script type ="text/javascript">var imgObj =null;var animate ;functioninit(){
    
            imgObj = document.getElementById('myImage');
            imgObj.style.position='relative'; 
            imgObj.style.left ='0px';}functionmoveRight(){
            imgObj.style.left =parseInt(imgObj.style.left)+10+'px';
            animate =setTimeout(moveRight,20);// call moveRight in 20msec}functionstop(){clearTimeout(animate);
            imgObj.style.left ='0px';}
         
         window.onload = init;&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form&gt;&lt;img id ="myImage" src ="/images/html.gif"/&gt;&lt;p&gt;Click the buttons below to handle animation&lt;/p&gt;&lt;input type ="button" value ="Start" onclick ="moveRight();"/&gt;&lt;input type ="button" value ="Stop" onclick ="stop();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Rollover with a Mouse Event

    Here is a simple example showing image rollover with a mouse event.

    Let's see what we are using in the following example −

    • At the time of loading this page, the if statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
    • The Image() constructor creates and preloads a new image object called image1.
    • The src property is assigned the name of the external image file called /images/html.gif.
    • Similarly, we have created image2 object and assigned /images/http.gif in this object.
    • The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
    • The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
    • When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed.
    • When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.
    <html><head><title>Rollover with a Mouse Events</title><script type ="text/javascript">if(document.images){var image1 =newImage();// Preload an image
    
            image1.src ="/images/html.gif";var image2 =newImage();// Preload second image
            image2.src ="/images/http.gif";}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Move your mouse over the image to see the result&lt;/p&gt;&lt;a href ="#" onMouseOver ="document.myImage.src = image2.src;"
         onMouseOut ="document.myImage.src = image1.src;"&gt;&lt;img name ="myImage" src ="/images/html.gif"/&gt;&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Form Validation

    Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.

    JavaScript provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions.

    • Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
    • Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.

    Example

    We will take an example to understand the process of validation. Here is a simple form in html format.

    <html><head><title>Form Validation</title><script type ="text/javascript">// Form validation code will come here.</script></head><body><form action ="/cgi-bin/test.cgi" name ="myForm" onsubmit ="return(validate());"><table cellspacing ="2" cellpadding ="2" border ="1"><tr><td align ="right">Name</td><td><input type ="text" name ="Name"/></td></tr><tr><td align ="right">EMail</td><td><input type ="text" name ="EMail"/></td></tr><tr><td align ="right">Zip Code</td><td><input type ="text" name ="Zip"/></td></tr><tr><td align ="right">Country</td><td><select name ="Country"><option value ="-1" selected>[choose yours]</option><option value ="1">USA</option><option value ="2">UK</option><option value ="3">INDIA</option></select></td></tr><tr><td align ="right"></td><td><input type ="submit" value ="Submit"/></td></tr></table></form></body></html>

    Basic Form Validation

    First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function.

    <script type ="text/javascript">// Form validation code will come here.functionvalidate(){if( document.myForm.Name.value ==""){alert("Please provide your name!");
    
         document.myForm.Name.focus();returnfalse;}if( document.myForm.EMail.value ==""){alert("Please provide your Email!");
         document.myForm.EMail.focus();returnfalse;}if( document.myForm.Zip.value ==""||isNaN( document.myForm.Zip.value )||
         document.myForm.Zip.value.length !=5){alert("Please provide a zip in the format #####.");
         document.myForm.Zip.focus();returnfalse;}if( document.myForm.Country.value =="-1"){alert("Please provide your country!");returnfalse;}return(true);}&lt;/script&gt;</pre>

    Data Format Validation

    Now we will see how we can validate our entered form data before submitting it to the web server.

    The following example shows how to validate an entered email address. An email address must contain at least a &commat; sign and a dot (.). Also, the &commat; must not be the first character of the email address, and the last dot must at least be one character after the &commat; sign.

    Example

    Try the following code for email validation.

    <script type ="text/javascript">functionvalidateEmail(){var emailID = document.myForm.EMail.value;
    
      atpos = emailID.indexOf("@");
      dotpos = emailID.lastIndexOf(".");if(atpos &lt;1||( dotpos - atpos &lt;2)){alert("Please enter correct email ID")
         document.myForm.EMail.focus();returnfalse;}return(true);}&lt;/script&gt;</pre>
  • Page Printing

    Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.

    The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.

    Example

    Try the following example.

    <html><head><script type ="text/javascript"><!--//--></script></head><body><form><input type ="button" value ="Print" onclick ="window.print()"/></form></body><html>

    Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising.

    You can make a page printer friendly in the following ways −

    • Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
    • If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!– PRINT STARTS HERE –>….. <!– PRINT ENDS HERE –> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors.

    Example

    Create a button with an onclick event that is attached with the printpage() method, & it should be triggered when we want to print the page.

    When the user clicks the button then printpage() method (in the script tag) will be called, which may contains some code that helps to print the page.

    <html><head><title>Print Page</title><script>functionprintpage(){
    
            window.print();}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;This is a sample page to print&lt;/h2&gt;&lt;button onclick="printpage()"&gt;Print Page&lt;/button&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    When the user clicks the button, the browser's print dialog box will open, allowing them to print your HTML document as displayed on their current window.

    Here are some additional things to keep in mind when using JavaScript to print a page:

    • The print() method will only print the content of the current window. If you want to print multiple pages, you will need to call the print() method for each page.
    • The print() method will not print any content that is hidden from view. For example, if you have an element with the style property set to "display: none", it will not be printed.
    • The print() method will not print any content that is loaded dynamically after the page has loaded. For example, if you use JavaScript to load an image from a server, the image will not be printed.

    If you need to print more complex content, such as a table or a form, you may need to use a different method, such as generating a PDF file or using a third-party printing library.

    How to Print a Page?

    If you dont find the above facilities on a web page, then you can use the browser's standard toolbar to get print the web page. Follow the link as follows.

    File →  Print → Click OK  button.
  • Dialog Boxes

    JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one.

    Alert Dialog Box

    An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message.

    Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button “OK” to select and proceed.

    Example

    <html><head><script type ="text/javascript">functionWarn(){alert("This is a warning message!");
    
            document.write("This is a warning message!");}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to see the result:&lt;/p&gt;&lt;form&gt;&lt;input type ="button" value ="Click Me" onclick ="Warn();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Confirmation Dialog Box

    A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.

    If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.

    Example

    <html><head><script type ="text/javascript">functiongetConfirmation(){var retVal =confirm("Do you want to continue ?");if( retVal ==true){
    
               document.write("User wants to continue!");returntrue;}else{
               document.write("User does not want to continue!");returnfalse;}}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to see the result:&lt;/p&gt;&lt;form&gt;&lt;input type ="button" value ="Click Me" onclick ="getConfirmation();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Prompt Dialog Box

    The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.

    This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.

    This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null.

    Example

    The following example shows how to use a prompt dialog box −

    <html><head><script type ="text/javascript">functiongetValue(){var retVal =prompt("Enter your name : ","your name here");
    
            document.write("You have entered : "+ retVal);}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to see the result:&lt;/p&gt;&lt;form&gt;&lt;input type ="button" value ="Click Me" onclick ="getValue();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Page Redirection

    What is Page Redirection?

    You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh.

    There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −

    • You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.
    • You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page.
    • The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.

    How Page Re-direction Works?

    The implementations of Page-Redirection are as follows.

    Example 1

    It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.

    <html><head><title>Page Redirection Example</title></head><body><p>Click the following button, you will be redirected to home page.</p><form><input type="button" value="Redirect Me" onclick="Redirect();"/></form><script type="text/javascript">functionRedirect(){
    
            window.location ="https://www.tutorialspoint.com";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example 2

    You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.

    <html><head><title>Page Redirection Example</title></head><body><p>You will be redirected to main page in10 sec.</p><script>functionredirect(){
    
           window.location ="https://www.tutorialspoint.com";}setTimeout('redirect()',10000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    You will be redirected to tutorialspoint.com main page in 10 seconds!
    

    Example 3

    The following example shows how to redirect your site visitors onto a different page based on their browsers.

    <html><head><title>Browser Redirect</title></head><body><script type ="text/javascript">var browsername = navigator.appName;if( browsername =="Netscape"){
    
         window.location ="https://www.tutorialspoint.com/javascript/index.htm";}elseif( browsername =="Microsoft Internet Explorer"){
         window.location ="https://www.tutorialspoint.com/articles/category/Javascript";}else{
         window.location ="https://www.tutorialspoint.com/";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Rest Parameter

    Rest Parameter

    The rest parameter in JavaScript allows a function to accept a variable number of arguments as an array. When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters.

    The JavaScript rest parameters allow you to collect all the remaining arguments in a single array. The rest parameter is represented with three dots (…) followed by a parameter name. This parameter name is the array that contains all the remaining arguments.

    Rest Parameter Syntax

    The rest parameter in JavaScript involves using three dots (…) followed by a parameter name in the function declaration.

    functionfunctionName(para1, para2, ...theArgs){// function body;}

    Here para1, and para2 are ordinary parameters while theArgs is a rest parameter. The rest parameter collects the rest of arguments (here, arguments other than the corresponding to the parameters para1 and para1) and assigns to an array named theArgs.

    We can write the rest parameter in function expression also same as in the function declaration.

    The rest parameter should always be the last parameter in the function definition.

    functionfuncName(...para1, para2, para2){}// SyntaxError: Invalid or unexpected token

    The function definition can have only one rest parameter.

    functionfuncName(para1, ...para2, ...para3){}//SyntaxError: Rest parameter must be last formal parameter  

    Example: Variable Length Parameter List

    The rest parameters are very useful when you want to define a function that can handle a variable number of arguments. Lets take the following example −

    <html><body><div> Rest parameter allows function to accept nay number of arguments.</div><div id ="demo"></div><script>functionsum(...nums){let totalSum =0;for(let num of nums){
    
        totalSum += num;}return totalSum;}
    document.getElementById("demo").innerHTML =sum(10,20,30,40)+"&lt;br&gt;"+sum(10,20)+"&lt;br&gt;"+sum();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Rest parameter allows function to accept nay number of arguments.
    100
    30
    0
    

    Here, the rest parameter nums allows the function to accept any number of number arguments.

    Example: Finding the Maximum Number

    JavaScript rest parameter simplifies the process of finding the max number among a set of given numbers.

    In this example, we use rest parameter to numbers to collect all arguments passed to the function. The spread operator is used to pass the individual values to the Math.max() function.

    <html><body><div> Finding the maximum number</div><div id ="demo"></div><script>functiongetMax(...args){return Math.max(...args);} 
    
      document.getElementById("demo").innerHTML =getMax(10,20,30,40)+"&lt;br&gt;"+getMax(10,20,30);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Finding the maximum number
    40
    30
    

    Here the rest parameter args allows the function getMax to accept any number of arguments.

    Spread Operator and Rest Parameters

    The spread operator (...) is closely related to rest parameters and is often used in conjunction with them. While the rest parameter collects function arguments into an array, the spread operator performs the opposite operation, spreading the elements of an array into individual arguments.

    In the above example of finding the maximum number, we used both rest parameter and spread operator.

    functiongetMax(...args){// here ...args as rest parameterreturn Math.max(...args);// here ... works as spread operator}

    Example

    In this example, the spread operator ... is used to pass the elements of the numbers array as individual arguments to the multiply function.

    <html><body><div> Spread operator in JavaScript<div><div id="demo"></div><script>functionmultiply(a, b, c){return a * b * c;}const numbers =[2,3,4];
    
      document.getElementById("demo").innerHTML =multiply(...numbers);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Spread operator in JavaScript
    24
    

    Rest Parameter vs. Arguments Object

    The introduction of rest parameters has implications for how we handle variable-length parameter lists compared to using the arguments object. Let's compare the two approaches:

    Rest Parameters

    <html><body><div> Sum using rest parameter in JavaScript:</div><div id ="demo"></div><script>functionsum(...numbers){return numbers.reduce((total, num)=> total + num,0);}
    
    document.getElementById("demo").innerHTML =sum(1,2,3,4,5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Sum using rest parameter in JavaScript:
    15
    

    Arguments Object

    <html><body><div> Sum using arguments object in JavaScript:</div><div id ="demo"></div><script>functionsum(){const argsArray = Array.from(arguments);return argsArray.reduce((total, num)=> total + num,0);}
    
    document.getElementById("demo").innerHTML =sum(1,2,3,4,5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Sum using arguments object in JavaScript:
    15
    

    While both approaches achieve the same result, the rest parameter syntax is more concise and readable. It also behaves more consistently with other modern JavaScript features.

    Destructuring with Rest Parameter

    The destructuring assignment is introduced in ES6. It allows us to access the individual values of the array without using array indexing. We can use the destructuring assignment to extract the values from the array created by rest parameter.

    Example

    In the example below, the destructuring assignment extracts the first two elements from the numbers array.

    <html><body><div> Destructuring assignment with rest parameter</div><div id ="demo"></div><script>functiongetFirstTwo(...numbers){const[first, second]= numbers;returnFirst: ${first}, Second: ${second};} 
    
    document.getElementById("demo").innerHTML =getFirstTwo(1,2,3,4,5);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Destructuring assignment with rest parameter
    First: 1, Second: 2