Category: Basic

  • Reserved Keywords

    Reserved Keywords in JavaScript

    The reserved keywords in JavaScript are predefined keywords used to serve the built-in functionality of the programming language. For example, the var and let keywords are used to define variables, the function keyword is used to define the functions, etc. JavaScript contains more that fifty reserved keywords.

    In simple terms, you can’t use the reserved keywords as an identifier. If you do, you will get the conflicts, and the code will generate the wrong output or throw an error.

    For example, the below code will throw an error as function is used as an identifier.

    varfunction="Hello";

    Reserved Keywords

    Here is the list of reserved keywords; you cant use them as an identifier −

    abstractdoubleimplementsreturn
    argumentselseinswitch
    awaitenuminstanceofsynchronized
    booleanevalintthis
    breakexportinterfacethrow
    byteextendsletthrows
    casefalselongtransient
    catchfinalnativetrue
    charfinallynewtry
    classfloatnulltypeof
    constforpackagevar
    continuefunctionprivatevoid
    debuggergotoprotectedvolatile
    defaultifpublicyield
    deleteimplementsshortwhile
    doimportstaticwith
    doubleinsuper

    Reserved Keywords added in ES5 and ES6

    Some new keywords are added in the ES5 and ES6 versions of JavaScript. However, some are currently in use, and some keywords are reserved for future versions.

    awaitclassenumexport
    extendsimportletSuper

    Removed Reserved Keywords

    Some reserved keywords are removed from JavaScript, which you cant use to achieve a particular functionality. Still, you cant use the keywords below as an identifier as many browsers dont support them.

    abstractbooleanbytechar
    doublefinalfloatgoto
    intlongnativeshort
    synchronizedthrowstransientvolatile

    JavaScript Objects, Properties, and Methods

    You should not use the name of JavaScript built-in objects, properties, and methods names as an identifier.

    JavaScript Built-in Objects

    ArrayArrayBufferBooleanDataView
    DateErrorevalFloat32Array
    Float64ArrayFunctionGeneratorGeneratorFunction
    Int8ArrayInt16ArrayInt32ArrayIntl
    JSONMapMathNumber
    ObjectPromiseProxyRangeError
    ReferenceErrorReflectRegExpSet
    StringSymbolSyntaxErrorTypeError
    Uint8ArrayUint8ClampedArrayUint16ArrayUint32Array
    URIErrorWeakMapWeakSet

    JavaScript Built-in Properties

    lengthconstructorprototype__proto__callercallee

    JavaScript Methods

    toStringshiftindexOfsplit
    toLocaleStringunshiftlastIndexOfsubstr
    valueOfsliceincludessubstring
    toLocaleDateStringspliceisArraytoLowerCase
    toLocaleTimeStringsortfromtoLocaleLowerCase
    toLocaleStringforEachoftoUpperCase
    toFixedmapcharAttoLocaleUpperCase
    toExponentialfiltercharCodeAttrim
    toPrecisionreducecodePointAtstartsWith
    concatreduceRightnormalizeendsWith
    joineveryrepeatmatch
    popsomereplacetest
    pushfindsearchreverse
    findIndexslice

    However, you can explore more built-in JavaScript methods and avoid using them as an identifier.

    Other Reserved Keywords

    JavaScript can be used with other programming languages like HTML, Java, etc. So, you should also avoid keywords that are reserved in HTML, Java, etc.

    Here is the list of other reserved keywords, and most of them are properties of the window object.

    alertelementsframeRateradio
    allembedhiddenreset
    anchorembedshistoryscreenX
    anchorsencodeURIimagescreenY
    areaencodeURIComponentimagesscroll
    assignescapeoffscreenBufferingsecure
    blureventopenselect
    buttonfileUploadopenerself
    checkboxfocusoptionsetInterval
    clearIntervalformouterHeightsetTimeout
    clearTimeoutformsouterWidthstatus
    clientInformationframepackagessubmit
    closeinnerHeightpageXOffsettaint
    closedinnerWidthpageYOffsettext
    confirmlayerparenttextarea
    constructorlayersparseFloattop
    cryptolinkparseIntunescape
    decodeURIlocationpassworduntaint
    decodeURIComponentmimeTypespkcs11window
    defaultStatusnavigateplugindocument
    navigatorpromptelementframes
    propertyIsEnum

    HTML Event Handlers

    You shouldnt use the HTML even handlers as a variable name in JavaScript.

    Here, we have listed some of the event handlers.

    onclickondblclickonmouseoveronmouseout
    onmousemoveonkeydownonkeyuponkeypress
    onfocusonbluronchangeonsubmit
    onresetonloadonunloadonresize
    onscroll

    In short, you should avoid using all the above keywords as a variable or function name.

  • Strict Mode

    Strict Mode in JavaScript

    In JavaScript, the strict mode is introduced in the ES5 (ECMAScript 2009). The purpose behind introducing the “strict mode” is to make the JavaScript code more secure.

    The ‘use strict‘ literal expression is used to add the strict mode in the JavaScript code. It removes the silent errors from the code, such as you can’t use the variable without declaration, you can’t modify the readable property of the object, etc.

    Enabling Strict Mode

    To enble strcit mode, you should write the following literal expression to the top of your code −

    'use strict';

    The ‘use strict’ directive is used enable JavaScript’s strict mode.

    Why Use the Strict Mode?

    Here, we have listed some reasons for using the strict JavaScript mode −

    • Error Prevention − The strict mode prevents the common errors which developers make while writing the JavaScript code, such as initializing the variable without declaration or using the reserved keywords as an identifier.
    • Safer Code − The strict mode prevents the creation of global variables accidentally. Also, it doesn’t allow to use of statements like ‘with’, which can lead to vulnerability in the code.
    • Future Compatibility − You can align your code with the future versions of JavaScript by using the script mode. For example, the current version of JavaScript doesn’t contain keywords like ‘public’ but is reserved for future versions. So, the strict mode won’t allow you to use it as an identifier from now.

    Strict Mode in the Global Scope

    When you add the ‘use strict‘ at the top of the JavaScript code; it uses the strict mode for the whole code.

    Example

    In the example below, we have defined the ‘y’ variable and initialized it with the 50. The code prints the value of ‘y’ in the output.

    Also, we initialized the variable ‘x’ without declaring it. So, it gives the error in the console and doesn’t print the output.

    In short, the strict mode doesn’t allow you to use the variable without its declaration.

    <html><head><title> Using the strict mode gloablly </title></head><body><script>"use strict";let y =50;// This is valid
    
      document.write("The value of the X is: "+ y);
      x =100;// This is not valid
      document.write("The value of the X is: "+ x);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Strict Mode in the Local Scope

    You can also use the "strict mode" inside the particular function. So, it will be applied only in the function scope. Let's understand it with the help of an example.

    Example

    In the example below, we used the 'use strict' literal only inside the test() function. So, it removes the unusual errors from the function only.

    The code below allows you to initialize the variable without declaring it outside the function but not inside it.

    <html><head><title> Using the strict mode gloablly </title></head><body><script>
    
        x =100;// This is valid
        document.write("The value of the X is - "+ x);functiontest(){"use strict";
            y =50;// This is not valid
            document.write("The value of the y is: "+ x);}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Mistakes that you should't make in the strict mode

    1. You can't initialize the variable with a value without declaring it.

    <script>'use strict';
       num =70.90;// This is invalid</script>

    2. Similarly, you can't use the object without declaring it.

    <script>'use strict';
       numObj ={a:89, b:10.23};// This is invalid</script>

    3. You can't delete objects using the delete keyword.

    <script>'use strict';let women ={ name:"Aasha", age:29};delete women;// This is invalid</script>

    4. You can't delete the object prototype in the strict mode.

    <script>'use strict';let women ={ name:"Aasha", age:29};delete women.prototype;// This is invalid</script>

    5. Deleting the function using the delete operator is not allowed.

    <script>'use strict';functionfunc(){}delete func;// This is invalid</script>

    6. You can't have a function with duplicate parameter values.

    <script>'use strict';functionfunc(param1, param1, param2){// Function with 2 param1 is not allowed!}</script>

    7. You can't assign octal numbers to variables.

    <script>'use strict';let octal =010;// Throws an error</script>

    8. You can't use escape characters.

    <script>'use strict';let octal = \010;// Throws an error</script>

    9. You can't use reserved keywords like eval, arguments, public, etc., as an identifier.

    <script>'use strict';letpublic=100;// Throws an error</script>

    10. You can't write to the readable property of the object.

    <script>'use strict';let person ={};
    
    
    Object.defineProperty(person,'name',{ value:"abc", writable:false});
    obj1.name ="JavaScript";// throws an error&lt;/script&gt;</pre>

    11. You can't assign values to the getters function.

    <script>'use strict';let person ={getname(){return"JavaScript";}};
       obj1.name ="JavaScript";// throws an error</script>

    12. In the strict mode, when you use the 'this' keyword inside the function, it refers to the reference object through which the function is invoked. If the reference object is not specified, it refers to the undefined value.

    <script>'use strict';functiontest(){
    
      console.log(this);// Undefined}test();&lt;/script&gt;</pre>

    13. You can't use the 'with' statement in the strict mode.

    <script>'use strict';with(Math){x =sin(2)};// This will throw an error</script>

    14. You can't use the eval() function to declare the variables for the security reason.

    <script>'use strict';eval("a = 8")</script>

    15. You can't use the keywords as an identifier that are reserved for the future. Below keywords are reserved for the future −

    • implements
    • interface
    • package
    • private
    • protected
  • Type Conversions

    JavaScript Type Conversions

    Type Conversions in JavaScript refer to the automatic or explicit process of converting data from one data type to another in JavaScript. These conversions are essential for JavaScript to perform operations and comparisons effectively. JavaScript variables can contain the values of any data type as it is a weakly typed language.

    There are two types of type conversion in JavaScript −

    • Implicit type conversion
    • Explicit type conversion

    The implicit type conversion is also known as coercion.

    Implicit Type Conversion

    When type conversion is done by JavaScript automatically, it is called implicit type conversion. For example, when we use the ‘+‘ operator with the string and number operands, JavaScript converts the number to a string and concatenates it with the string.

    Here are some examples of the implicit type conversion.

    Converting to String (Implicit conversion)

    In this example, we used the ‘+‘ operator to implicitly convert different values to the string data type.

    "100"+24;// Converts 24 to string'100'+false;// Converts false boolean value to string"100"+null;// Converts null keyword to string

    Please note that to convert a value to string using “+” operator, one operand should be string.

    Let’s try the example below, and check the output −

    <html><head><title>Implicit conversion to string </title></head><body><script>
    
      document.write("100"+24+"&lt;br/&gt;");
      document.write('100'+false+"&lt;br/&gt;");
      document.write("100"+null+"&lt;br/&gt;");
      document.write("100"+undefined+"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Converting to Number (Implicit conversion)

    When you use the string values containing the digits with the arithmetic operators except for the '+' operator, it converts operands to numbers automatically and performs the arithmetic operation, which you can see in the example below.

    Boolean values are also gets converted to a number.

    '100'/50;// Converts '100' to 100'100'-'50';// Converts '100' and '50' to 100 and 50'100'*true;// Converts true to 1'100'-false;// Converts false to 0'tp'/50// converts 'tp' to NaN

    Try the example below and check the output −

    <html><head><title> Implicit conversion to Number </title></head><body><script>
    
    	document.write(('100'/50)+"&lt;br&gt;");
        document.write(('100'-'50')+"&lt;br&gt;");
        document.write(('100'*true)+"&lt;br&gt;");
        document.write(('100'-false)+"&lt;br&gt;");
        document.write(('tp'/50)+"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Converting to Boolean (Implicit conversion)

    When you use the Nullish (!!) operator with any variable, it implicitly converts its value to the boolean value.

    num =!!0;// !0 = true, !!0 = false
    num =!!1;// !1 = false, !!1 = true
    str =!!"";// !"" = true, !!"" = false
    str =!!"Hello";// !"Hello" = false, !!"Hello" = true

    Null to Number (Implicit conversion)

    In JavaScript, the null represents the empty. So, null automatically gets converted to 0 when we use it as an operand of the arithmetic operator.

    let num =100+null;// Converts null to 0
    num =100*null;// Converts null to 0

    Undefined with Number and Boolean (Implicit conversion)

    Using the undefined with the 'number' or 'boolean' value always gives the NaN in the output. Here, NaN means not a number.

    <html><head><title> Using undefinedwith a number and boolean value </title></head><body><script>let num =100+undefined;// Prints NaN
    
      document.write("The value of the num is: "+ num +"&lt;br&gt;");
      num =false*undefined;// Prints NaN
      document.write("The value of the num is: "+ num +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Explicit Type Conversion

    In many cases, programmers are required to convert the data type of the variable manually. It is called the explicit type conversion.

    In JavaScript, you can use the constructor functions or built-in functions to convert the type of the variable.

    Converting to String (Explicit conversion)

    You can use the String() constructor to convert the numbers, boolean, or other data types into the string.

    String(100);// number to stringString(null);// null to stringString(true);// boolean to string

    Example

    You can use the String() constructor function to convert a value to the string.You can also use typeof operator to check the type of the resultant value.

    <html><head><title> Converting to string explicitly </title></head><body><script>
    
        document.write(typeofString(100)+"&lt;br/&gt;");
        document.write(typeofString(null)+"&lt;br/&gt;");
        document.write(typeofString(true)+"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    We can also use the toString() method of Number object to convert number to string.

    const num =100;
    num.toString()// converts 100 to '100'

    Converting to Number (Explicit conversion)

    You can use the Numer() constructor to convert a string into a number. We can also use unary plus (+) operator to convert a string to number.

    Number('100');// Converts '100' to 100Number(false);// Converts false to 0Number(null);// Converts null to 0
    num =+"200";// Using the unary operator

    However, you can also use the below methods and variables to convert the string into numbers.

    Sr.No.Method / OperatorDescription
    1parseFloat()To extract the floating point number from the string.
    2parseInt()To extract the integer from the string.
    3+It is an unary operator.

    Example

    You can use the Number() constructor function or unary (+) operator to convert a string, boolean, or any other value to a number.

    The Number() function also converts the exponential notation of a number to a decimal number.

    <html><head><title> Converting to string explicitly </title></head><body><script>
    
      document.write(Number("200")+"&lt;br/&gt;");
      document.write(Number("1000e-2")+"&lt;br/&gt;");
      document.write(Number(false)+"&lt;br/&gt;");
      document.write(Number(null)+"&lt;br/&gt;");
      document.write(Number(undefined)+"&lt;br/&gt;");
      document.write(+"200"+"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Converting to Boolean (Explicit conversion)

    You can use the Boolean() constructor to convert the other data types into Boolean.

    Boolean(100);// Converts number to boolean (true)Boolean(0);// 0 is falsy value (false)Boolean("");// Empty string is falsy value (false)Boolean("Hi");// Converts string to boolean (true)Boolean(null);// null is falsy value (false)

    Example

    You can use the Boolean() constructor to convert values to the Boolean. All false values like 0, empty string, null, undefined, etc., get converted to false and other values are converted to true.

    <html><head><title> Converting to string explicitly </title></head><body><script>
    
      document.write(Boolean(100)+"&lt;br/&gt;");
      document.write(Boolean(0)+"&lt;br/&gt;");
      document.write(Boolean("")+"&lt;br/&gt;");
      document.write(Boolean("Hi")+"&lt;br/&gt;");
      document.write(Boolean(null)+"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Converting Date to String/Number

    You can use the Date object's Number() constructor or getTime() method to convert the date string into the number. The numeric date represents the total number of milliseconds since 1st January 1970.

    Follow the syntax below to convert the date into a number.

    Number(date);OR
    date.getTime();

    You can use the String() constructor or the toString() method to convert the date into a string.

    Follow the syntax below to convert the date into the string.

    String(date);OR
    date.toString();

    Let's try to demonstrate this with the help of a program.

    <html><head><title> Coverting date to string / number </title></head><body><script>let date =newDate();let numberDate = date.getTime();
    
      document.write("The Numeric date is: "+ numberDate +"&lt;br/&gt;");let dateString = date.toString();
      document.write("The string date is: "+ dateString +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Conversion Table in JavaScript

    In the below table, we have given the original values and their resultant value when we convert the original value to string, number, and boolean.

    ValueString conversionNumber conversionBoolean conversion
    0"0"0false
    1"1"1true
    "1""1"1true
    "0""0"0true
    """"0false
    "Hello""Hello"NaNtrue
    true"true"1true
    false"false"0false
    null"null"0false
    undefined"undefined"NaNfalse
    [50]"50"50true
    [50, 100]"[50, 100]"NaNtrue

  • Data Types

    JavaScript Data Types

    Data types in JavaScript referes to the types of the values that we are storing or working with. One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

    JavaScript data types can be categorized as primitive and non-primitive (object). JavaScript (ES6 and higher) allows you to work with seven primitive data types −

    • Strings of text e.g. “This text string” etc.
    • Numbers, eg. 123, 120.50 etc.
    • Boolean e.g. true or false.
    • null
    • undefined
    • BigInt
    • Symbol

    BigInt and Symbol are introduced in ES6. In ES5, there were only five primitive data types.

    In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.

    The Object data type contains the 3 sub-data types −

    • Object
    • Array
    • Date

    Why are data types important?

    In any programming language, data types are important for operation manipulation.

    For example, the below code generates the 1010 output.

    let sum ="10"+10;

    Here, the JavaScript engine converts the second operand to a string and combines it using the ‘+’ operator rather than adding them.

    So, you need to ensure that the type of operands is correct.

    Now, let’s learn about each data type with examples.

    JavaScript String

    In JavaScript, the string is a sequence of characters and can be created using 3 different ways given below −

    • Using the single quote
    • Using the double quote
    • Using the backticks

    Example

    In the example below, we have created strings using single quotes, double quotes, and backticks. In the output, it prints the same result for all 3 strings.

    <html><head><title> JavaScript string </title></head><body><script>let str1 ="Hello World!";// Using double quoteslet str2 ='Hello World!';// Using single quoteslet str3 =Hello World!;// Using backticks
    
      document.write(str1 +"&lt;br&gt;");
      document.write(str2 +"&lt;br&gt;");
      document.write(str3 +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Number

    A JavaScript number is always stored as a floating-point value (decimal number).

    JavaScript does not make a distinction between integer values and floating-point values.

    JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

    Example

    In the example below, we demonstrate JavaScript numbers with and without decimal points.

    <html><head><title> JavaScript number </title></head><body><script>let num1 =10;// Integerlet num2 =10.22;// Floating point number
    
      document.write("The value of num1 is "+ num1 +"&lt;br/&gt;");
      document.write("The value of num2 is "+ num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example (Exponential notation of numbers)

    JavaScript also support exponential notaion of numbers. We have explained this in the below example code −

    <html><head><title> JavaScript number Exponential notation </title></head><body><script>let num1 =98e4;// 980000let num2 =98e-4;// 0.0098
    
      document.write("The value of num1 is: "+ num1 +"&lt;br/&gt;");
      document.write("The value of num2 is: "+ num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Boolean

    In JavaScript, the Boolean data type has only two values: true or false.

    <html><head><title> JavaScript Boolean </title></head><body><script>let bool1 =true;let bool2 =false;
    
      document.write("The value of the bool1 is "+ bool1 +"&lt;br/&gt;");
      document.write("The value of the bool2 is "+ bool2 +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Undefined

    When you declare a variable but don't initialize it, it contains an undefined value. However, you can manually assign an undefined value to the variable also.

    <html><head><title> JavaScript Undefined </title></head><body><script>let houseNo;// Contains undefined valuelet apartment ="Ajay";
    
      apartment =undefined;// Assigning the undefined value
      document.write("The value of the house No is: "+ houseNo +"&lt;br/&gt;");
      document.write("The value of the apartment is: "+ apartment +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Null

    When any variable's value is unknown, you can use the null. It is good practice to use the null for the empty or unknown value rather than the undefined one.

    <html><head><title> JavaScript null</title></head><body><script>let houseNo =null;// Unknown house numberlet apartment ="B-2";
    
      appartment =null;// Updating the value to null
      document.write("The value of the houseNo is: "+ houseNo +"&lt;br/&gt;");
      document.write("The value of the apartment is: "+ apartment +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Bigint

    JavaScript stores only 64-bit long floating point numbers. If you want to store a very large number, you should use the Bigint. You can create Bigint by appending n to the end of the number.

    <html><head><title> JavaScript Bigint </title></head><body><script>let largeNum =1245646564515635412348923448234842842343546576876789n;
    
      document.write("The value of the largeNum is "+ largeNum +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Symbol

    The Symbol data type is introduced in the ES6 version of JavaScript. It is used to create unique primitive, and immutable values.

    The Symbol() constructor can be used to create a unique symbol, and you may pass the string as a parameter of the Symbol() constructor.

    Example

    In the example below, we created the sym1 and sym2 symbols for the same string. After that, we compared the value of sym1 and sym2, and it gave a false output. It means both symbols are unique.

    <html><head><title> JavaScript Symbol </title></head><body><script>let sym1 =Symbol("123");let sym2 =Symbol("123");let res = sym1 === sym2;
    
      document.write("Is sym1 and Sym2 are same? "+ res +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Object

    In JavaScript, the object data type allows us to store the collection of the data in the key-value format. There are multiple ways to define the object, which we will see in the Objects chapter.

    Here, we will create an object using the object literals.

    Example

    In the example below, we used the '{}' (Object literals) to create an obj object. The object contains the 'animal' property with the string value, the 'legs' property with the number value, and the value of the 'color' variable is assigned to the 'hourseColor' property.

    The JSON.stringify() method converts the object to strings and shows it in the output.

    <html><head><title> JavaScript Object </title></head><body><script>let color ="Brown";const obj ={
    
         animal:"Hourse",
         legs:4,
         hourseColor: color
      }
      document.write("The given object is: "+JSON.stringify(obj)+"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Array

    In JavaScript, the array is a list of elements of the different data types. You can create an array using two square brackets '[]' and insert multiple comma seprated values inside the array.

    <html><head><title> JavaScript Array </title></head><body><script>const colors =["Brown","red","pink","Yellow","Blue"];
    
      document.write("The given array is: "+ colors +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Date

    You can use the JavaScript Date object to manipulate the date.

    Example

    In the example below, we used the Date() constructor to create a date. In the output, you can see the current date and time according to your time zone.

    <html><head><title> JavaScript Date </title></head><body><script>let date =newDate();
    
      document.write("The today's date and time is: "+ date +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Dynamic Types

    JavaScript is a dynamically typed language like Python and Ruby. So, it decides the variable's data type at the runtime but not at the compile time. We can initialize or reassign the value of any data type to the JavaScript variables.

    Example

    In the example below, we initialized the first variable with the string value. After that, we updated its values to the number and boolean value.

    <html><head><title> JavaScript dynamic data type </title></head><body><script>let first ="One";// it is string
    
      first =1;// now it's Number
      document.write("The value of the first variable is "+ first +"&lt;br/&gt;");
      first =true;// now it's Boolean
      document.write("The value of the first variable is "+ first +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Checking Data Types Using the typeof Operator

    The typeof operator allows you to check the type of the variable.

    Example

    In the below example, we used the typeof operator to check the data type of the various variables.

    <html><head><title>typeof operator </title></head><body><script>let num =30;let str ="Hello";let bool =true;
    
      document.write("The data type of num is: "+typeof num +"&lt;br/&gt;");
      document.write("The data type of str is: "+typeof str +"&lt;br/&gt;");
      document.write("The data type of bool is: "+typeof bool +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Constants

    JavaScript constants are the variables whose values remain unchanged throughout the execution of the program. You can declare constants using the const keyword.

    JavaScript const Keyword

    The const keyword is introduced in the ES6 version of JavaScript with the let keyword. The const keyword is used to define the variables having constant reference.

    A variable defined with const can’t be re-declaredreassigned. The const declaration have block as well as function scope.

    Declaring JavaScript Constants

    You always need to assign a value at the time of declaration if the variable is declared using the const keyword.

    const x =10;// Correct Way

    In any case, you can’t declare the variables with the const keyword without initialization.

    const y;// Incorrect way
    y =20;

    Can’t be Reassigned

    You can’t update the value of the variables declared with the const keyword.

    const y =20; 
    y =40;// This is not possible

    Block Scope

    A JavaScript variable declared with const keyword has block-scope. This means same variable is treated as different outside the block.

    In the below example, the x declared within block is different from x declared outside the block. So we can re-declare the same variable outside the block

    {const x ="john";}const x ="Doe"

    But we can’t re-declare the const variable within the same block.

    {const x ="john";const x ="Doe"// incorrect}

    Constant Arrays and Objects in JavaScript

    We can declare the arrays and objects using the const keyword, but there is a little twist in the array and object declaration.

    The variable with the const keyword keeps the constant reference but not the constant value. So, you can update the same array or object declared with the const keyword, but you can’t reassign the reference of the new array or object to the constant variable.

    Example (Constant Arrays)

    In the example below, we have defined the array named ‘arr’ using the const keyword. After that, we update the array element at the 0th index and insert the ‘fence’ string at the end of the array.

    In the output, you can observe that it prints the updated array.

    <html><head><title> Constant Arrays </title></head><body><script>// Defining the constant arrayconst arr =["door","window","roof","wall"];// Updating arr[0]
    
      arr[0]="gate";// Inserting an element to the array
      arr.push("fence");//arr = ["table", "chair"] // re-assigning array will cause error.// Printing the array
      document.write(arr);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    When you execute the above code, it will produce the following result −

    gate,window,roof,wall,fence
    

    Example (Constant Objects)

    In the below example, we created the 'obj' object with the const keyword. Next, we update the 'animal' property of the object and insert the 'legs' property in the object. In the output, the code prints the updated object.

    <html><head><title> Constant Objects </title></head><body><script>// Defining the constant objectconst obj ={
    
         animal:"Lion",
         color:"Yellow",};// Changing animal name
      obj.animal ="Tiger";// Inserting legs property
      obj.legs =4;// Printing the object
      document.write(JSON.stringify(obj));// obj = { name: "cow" } // This is not possible&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    {"animal":"Tiger","color":"Yellow","legs":4}
    

    So, we can't change the reference to the variables (arrays and objects) declared with the const keyword but update the elements and properties.

    No Const Hoisting

    Variables defined with const keyword are not hoisted at the top of the code.

    In the example below, the const variable x is accessed before it defined. It will cause an error. We can catch the error using try-catch statement.

    <html>
    <body>
       <script>
    
      document.write(x);
    const x = 10; </script> </body> </html>

    Here are some other properties of the variables declared with the const keyword.

    • Block scope.
    • It can't be re-declared in the same scope.
    • Variables declared with the const keyword can't be hoisted at the top of the code.
    • Constant variables value is a primitive value.

    Difference between var, let and const

    We have given the comparison table between the variables declared with the var, let, and const keywords.

    Comparison basisvarletconst
    ScopeFunctionBlockBlock
    HoistedYesNoNo
    ReassignYesYesNo
    Re-declareYesNoNo
    Bind ThisYesNoNo

    Which should you use among var, let, and const?

    • For the block scope, you should use the let keyword.
    • If you need to assign the constant reference to any value, use the const keyword.
    • When you require to define the variable inside any particular block, like a loop, 'if statement', etc. and need to access outside the block but inside the function, you may use the var keyword.
    • However, you can use any keyword to define global variables.
    • Re-declaring variables is not a good practice. So, you should avoid it, but if necessary, you may use the var keyword.
  •  let Statement

    What is JavaScript let statement?

    The JavaScript let statement is used to declare a variable. With the let statement, we can declare a variable that is block-scoped. This mean a variable declared with let is only accessible within the block of code in which it is defined.

    The let keyword was introduced in the ES6 (2015) version of JavaScript. It is an alternative to the var keyword.

    The main reason behind introducing the let keyword is to improve the scoping behaviors of variables and the safety of the code.

    Variable Declaration with let statement

    Following is the syntax to declare a variable with let statement −

    let var_name = value
    

    Let’s have a look at some examples for variable declaration with let.

    let name ="John";let age =35;let x =true;

    Using let statement we can declare a variable of any datatypes, e.g., numeric, string, boolean, etc.

    JavaScript Block Scope vs. Function Scope

    The scope of the variable declared with the let keyword is a block-scope. It means if you define the variable with the let keyword in the specific block, you can access the variable inside that particular block only, and if you try to access the variable outside the block, it raises an error like ‘variable is not defined’.

    {let x ="John";}//here x can't be accessed

    The var keyword has a function scope, meaning if you define the variable using the var keyword in any function block, you can access it throughout the function.

    functionfoo(){if(true){let x =5var y =10}// here x can't be accessed while y is accessible}

    Sometimes, we require to define the variable with the same name in different blocks of one function. Conflicts may occur with the variable value if they use the var keyword.

    Example

    In the example below, we have defined the variable x using the let keyword and variable y using the var keyword. Also, we have assigned 10 and 20 values to both variables, respectively.

    We defined the test() function, redeclared the x and y variables inside it, and initialized them with 50 and 100 values, respectively. We print variable values inside the function, and it prints the 50 and 100 as it gives first preference to the local variables over global variables.

    <html><head><title> Variable declaration withlet keyword </title></head><body><script>let x =10;var y =20;functiontest(){let x =50;var y =100;
    
         document.write("x = "+ x +", y = "+ y +"&lt;br/&gt;");}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In the example below, we initialized the bool variable with a 'true' value. After that, we declared the variables x and y using the let and var keywords in the 'if' block.

    We print the value of the x and y variable inside the 'if' block. We can't access the 'x' variable outside the 'if' block as it has blocked scope, but we can access variable y outside the 'if' block and inside the function block as it has function scope.

    <html><head><title> Variable declaration withlet keyword </title></head><body><script>functiontest(){let bool =true;if(bool){let x =30;var y =40;
    
    	    document.write("x = "+ x +", y = "+ y +"&lt;br/&gt;");}// x can't be accessible here
    document.write("y = "+ y +"<br/>");}test();</script></body></html>

    In this way, the let keyword is used to improve the scoping behaviors of the code.

    Redeclaring Variables in JavaScript

    You can't redeclare the variables declared with the let keyword in the same block. However, you can declare the variables with the same name into the different blocks with the same function.

    Example

    In the example below, you can observe that variables declared with the let keyword cant be redeclared in the same block, but variables declared with the var keyword can be redeclared in the same block.

    The code prints the value of the newly declared variable in the output.

    <html><head><title> Variable redeclaring </title></head><body><script>functiontest(){if(1){let m =70;// let m = 80; // redeclaration with let keyword is not	possiblevar n =80;var n =90;// redeclaration with var keyword is possible
    			document.write("m = "+ m +", n = "+ n);}}test();</script></body></html>

    Variable Hoisting

    The hoisting behaviors of JavaScript move the declaration of the variables at the top of the code. The let keyword doesn't support hoisting, but the var keyword supports the hosting.

    Example

    In the example below, you can see that we can initialize and print the value of the variable n before its declaration as it is declared using the var keyword.

    <html><head><title> Variable hoisting </title></head><body><script>functiontest(){// Hoisiting is not supported by let keyword// m = 100;// document.write("m = " + m + "<br/>");// let m;
    
         n =50;
         document.write("n = "+ n +"&lt;br/&gt;");var n;}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    You can uncomment the code using the let keyword and check the error in the web console, as it doesn't support hoisting.

  • Variables

    JavaScript Variables

    JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

    Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways −

    • Without using any keywords.
    • Using the ‘var‘ keyword.
    • Using the ‘let‘ keyword.
    • Using the ‘const‘ keyword.

    The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, only var keyword was used to declare the variable in JavaScript. In this section, we will discuss ‘var’ keyword. We will cover the ‘let’ and ‘const’ keywords in subsequent chapters.

    Variable Declaration in JavaScript

    You can follow the syntax below to declare the variables without using any keywords.

    <script>
       Money =10;
       Name ="tutorialspoint";</script>

    Furthermore, you can use the var keyword to declare the variables as shown below.

    <script>var money;var name;</script>

    You can also declare multiple variables with the same var keyword as follows −

    <script>var money, name;</script>

    Variable Initialization using the Assignment Operator

    Storing a value in a variable is called variable initialization. You can initialize a variable at the time of creation or at a later point in time when you need that variable.

    For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.

    <script>var name ="Ali";var money;
       money =2000.50;</script>

    Note: Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.

    JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold.

    The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

    JavaScript Data Types

    In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables.

    <script>var num =765;// Numbervar str ="Welcome";// Stringvar bool =false;// Boolean</script>

    You will learn data types in detail in JavaScript Data Types chapter.

    JavaScript Variable Names (Identifiers)

    In JavaScript, a unique character sequence is used to name the variables called identifiers.

    Here are some rules for the naming of the identifiers in JavaScript −

    • Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
    • Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers.
    • Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language.
    • Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords.

    JavaScript Dollar Sign ($) and Under Score (_)

    You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character.

    Example (Demonstrating the identifiers)

    In this example, we have defined the variables using the var keyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign.

    Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit.

    <html><head><title> Variables in JavaScript </title></head><body><script>var _abc ="Hi!";var $abc ="Hello!";//  var 9abc = "Bye!";  // This is invalid
    
        document.write("_abc "+ _abc +"&lt;br&gt;");
        document.write("$abc = "+ $abc +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It produces the following result −

    _abc Hi!
    $abc = Hello!
    

    Undefined Variable Value in JavaScript

    When you don't initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable.

    Example

    Let's look at the example below −

    <html><body><script>var num;
    
      document.write("The value of num is: "+ num +"&lt;br/&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    This produces the following result −

    The value of num is: undefined
    

    JavaScript Variable Scope

    The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

    • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
    • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

    Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.

    Example

    In the example below, we have defined the variable named myVar outside the function and initialized it with the 'global' value. Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the 'local' value.

    We print the myVar variable's value inside the function. So, the local variable takes preference over the global variable and prints the 'local' in the output.

    <html><head><title> JavaScript Variable Scope Example</title></head><body onload =checkscope();><script>var myVar ="global";// Declare a global variablefunctioncheckscope(){var myVar ="local";// Declare a local variable
    		 document.write(myVar);}</script></body></html>

    This produces the following result −

    local
    

    Example

    In the example below, we have defined the variables without using the var keyword. The name variable contains the value of the string type, and the number variable contains the value of the float data type.

    When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere inside the code.

    <html><head><title> Variables without var keyword </title></head><body><script>
    
      name ="tutorialspoint";// String type variable
      number =10.25;// Number type variable
      document.write("name = "+ name +", number = "+ number +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    This produces the following result −

    name = tutorialspoint, number = 10.25
    

    Also, the identifier doesn't lose the previous value if we declare the variable using the var keyword with the value and re-declare the same identifier without initialization. Lets understand it via the example below.

    Example

    In the example below, we have declared the age variable and initialized it with 10. Again, we have declared the age variable but havent initialized it.

    Still, it prints 10 in the output because it doesnt lose the previous initializations value. However, if we update the value of the age variable, it successfully updates it.

    <html><head><title> Variables withvar keyword </title></head><body><script>var age =10;var age;
    
      document.write("age = "+ age +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    This produces the following result −

    age = 10
    

  • Comments

    JavaScript Comments

    JavaScript comments are used to explain the purpose of the code. The comments are not executed as a part of program and these are solely meant for human developers to understand the code better.

    You can use comments for various purposes, such as −

    • Explaining the purpose of a particular piece of code.
    • Adding documentation to your code for yourself and others who may read it.
    • Temporarily disabling or “commenting out” a block of code for testing or debugging without deleting it.

    A good developer always writes a comment to explain the code.

    Types of Comments in JavaScript

    There are two common ways to write comments in JavaScript −

    • Single-line comments
    • Multi-line comments

    Single-line comments in JavaScript

    We can start the single-line comment with the double forward slash (//). We can write comment between // and end of the line.

    Syntax

    The syntax for the single-line comments is given below −

    <script>// single-line comment message</script>

    Example

    In the example below, we have explained each step of JavaScript code using single-line comments. In the output, the code prints the concatenated string.

    <html><head><title> Single line comments </title></head><body><script>// Defining the string1var string1 ="JavaScript";// Defining the string2var string2 ="TypeScript";// Printing the strings
    
    document.write(string1," ", string2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Multi-line comments in JavaScript

    The multi-line comment is useful when we require to comment the multiple lines of code or explain the larger codes. We can write multi-line comments between the /* and */.

    Syntax

    The syntax for the multi-line comments is given below −

    <script>/* First line of comment message
       The second line of the comment message */</script>

    Example

    In the example below, we have defined a function and explained it using the multi-line comments −

    <html><head><title> Multi line comments </title></head><body><script>let result =addition(1123,8823);
    
    document.write("Result = "+ result);/* This function accepts two values as parameters,
     adds them and returns the result*/functionaddition(a, b){var a =100;var b =200;return a+b;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Always write comments in your code as it helps other collaborators to understand your code.

    Using Comments to Prevent Execution

    In addition to use comments to provide information about the code, we can also use them to prevent the execution of a particular piece of code.

    Example

    In the example below, we have commented the 'bool1 = false;' line to avoid execution of that code. In the output, we can see that value of the bool1 variable is true, as we commented out the code, which updates the bool1 variables value.

    Also, we can add the single line code after writing the code, as we added after the document.write() method.

    <html><head><title> Single line comments </title></head><body><script>var bool1 =true;// bool1 = false;
    
    document.write("The value of the bool1 is: ", bool1);// print variable value&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In the example below, we have defined 'a' and 'b' variables. After that, we have written the code to swap values of 'a' and 'b' in 3 lines and comment out using the multi-line comments.

    The output prints the actual values of the 'a' and 'b' as the browser ignores the commented code.

    <html><head><title> Multi line comments </title></head><body><script>var a =100;var b =200;/* a = a + b;
    
    b = a - b;
    a = a - b; */
    document.write("a = "+ a +"&lt;br&gt;"+"b = "+ b);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Console.log() Method

    JavaScript console.log() Method

    The console.log() is one of the most important methods in JavaScript. It is used to print the message in the web console.

    We can use the console.log() method to debug the code by printing the output in the console. For example, if the developer requests API and wants to check the data received as a response, they might use the console.log() method. Also, there are other use cases of the console.log() method.

    Syntax

    You can follow the syntax below to use the console.log() method −

    console.log(msg1, msg2,, msgN);

    You can pass different messages (msg1, msg2, …,msgN) by separating them with a comma as a parameter of the console.log() method.

    Console.log() with client-sided JavaScript

    Whenever we use the console.log() method in the front-end code, it prints the output in the browser’s console.

    Here is shortcut to open the console in Chrome browser −

    • Press Ctrl + Shift + J together on Windows/Linux and Cmd + Option + J on Mac.

    Most browsers have the same shortcut key to open the console. However, if you cant open the console in any browser, you may search on Google.

    Alternatively, to open the Console, right click the mouse and follow Inspect -> Console options.

    Example

    In the example below, we have printed the “Hello World!” message using the console.log() method.

    Also, we defined two integer variables and used another console.log() method to print the sum of num1 and num2. Here, developers can observe how we have printed variables in the console. The example also demonstrates that we can perform addition, multiplication, etc. operations in the console.log() method parameter.

    <html><head><title> Console.log() method withHTML</title></head><body><h3> Message is printed in the console </h3><p> Please open the console before clicking "Edit & Run" button </p><script>
    
      console.log("Hello World!");var num1 =30;var num2 =20;
      console.log("The sum of ", num1," and ", num2," is: ", num1 + num2);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result in the Console −

    Hello World!
    The sum of  30  and  20  is:  50
    

    Example

    In the example below, we have created the JavaScript object containing the name, domain, and description properties. We have printed the object in the web console using the console.log() method.

    In the console, we can see that it prints the object, and we can expand the object by clicking the arrow given at the start of the object to see the detailed information.

    <html><head><title> Console.log() method withHTML</title></head><body><h3> Message is printed in the console </h3><p> Please open the console before clicking "Edit & Run" button </p><script>// Defining the objectvar obj ={
    
         website:"Tutorialspoint",
    Domain:"www.tutorialspoint.com", description:"This site is for learning."};
      console.log(obj);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result in the Console −

    {website: 'Tutorialspoint', Domain: 'www.tutorialspoint.com', description: 'This site is for learning.'}
    

    Console.log() with server-side JavaScript

    The console.log() method with the back-end code prints the output in the terminal where the back-end server is running.

    Example

    We have written the below code printing the Hello World! message into the app.js file and using the 'node app.js' command in the terminal to run the server. It prints the message in the terminal that we can observe.

    let message ="Hello world!";
    console.log(message);

    This will produce the following result −

    Hello world!
    

    You can use the console.log() method with front-end and back-end code to debug the code by printing output in the console.

  • Hello World Program

    Write “Hello World” Program in JavaScript

    “Hello, World!” is often the first program, programmers write when learning a new programming language. JavaScript “Hello World” is a simple program, generally used to demonstrate the basic syntax of the language. This program will make use of different JavaScript methods to print “Hello World”.

    Using document.write()

    In JavaScript, the simplest way to print “Hello World” is to use document.write() method. The document.write() method writes the content (a string of text) directly to the HTML document or web page. Lets look at the following −

    <script>
       document.write("Hello World)</script>

    We should write the document.write() within the <script> and </script> tags. We can place the <script> inside the <head> or <body> section.

    Example

    Let’s try to write a JavaScript program that prints the “Hello World!” to the document or web page. In the below program, we placed the JavaScript code within the <head> section. You can try to put the JavaScript part inside the <body> section and execute the program.

    <html><head><script>
    
      document.write("Hello World");&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;html&gt;</pre>

    Using alert() method

    We can use the window alert() method to print "Hello Word" in a dialogue box.

    The alert() is a window method that instruct the browser to display an alert box with the message. We can write alert without passing any message to it.

    <script>alert("Hello World")</script>

    We can write alert() method as window.alert(). As window object is a global scope object, we can skip the "window" keyword.

    Example

    Let's try an example showing "Hello World" in the alert box. Try to execute the program by putting the <script> part within the <body> section.

    <html><head><script>alert("Hello World");</script></head><body></body><html>

    Using console.log()

    The console.log() is a very convenient method to print the message to web Console. It is very useful to debug the JavaScript codes in the browsers. Let's look at the simple application of the console.log() to print the "Hello World" to the web console.

    <script>
       Console.log("Hello World")</script>

    We can use the console.log to print strings or JavaScript objects. Here in above code snippet, we have passed "Hello World" as a string argument to the console.log() method.

    Example

    Let's try to write a complete JavaScript program with HTML.

    <html><head><script>
    
      console.log("Hello World");&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt; Please open the console before clicking "Edit &amp; Run" button &lt;/p&gt;&lt;/body&gt;&lt;html&gt;</pre>

    It will produce the following message in the web console −

    Hello World
    

    Using innerHTML

    The innerHTML property of an HTML element defines the HTML content of the element. We can use this property to display the Hello World message. By changing the innerHTML property of the element, we can display the message in HTML document or webpage.

    To use innerHTML property of an element, we need to access that element first. We can use document.getElementById() method to access the element. Let's look at a complete example.

    Example

    In the example below, we define a div element with id, "output". We access this element using the document.getElementById("output"). Then we change the innerHTML property and display our message, "Hello World".

    <html><head><title>Using innerHTML property</title></head><body><div id ="output"></div><script>
    
      document.getElementById("output").innerHTML ="Hello World";&lt;/script&gt;&lt;/body&gt;&lt;html&gt;</pre>