Blog

  • JavaScript – Set Date Methods

    Set Date Methods

    JavaScript Set Date Methods are functionalities linked to the Date object in JavaScript, designed to streamline the adjustment and modification of specific elements within a date and time structure. These methods empower developers to efficiently update individual components, such as year, month, day, hour, and minute, in a Date object, offering a convenient approach for handling and manipulating date-related values in JavaScript applications.

    Here, we will discuss about these JavaScript set date methods in detail. The table below comprises of the most commonly used set date methods and their corresponding description.

    MethodDescription
    setFullYear(year)Sets the year of the date object. Accepts a four-digit year. Adjusts the date; if it’s a leap year and the date is February 29, it remains; otherwise, it changes to the closest valid date in the new year.
    setMonth(month)Sets the month of the date object (0-11). Accepts a numeric value (0-11). Adjusts the date, changing the year if the month value is outside the valid range.
    setDate(day)Sets the day of the month for the date object (1-31). Accepts a numeric value (1-31). Adjusts the date, changing the month and year if the day value is outside the valid range for the current month.
    setHours(hours)The function sets the hour of a date object within the range of 0-23, accepting only numeric values. It adjusts the date as necessary to maintain validity, potentially altering the month and year in addition to time.
    setMinutes(minutes)Accepts numbers ranging from 0 to 59 and sets the minutes of that particular date object. It adjusts the date in such a way that hour, date, month and year are a valid date and time.
    setSeconds(seconds)Sets the seconds of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date, potentially changing the minute, hour, date, month, and year to ensure a valid date and time.
    setMilliseconds(ms)Sets the milliseconds of the date object (0-999). Accepts a numeric value (0-999). Adjusts the date, potentially changing the second, minute, hour, date, month, and year to ensure a valid date and time.
    setTime(milliseconds)The function sets the date and time in milliseconds since January 1, 1970; it accepts a numeric value. Then, the entire date object is transformed to reflect the provided milliseconds value.
    setUTCFullYear(year)Takes input as a 4 digit year and adjusts the Coordinated Universal Time or UTC, considering the leap years.
    setUTCMonth(month)Sets the UTC month of the date object (0-11). Accepts a numeric value (0-11). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the year if the month value is outside the valid range.
    setUTCDate(day)Accepts numeric value between 1 to 31 and sets the UTC day of the month for that particular date object. It basically adjusts the date in Coordinated Universal Time (UTC), changing the month and year if the day value is in the valid range for the current month.
    setUTCHours(hours)Sets the UTC hour of the date object (0-23). Accepts a numeric value (0-23). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the date, month, and year to ensure a valid date and time.
    setUTCMinutes(minutes)Sets the UTC minutes of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the hour, date, month, and year to ensure a valid date and time.
    setUTCSeconds(seconds)Sets the UTC seconds of the date object (0-59). Accepts a numeric value (0-59). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the minute, hour, date, month, and year to ensure a valid date and time.
    setUTCMilliseconds(ms)Sets the UTC milliseconds of the date object (0-999). Accepts a numeric value (0-999). Adjusts the date in Coordinated Universal Time (UTC), potentially changing the second, minute, hour, date, month, and year to ensure a valid date and time.

    Examples

    Example 1: Simple implementation of set methods

    We employ set methods to modify a variety of date components, thereby demonstrating the versatility inherent in each method. These adjustments to the current date accommodate diverse scenarios; they include not only adding years, months and days but also hours – even minutes and milliseconds.

    <!DOCTYPE html><html><body><div id="result"><p id="setFullYear"></p><p id="setMonth"></p><p id="setDate"></p><p id="setHours"></p><p id="setMinutes"></p><p id="setSeconds"></p><p id="setMilliseconds"></p><p id="setTime"></p><p id="setUTCFullYear"></p><p id="setUTCMonth"></p><p id="setUTCDate"></p><p id="setUTCHours"></p><p id="setUTCMinutes"></p><p id="setUTCSeconds"></p><p id="setUTCMilliseconds"></p></div><script>const currentDate =newDate();
          currentDate.setFullYear(currentDate.getFullYear()+1);
          document.getElementById("setFullYear").innerText =`setFullYear: ${currentDate.toDateString()}`;
         
          currentDate.setMonth(currentDate.getMonth()+2);
          document.getElementById("setMonth").innerText =`setMonth: ${currentDate.toDateString()}`;
          
    		currentDate.setDate(currentDate.getDate()+5);
          document.getElementById("setDate").innerText =`setDate: ${currentDate.toDateString()}`;
     
          currentDate.setHours(currentDate.getHours()+3);
          document.getElementById("setHours").innerText =`setHours: ${currentDate.toDateString()}`;
      
          currentDate.setMinutes(currentDate.getMinutes()+15);
          document.getElementById("setMinutes").innerText =`setMinutes: ${currentDate.toDateString()}`;
          
    		currentDate.setSeconds(currentDate.getSeconds()+30);
          document.getElementById("setSeconds").innerText =`setSeconds: ${currentDate.toDateString()}`;
      
          currentDate.setMilliseconds(currentDate.getMilliseconds()+500);
          document.getElementById("setMilliseconds").innerText =`setMilliseconds: ${currentDate.toDateString()}`;
          
    		currentDate.setTime(currentDate.getTime()+86400000);// 86400000 milliseconds in a day
          document.getElementById("setTime").innerText =`setTime: ${currentDate.toDateString()}`;
      
          currentDate.setUTCFullYear(currentDate.getUTCFullYear()+1);
          document.getElementById("setUTCFullYear").innerText =`setUTCFullYear: ${currentDate.toDateString()}`;
      
          currentDate.setUTCMonth(currentDate.getUTCMonth()+2);
          document.getElementById("setUTCMonth").innerText =`setUTCMonth: ${currentDate.toDateString()}`;
          
    		currentDate.setUTCDate(currentDate.getUTCDate()+5);
          document.getElementById("setUTCDate").innerText =`setUTCDate: ${currentDate.toDateString()}`;
           
    		currentDate.setUTCHours(currentDate.getUTCHours()+3);
          document.getElementById("setUTCHours").innerText =`setUTCHours: ${currentDate.toDateString()}`;
      
          currentDate.setUTCMinutes(currentDate.getUTCMinutes()+15);
          document.getElementById("setUTCMinutes").innerText =`setUTCMinutes: ${currentDate.toDateString()}`;
      
          currentDate.setUTCSeconds(currentDate.getUTCSeconds()+30);
          document.getElementById("setUTCSeconds").innerText =`setUTCSeconds: ${currentDate.toDateString()}`;
      
          currentDate.setUTCMilliseconds(currentDate.getUTCMilliseconds()+500);
          document.getElementById("setUTCMilliseconds").innerText =`setUTCMilliseconds: ${currentDate.toDateString()}`;</script></body></html>

    Example 2: Combining Set Date Methods for a Complex Update

    A sophisticated date manipulation combines multiple set methods: for instance, it adjusts the date by adding two years; subtracts one month then adds fifteen days. Finally with precision and accuracy, the time is set at 18:30:45.

    <!DOCTYPE html><html><body><div id="result"><h2>Complex Date Manipulation</h2><p id="complexManipulation"></p></div><script>const currentDate =newDate();// Combining multiple set methods for a complex update
         currentDate.setFullYear(currentDate.getFullYear()+2);
         currentDate.setMonth(currentDate.getMonth()-1);
         currentDate.setDate(currentDate.getDate()+15);
         currentDate.setHours(18);
         currentDate.setMinutes(30);
         currentDate.setSeconds(45);
    
         document.getElementById("complexManipulation").innerText =`Complex Manipulation Result: ${currentDate.toDateString()} ${currentDate.toTimeString()}`;</script></body></html>
  • JavaScript – Get Date Methods

    Get Date Methods

    JavaScript utilizes the Date object for date and time manipulation. This object offers an array of methods that facilitate retrieval and modification of date-specific information. Here, we will discuss about the get date methods within JavaScript which fetch different components of the date/time.

    Below is a table of the most commonly used get date methods and their corresponding description.

    MethodDescription
    getFullYear()This method fetches and presents the comprehensive calendar year by retrieving the current year in local time zone; it returns the full four-digit representation of a local date object.
    getMonth()Returns the month (0-11) of the local date object. This method retrieves the current month, with values ranging from 0 (January) to 11 (December). It’s useful for displaying and manipulating month-related information.
    getDate()The method: ‘returns the day component of the current date’, a value ranging from 1 to 31. This functionality proves particularly useful when one needs this information extracted from a local date object.
    getHours()The function ‘getHours()’ extracts and returns the local date object’s hour component (0-23). This allows you to retrieve the current hour in your local time zone for a variety of time-related applications.
    getMinutes()Returns the minutes (0-59) of the local date object. Retrieves the current minute component, ranging from 0 to 59. Useful for displaying and handling time-related data at the minute level.
    getSeconds()This returns the seconds ranging from 0 to 59 of the local date object. It provides precision down the seconds for a variety of time-based calculations/displays.
    getMilliseconds()Returns the milliseconds (0-999) of the local date object. Retrieves the current millisecond component, allowing for high precision in time-related applications and calculations.
    getDay()Returns the index of day of the week starting from 0 which stands for Sunday, all the way up to 6 for Saturday.
    getUTCFullYear()Returns the full 4-digit year of the date object in Coordinated Universal Time (UTC). This method retrieves the current year in UTC, providing a standardized representation of the calendar year irrespective of the local time zone.
    getUTCMonth()Returns the index of the month ranging from 0(Jan) to 11(Dec) but of the date object in Coordinated Universal Time (UTC).
    getUTCDate()Returns the day of the month (1-31) of the date object in Coordinated Universal Time (UTC). Useful for obtaining the day component of the current date in a UTC context.
    getUTCHours()Returns the hour (0-23) of the date object in Coordinated Universal Time (UTC). Retrieves the current hour in UTC, allowing for standardized access to the hour component across different time zones.
    getUTCMinutes()Returns the minutes (0-59) of the date object in Coordinated Universal Time (UTC). Retrieves the current minute component in UTC, providing standardized minute information for various international time-based applications.
    getUTCSeconds()The function fetches the seconds (ranging from 0 to 59) of a date object in Coordinated Universal Time (UTC). It also acquires the current second component in UTC, thereby enabling standardized second information across various time zones.
    getUTCMilliseconds()The function returns the milliseconds (0-999) of the date object in Coordinated Universal Time (UTC); it retrieves and offers high precision for standardized time-related calculations and applications: specifically, it provides the current millisecond component in UTC.

    Examples

    Example 1: Simple demonstration of get date methods

    The following example demonstrates the fundamental application of prevalent JavaScript date methods: It instantiates a novel Date object to represent the present date and time; subsequently, it exhibits an array of diverse components – year, month, day; hours, minutes, seconds, milliseconds; along with their corresponding UTC counterparts. The displayed elements encompass not only standard temporal divisions but also supplementary information about weekdays: thus providing comprehensive insight into current temporal dynamics.

    <!DOCTYPE html><html><head><title> Exxample to demonstrate get date methods in JavaScript</title></head><body><script>// Create a new Date objectconst currentDate =newDate();functiondisplayResult(methodName, result){const resultDiv = document.createElement('div');
             resultDiv.innerHTML =`${methodName}: ${result}`;
             document.body.appendChild(resultDiv);}displayResult('getFullYear()', currentDate.getFullYear());displayResult('getMonth()', currentDate.getMonth());displayResult('getDate()', currentDate.getDate());displayResult('getHours()', currentDate.getHours());displayResult('getMinutes()', currentDate.getMinutes());displayResult('getSeconds()', currentDate.getSeconds());displayResult('getMilliseconds()', currentDate.getMilliseconds());displayResult('getDay()', currentDate.getDay());displayResult('getUTCFullYear()', currentDate.getUTCFullYear());displayResult('getUTCMonth()', currentDate.getUTCMonth());displayResult('getUTCDate()', currentDate.getUTCDate());displayResult('getUTCHours()', currentDate.getUTCHours());displayResult('getUTCMinutes()', currentDate.getUTCMinutes());displayResult('getUTCSeconds()', currentDate.getUTCSeconds());displayResult('getUTCMilliseconds()', currentDate.getUTCMilliseconds());</script></body></html>

    Example 2: Comparison of two dates

    In this example, the Date constructor creates two specific dates: date1 and date2. The script subsequently compares these dates; it displays their formatted representations, along with a message indicating if date1 is later, earlier or equal to date2.

    <!DOCTYPE html><html><head><title>Comparison of two dates in JavaScript</title></head><body><script>const date1 =newDate(2024,0,18);const date2 =newDate(2024,0,26);functiondisplayComparison(){const date1Div = document.createElement('div');
             date1Div.innerHTML =`Date 1: ${date1.toDateString()}`;
             document.body.appendChild(date1Div);const date2Div = document.createElement('div');
             date2Div.innerHTML =`Date 2: ${date2.toDateString()}`;
             document.body.appendChild(date2Div);const resultDiv = document.createElement('div');if(date1 > date2){
                resultDiv.innerHTML ="date 1 is later than date 2";}elseif(date1 < date2){
                resultDiv.innerHTML ="date 1 is earlier than date 2";}else{
                resultDiv.innerHTML ="Both dates are equal";}
             document.body.appendChild(resultDiv);}displayComparison();</script></body></html>
  • JavaScript – Date Formats

    Date Formats

    JavaScript offers us a variety of date formats ranging from elementary locale-specific formatting all the way up to sophisticated customization options. Understanding the different date formats is a fundamental and essential aspect of web development, irrespective of whether youre building a dynamic web application, managing time sensitive data or simply displaying dates in a user-friendly manner.

    Here, we are going to cover different date formats of JavaScript and implement them with a few examples to understand them better. Below is a table explaining all the different date formats used in JavaScript.

    FormatExampleDescription
    ISO Format (UTC)2024-01-29T12:34:56.789ZStandardized format with the year, month, day, and time components. The ‘Z’ indicates the time is in UTC (Coordinated Universal Time).
    Locale Date and Time1/29/2024, 12:34:56 PMIt is the localized date & time representation based on the users system or browsers settings and can vary in terms of symbols depending on the locale.
    Custom Date FormatJan 29, 2024, 12:34:56 PM PSTThe custom format allows developers to specify which components of the date (year, month, day, hour, minute, second) are to be included and in what format they should be occurring.
    Short Date Format01/29/24A short representation of the date with the month, day, and year. The order may vary based on the locale.
    Long Date FormatJanuary 29, 2024A long representation of the date with the full month name, day, and year.
    Short Time Format12:34 PMA short representation of the time with hours and minutes.
    Long Time Format12:34:56 PMA long representation of the time with hours, minutes, and seconds.
    UTC Date FormatTue, 29 Jan 2024 12:34:56 GMTCoordinated Universal Time (UTC) formatted date and time string. It includes the day of the week and the timezone abbreviation (GMT).
    Epoch Timestamp1643450096789The number of milliseconds since January 1, 1970, 00:00:00 UTC. Also known as Unix Timestamp. Useful for handling and comparing dates as numbers.
    Relative Time2 hours ago, 3 days agoA human-readable format that expresses the time difference in a relative manner, such as “ago” for past dates. Useful for displaying how much time has passed since a certain date.

    Examples

    Example 1: Displaying current date in different formats

    JavaScript in this example dynamically generates and displays a variety of date formats on the page: ISO format, locale date and time, custom date format; short and long date formats; short and long time formats; UTC date format, even an epoch timestamp. Furthermore, it calculates the relative time between two given dates current one being compared to a specified previous one and presents these results in human-readable form. This code exemplifies pragmatic techniques for formatting dates within an HTML context using JavaScript.

    <!DOCTYPE html><html><body><h2>All Types of Date Formats</h2><script>const currentDate =newDate();functionappendFormattedDate(type, formatFunction){const formattedDate =formatFunction(currentDate);const paragraph = document.createElement('p');
             paragraph.innerText =`${type}: ${formattedDate}`;
             document.body.appendChild(paragraph);}appendFormattedDate('ISO Format (UTC)',date=> date.toISOString());appendFormattedDate('Locale Date and Time',date=> date.toLocaleString());const options ={ 
             year:'numeric', 
             month:'short', 
             day:'numeric', 
             hour:'2-digit', 
             minute:'2-digit', 
             second:'2-digit', 
             timeZoneName:'short'};appendFormattedDate('Custom Date Format',date=> date.toLocaleString('en-US', options));appendFormattedDate('Short Date Format',date=> date.toLocaleDateString());appendFormattedDate('Long Date Format',date=> date.toLocaleDateString(undefined,{ year:'numeric', month:'long', day:'numeric'}));appendFormattedDate('Short Time Format',date=> date.toLocaleTimeString());appendFormattedDate('Long Time Format',date=> date.toLocaleTimeString(undefined,{ hour:'2-digit', minute:'2-digit', second:'2-digit'}));appendFormattedDate('UTC Date Format',date=> date.toUTCString());appendFormattedDate('Epoch Timestamp',date=> date.getTime());const previousDate =newDate('2024-01-29T00:00:00Z');const relativeTime =formatRelativeTime(previousDate, currentDate);appendFormattedDate('Relative Time',()=> relativeTime);// Function to calculate relative timefunctionformatRelativeTime(previousDate, currentDate){const elapsedMilliseconds = currentDate - previousDate;const seconds = Math.floor(elapsedMilliseconds /1000);const minutes = Math.floor(seconds /60);const hours = Math.floor(minutes /60);if(seconds <60){return`${seconds} second${seconds !== 1 ? 's' : ''} ago`;}elseif(minutes <60){return`${minutes} minute${minutes !== 1 ? 's' : ''} ago`;}elseif(hours <24){return`${hours} hour${hours !== 1 ? 's' : ''} ago`;}else{return'More than a day ago';}}</script></body></html>

    Example 2: Customized date formats

    This example gives us a deeper understanding of the customized date formats which do not have any prefix format and are up to the developer choose. We use the Intl.DateTimeFormat object to create our format of (weekday, month, day, year). With this option customized date formats we can choose not only the parts of the date to be made visible but also their order. A website might be more suitable if it displayed dates in dd/mm/yyyy in some countries but more user friendly if it displayed dates in mm-dd-yyyy in some other countries.

    <!DOCTYPE html><html><body><h2>Custom Date Format Example</h2><script>const currentDate =newDate();functioncustomDateFormat(date){const options ={ weekday:'long', month:'long', day:'numeric', year:'numeric'};returnnewIntl.DateTimeFormat('en-US', options).format(date);}// Function to append formatted date to the bodyfunctionappendFormattedDate(type, formatFunction){const formattedDate =formatFunction(currentDate);
             document.body.innerHTML +=`<p>${type}: ${formattedDate}</p>`;}// Append custom date formatappendFormattedDate('Custom Date Format', customDateFormat);</script></body></html>

    Example 3: Generating next 5 days dates

    In this example JavaScript generates future dates, specifically for the next five days based on the current date. Subsequently, it formats and displays these dates in three different ways; ISO format; locale-specific arrangement, and a custom layout are showcased on the web page. Without requiring any user input, JavaScript’s date handling capabilities receive a practical illustration through dynamically generated dates from the generateFutureDates function.

    <!DOCTYPE html><html><body><h2>Future Dates Generator</h2><div id="futureDates"></div><script>functiongenerateFutureDates(){const today =newDate();const futureDatesDiv = document.getElementById('futureDates');for(let i =1; i <=5; i++){const futureDate =newDate(today.getTime()+ i *24*60*60*1000);// Adding 1 day for each iterationconst isoFormat = futureDate.toISOString();const localeFormat = futureDate.toLocaleString();const customFormatOptions ={ year:'numeric', month:'long', day:'numeric', hour:'2-digit', minute:'2-digit', second:'2-digit', timeZoneName:'short'};const customFormat = futureDate.toLocaleString('en-US', customFormatOptions);
    
                futureDatesDiv.innerHTML +=`
                <p><strong>Day ${i}:</strong></p>
                <p>ISO Format (UTC): ${isoFormat}</p>
                <p>Locale Date and Time: ${localeFormat}</p>
                <p>Custom Format: ${customFormat}</p>
                <hr>
                `;}}generateFutureDates();</script></body></html>
  • JavaScript – Multiline Strings

    multiline string is a JavaScript string that spans multiple lines. Using multiline strings in programs make it easier to read and maintain. In JavaScript, the easiest way to create multiline strings is to use template literals (template strings). The template literals are introduced in ECMAScript 2015 (ES6). Before introduction of template literals, the multiline strings are created by concatenating multiple strings using + operator.

    In JavaScript, a string is a sequence of characters containing alphabetical, numeric, and special characters. We can create the string using single quote (‘), double quote (“) or backtick (`) characters.

    Creating Multiline Strings Using Template Literals

    The template literals are the best way to create multiline string in JavaScript. Template literals are enclosed with backtick (`) characters. A template literal contains strings and also placeholders. Template literals are sometimes also called template strings.

    A simple example of a template literal is as follows −

    `This is a template literal enclosed by backtick characters.`

    Let’s now create a multiline string using template literals −

    let multilineString =`This is a multiline
    string created using
    template literal.`

    In the above JavaScript code snippet, we have created a multiline string containing three lines. We assigned this multiline string to the variable called multilineString.

    Example

    In the below example, we have created a multiline string using template literal and displayed the string in the web console.

    let mulString =`This is a multiline
    string created using
    template literal.`;
    console.log(mulString);

    Output

    This is a multiline
    string created using
    template literal.
    

    Example

    In the below example, we are trying to display the multiline string crated using the template literal on the webpage. We used <br> to make a line break.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString =`This is a multine <br>
          string created using template literal <br>
          and displayed on the webpage.`;    
          document.getElementById("output").innerHTML = mulString;</script></body></html>

    Output

    This is a multine
    string created using template literal
    and displayed on the webpage.
    

    Creating Multiline String Using + Operator

    We can also create a multiline string in JavaScript by concatenating the individual strings using + operator. To create a line break, we can use the escape character \n or <br>.

    You can concatenate the strings defined with single or double quotes.

    Let’s have a look at the following example −

    Example

    In this example, we created a multiline string by concatenating three individual strings. We used escape character (\n) at the end of the individual strings to break the line.

    let mulString ="This is a multiline string\n"+"created by concatenating the individual strings\n"+"and using \\n to break the line.";
    console.log(mulString);

    Output

    This is a multiline string
    created by concatenating the individual strings
    and using \n to break the line.
    

    Example

    In the example below, we created a multiline string by concatenating three strings. We used <br> to break the line.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString ="This is a multiline string <br>"+"created by concatenating the individual strings<br>"+"and line break.";  
          document.getElementById("output").innerHTML = mulString;</script></body></html>

    Output

    This is a multiline string
    created by concatenating the individual strings
    and line break.
    

    Creating Multiline String Using \ Operator

    We can use backslash (\) operator to create multiline strings in JavaScript. We can use the escape character (\n) to break the line.

    Example

    Try the following JavaScript example −

    let mulString ="This is a multiline string\n\
    created using the backslash operator\n\
    and escape character to break the line.";
    console.log(mulString);

    Output

    This is a multiline string
    created using the backslash operator
    and escape character to break the line.
    

    Example

    In the example below, we have created a multiline string using the backslash (\) operator. And to make a line break, we used <br>.

    <!DOCTYPE html><html><body><p id ="output"></p><script>let mulString ="This is first line of the multiline string <br>\
          This is second line of the multiline string <br> \
          This is the last line of multiline string.";    
          document.getElementById("output").innerHTML = mulString;</script></body></html>

    Output

    This is first line of the multiline string
    This is second line of the multiline string
    This is the last line of multiline string.
  • JavaScript – 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 +"<br>"+"Age: "+person.age+"<br>"+"Occupation: "+person.occupation;</script></body></html>

    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;</script></body></html>

    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;</script></body></html>

    Output

    Converting JavaScript object to JSON string
    {"name":"John Doe","age":30,"isStudent":false}
  • JavaScript – 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("<br /> Browser version info : "+ version );</script></body></html>

    Output

    On executing the above program, you will get the output similar to the following −https://www.tutorialspoint.com/javascript/src/browsers_handling.htm

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

  • JavaScript – 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
             }</script></head><body><form name ="myform"><input type ="text" name ="stage" size ="20"/></form><!-- Create  Mappings --><img src ="/images/usemap.gif" alt ="HTML Map" border ="0" usemap ="#tutorials"/><map name ="tutorials"><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('')"/><area shape ="rect" 
                coords ="22,83,126,125"
                href ="/html/index.htm" alt ="HTML Tutorial" 
                target ="_self" 
                onMouseOver ="showTutorial('html')" 
                onMouseOut ="showTutorial('')"/><area shape ="circle" 
                coords ="73,168,32"
                href ="/php/index.htm" alt ="PHP Tutorial"
                target ="_self" 
                onMouseOver ="showTutorial('php')" 
                onMouseOut ="showTutorial('')"/></map></body></html>

    Output

    You can feel the map concept by placing the mouse cursor on the image object.https://www.tutorialspoint.com/javascript/src/image_map.htm

  • JavaScript – 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("<tr><td>");
                   document.write(navigator.plugins[i].name);
                   document.write("</td><td>");
                   document.write(navigator.plugins[i].filename);
                   document.write("</td><td>");
                   document.write(navigator.plugins[i].description);
                   document.write("</td></tr>");}</script></table></body></html>

    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("<embed src = 'quick.mov' height = 100 width = 100>");}else{
                document.write("<img src = 'quick.gif' height = 100 width = 100>");}</script></body></html>

    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();}</script></head><body><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"><form name ="form" id ="form" action ="#" method ="get"><input type ="button" value ="Start" onclick ="play();"/><input type ="button" value ="Stop" onclick ="stop();"/><input type ="button" value ="Rewind" onclick ="rewind();"/></form></body></html>
  • JavaScript – 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;</script></head><body><form><img id ="myImage" src ="/images/html.gif"/><p>Click button below to move the image to right</p><input type ="button" value ="Click Me" onclick ="moveRight();"/></form></body></html>

    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;</script></head><body><form><img id ="myImage" src ="/images/html.gif"/><p>Click the buttons below to handle animation</p><input type ="button" value ="Start" onclick ="moveRight();"/><input type ="button" value ="Stop" onclick ="stop();"/></form></body></html>

    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";}</script></head><body><p>Move your mouse over the image to see the result</p><a href ="#" onMouseOver ="document.myImage.src = image2.src;"
             onMouseOut ="document.myImage.src = image1.src;"><img name ="myImage" src ="/images/html.gif"/></a></body></html>
  • JavaScript – 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);}</script>

    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 <1||( dotpos - atpos <2)){alert("Please enter correct email ID")
             document.myForm.EMail.focus();returnfalse;}return(true);}</script>