Blog

  • Data Layout

    COBOL layout is the description of use of each field and the values present in it. Following are the data description entries used in COBOL −

    • Redefines Clause
    • Renames Clause
    • Usage Clause
    • Copybooks

    Redefines Clause

    Redefines clause is used to define a storage with different data description. If one or more data items are not used simultaneously, then the same storage can be utilized for another data item. So the same storage can be referred with different data items.

    Syntax

    Following is the syntax for Redefines clause −

    01 WS-OLD PIC X(10).
    01 WS-NEW1 REDEFINES WS-OLD PIC 9(8).
    01 WS-NEW2 REDEFINES WS-OLD PIC A(10).
    

    Following are the details of the used parameters −

    • WS-OLD is Redefined Item
    • WS-NEW1 and WS-NEW2 are Redefining Item

    Level numbers of redefined item and redefining item must be the same and it cannot be 66 or 88 level number. Do not use VALUE clause with a redefining item. In File Section, do not use a redefines clause with 01 level number. Redefines definition must be the next data description you want to redefine. A redefining item will always have the same value as a redefined item.

    ExampleLive Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-DESCRIPTION.
       05 WS-DATE1 VALUE '20140831'.
       10 WS-YEAR PIC X(4).
       10 WS-MONTH PIC X(2).
       10 WS-DATE PIC X(2).
       05 WS-DATE2 REDEFINES WS-DATE1 PIC 9(8).
    
    PROCEDURE DIVISION.
       DISPLAY "WS-DATE1 : "WS-DATE1.
       DISPLAY "WS-DATE2 : "WS-DATE2.
    
    STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program it produces the following result −

    WS-DATE1 : 20140831
    WS-DATE2 : 20140831
    

    Renames Clause

    Renames clause is used to give different names to existing data items. It is used to re-group the data names and give a new name to them. The new data names can rename across groups or elementary items. Level number 66 is reserved for renames.

    Syntax

    Following is the syntax for Renames clause −

    01 WS-OLD.
    10 WS-A PIC 9(12).
    10 WS-B PIC X(20).
    10 WS-C PIC A(25).
    10 WS-D PIC X(12).
    66 WS-NEW RENAMES WS-A THRU WS-C.
    

    Renaming is possible at same level only. In the above example, WS-A, WS-B, and WS-C are at the same level. Renames definition must be the next data description you want to rename. Do not use Renames with the level numbers 01 or, 77. The data names used for renames must come in sequence. Data items with occur clause cannot be renamed.

    Example

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-DESCRIPTION.
       05 WS-NUM.
       10 WS-NUM1 PIC 9(2) VALUE 20.
       10 WS-NUM2 PIC 9(2) VALUE 56.
       05 WS-CHAR.
       10 WS-CHAR1 PIC X(2) VALUE 'AA'.
       10 WS-CHAR2 PIC X(2) VALUE 'BB'.
       66 WS-RENAME RENAMES WS-NUM2 THRU WS-CHAR2.
    
    PROCEDURE DIVISION.
       DISPLAY "WS-RENAME : " WS-RENAME.
       
    STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    WS-RENAME : 56AABB
    

    Usage Clause

    Usage clause specifies the operating system in which the format data is stored. It cannot be used with level numbers 66 or 88. If usage clause is specified on a group, then all the elementary items will have the same usage clause. The different options available with Usage clause are as follows −

    Display

    Data item is stored in ASCII format and each character will take 1 byte. It is default usage.

    The following example calculates the number of bytes required −

    01 WS-NUM PIC S9(5)V9(3) USAGE IS DISPLAY.
    It requires 8 bytes as sign and decimal doesn't require any byte.
    
    01 WS-NUM PIC 9(5) USAGE IS DISPLAY.
    It requires 5 bytes as sign.

    COMPUTATIONAL / COMP

    Data item is stored in binary format. Here, data items must be integer.

    The following example calculates the number of bytes required −

    01 WS-NUM PIC S9(n) USAGE IS COMP.
    
    If 'n' = 1 to 4, it takes 2 bytes.
    If 'n' = 5 to 9, it takes 4 bytes.
    If 'n' = 10 to 18, it takes 8 bytes.

    COMP-1

    Data item is similar to Real or Float and is represented as a single precision floating point number. Internally, data is stored in hexadecimal format. COMP-1 does not accept PIC clause. Here 1 word is equal to 4 bytes.

    COMP-2

    Data item is similar to Long or Double and is represented as double precision floating point number. Internally, data is stored in hexadecimal format. COMP-2 does not specify PIC clause. Here 2 word is equal to 8 bytes.

    COMP-3

    Data item is stored in packed decimal format. Each digit occupies half a byte (1 nibble) and the sign is stored at the rightmost nibble.

    The following example calculates the number of bytes required −

    01 WS-NUM PIC 9(n) USAGE IS COMP.
    Number of bytes = n/2 (If n is even)
    Number of bytes = n/2 + 1(If n is odd, consider only integer part)
    
    01 WS-NUM PIC 9(4) USAGE IS COMP-3 VALUE 21.
    It requires 2 bytes of storage as each digit occupies half a byte.
    
    01 WS-NUM PIC 9(5) USAGE IS COMP-3 VALUE 21.
    It requires 3 bytes of storage as each digit occupies half a byte.

    AD

    https://delivery.adrecover.com/recover.html?siteId=18107&dataDogLoggingEnabled=false&dataDogLoggingVersion=1

    Copybooks

    A COBOL copybook is a selection of code that defines data structures. If a particular data structure is used in many programs, then instead of writing the same data structure again, we can use copybooks. We use the COPY statement to include a copybook in a program. COPY statement is used in the WorkingStorage Section.

    The following example includes a copybook inside a COBOL program −

    DATA DIVISION.
    WORKING-STORAGE SECTION.
    COPY ABC.

    Here ABC is the copybook name. The following data items in ABC copybook can be used inside a program.

    01 WS-DESCRIPTION.
       05 WS-NUM.
    
      10 WS-NUM1 PIC 9(2) VALUE 20.
      10 WS-NUM2 PIC 9(2) VALUE 56.
    05 WS-CHAR.
      10 WS-CHAR1 PIC X(2) VALUE 'AA'.
      10 WS-CHAR2 PIC X(2) VALUE 'BB'.</code></pre>
  • Data Types

    Data Division is used to define the variables used in a program. To describe data in COBOL, one must understand the following terms −

    • Data Name
    • Level Number
    • Picture Clause
    • Value Clause
    01            TOTAL-STUDENTS            PIC9(5)            VALUE '125'.
    |                    |                    |                    |
    |                    |                    |                    |
    |                    |                    |                    | 
    Level Number     Data Name           Picture Clause       Value Clause
    

    Data Name

    Data names must be defined in the Data Division before using them in the Procedure Division. They must have a user-defined name; reserved words cannot be used. Data names give reference to the memory locations where actual data is stored. They can be elementary or group type.

    Example

    The following example shows valid and invalid data names −

    Valid:
       WS-NAME
       TOTAL-STUDENTS
       A100
       100B
    
    Invalid:
       MOVE            (Reserved Words)
       COMPUTE         (Reserved Words)
       100             (No Alphabet)
       100+B           (+ is not allowed) 

    Level Number

    Level number is used to specify the level of data in a record. They are used to differentiate between elementary items and group items. Elementary items can be grouped together to create group items.

    Sr.No.Level Number & Description
    101Record description entry
    202 to 49Group and Elementary items
    366Rename Clause items
    477Items which cannot be sub-divided
    588Condition name entry
    • Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item.
    • Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01.

    Example

    The following example shows Group and Elementary items −

    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 WS-NAME    PIC X(25).                               ---> ELEMENTARY ITEM 
    01 WS-CLASS   PIC 9(2)  VALUE  '10'.                   ---> ELEMENTARY ITEM
    
    01 WS-ADDRESS.                                         ---> GROUP ITEM   
       05 WS-HOUSE-NUMBER    PIC 9(3).                     ---> ELEMENTARY ITEM
       05 WS-STREET          PIC X(15).                    ---> ELEMENTARY ITEM
       05 WS-CITY            PIC X(15).                    ---> ELEMENTARY ITEM
       05 WS-COUNTRY         PIC X(15)  VALUE 'INDIA'.     ---> ELEMENTARY ITEM

    Picture Clause

    Picture clause is used to define the following items −

    • Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters.
    • Sign can be used with numeric data. It can be either + or –.
    • Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data.
    • Length defines the number of bytes used by the data item.

    Symbols used in a Picture clause −

    Sr.No.Symbol & Description
    19Numeric
    2AAlphabetic
    3XAlphanumeric
    4VImplicit Decimal
    5SSign
    6PAssumed Decimal

    Example

    The following example shows the use of PIC clause −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-NUM1 PIC S9(3)V9(2).
       01 WS-NUM2 PIC PPP999.
       01 WS-NUM3 PIC S9(3)V9(2) VALUE -123.45.
       01 WS-NAME PIC A(6) VALUE 'ABCDEF'.
       01 WS-ID PIC X(5) VALUE 'A121$'.
    
    PROCEDURE DIVISION.
       DISPLAY "WS-NUM1 : "WS-NUM1.
       DISPLAY "WS-NUM2 : "WS-NUM2.
       DISPLAY "WS-NUM3 : "WS-NUM3.
       DISPLAY "WS-NAME : "WS-NAME.
       DISPLAY "WS-ID : "WS-ID.
    STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    WS-NUM1 : +000.00
    WS-NUM2 : .000000
    WS-NUM3 : -123.45
    WS-NAME : ABCDEF
    WS-ID : A121$
    

    Value Clause

    Value clause is an optional clause which is used to initialize the data items. The values can be numeric literal, alphanumeric literal, or figurative constant. It can be used with both group and elementary items.

    Example

    The following example shows the use of VALUE clause −

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-NUM1 PIC 99V9 VALUE IS 3.5.
       01 WS-NAME PIC A(6) VALUE 'ABCD'.
       01 WS-ID PIC 99 VALUE ZERO.
    
    PROCEDURE DIVISION.
       DISPLAY "WS-NUM1 : "WS-NUM1.
       DISPLAY "WS-NAME : "WS-NAME.
       DISPLAY "WS-ID   : "WS-ID.
    STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    WS-NUM1 : 03.5
    WS-NAME : ABCD
    WS-ID   : 00
    
  • Basic Syntax

    Character Set

    ‘Characters’ are lowest in the hierarchy and they cannot be divided further. The COBOL Character Set includes 78 characters which are shown below −

    Sr.No.Character & Description
    1A-ZAlphabets(Upper Case)
    2a-zAlphabets (Lower Case)
    30-9Numeric
    4 Space
    5+Plus Sign
    6Minus Sign or Hyphen
    7*Asterisk
    8/Forward Slash
    9$Currency Sign
    10,Comma
    11;Semicolon
    12.Decimal Point or Period
    13Quotation Marks
    14(Left Parenthesis
    15)Right Parenthesis
    16>Greater than
    17<Less than
    18:Colon
    19Apostrophe
    20=Equal Sign

    Coding Sheet

    The source program of COBOL must be written in a format acceptable to the compilers. COBOL programs are written on COBOL coding sheets. There are 80 character positions on each line of a coding sheet.

    Character positions are grouped into the following five fields −

    PositionsFieldDescription
    1-6Column NumbersReserved for line numbers.
    7IndicatorIt can have Asterisk (*) indicating comments, Hyphen (-) indicating continuation and Slash ( / ) indicating form feed.
    8-11Area AAll COBOL divisions, sections, paragraphs and some special entries must begin in Area A.
    12-72Area BAll COBOL statements must begin in area B.
    73-80Identification AreaIt can be used as needed by the programmer.

    Example

    The following example shows a COBOL coding sheet −

    000100 IDENTIFICATION DIVISION.                                         000100
    000200 PROGRAM-ID. HELLO.                                               000101
    000250* THIS IS A COMMENT LINE                                          000102
    000300 PROCEDURE DIVISION.                                              000103
    000350 A000-FIRST-PARA.                                                 000104
    000400     DISPLAY “Coding Sheet”.                                      000105
    000500 STOP RUN.                                                        000106

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    Coding Sheet
    

    Character Strings

    Character strings are formed by combining individual characters. A character string can be a

    • Comment,
    • Literal, or
    • COBOL word.

    All character strings must be ended with separators. A separator is used to separate character strings.

    Frequently used separators − Space, Comma, Period, Apostrophe, Left/Right Parenthesis, and Quotation mark.

    Comment

    A comment is a character string that does not affect the execution of a program. It can be any combination of characters.

    There are two types of comments −

    Comment Line

    A comment line can be written in any column. The compiler does not check a comment line for syntax and treats it for documentation.

    Comment Entry

    Comment entries are those that are included in the optional paragraphs of an Identification Division. They are written in Area B and programmers use it for reference.

    The text highlighted in Bold are the commented entries in the following example −

    000100 IDENTIFICATION DIVISION.                                         000100
    000150 PROGRAM-ID. HELLO.                                               000101 
    000200 AUTHOR. TUTORIALSPOINT.                                          000102
    000250* THIS IS A COMMENT LINE                                          000103
    000300 PROCEDURE DIVISION.                                              000104
    000350 A000-FIRST-PARA.                                                 000105  
    000360/ First Para Begins - Documentation Purpose                       000106
    000400     DISPLAY “Comment line”.                                      000107
    000500 STOP RUN.                                                        000108

    JCL to execute above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    Comment Line
    

    Literal

    Literal is a constant that is directly hard-coded in a program. In the following example, “Hello World” is a literal.

    PROCEDURE DIVISION.
    DISPLAY 'Hello World'.

    There are two types of literals as discussed below −

    Alphanumeric Literal

    Alphanumeric Literals are enclosed in quotes or apostrophe. Length can be up to 160 characters. An apostrophe or a quote can be a part of a literal only if it is paired. Starting and ending of the literal should be same, either apostrophe or quote.

    Example

    The following example shows valid and invalid Alphanumeric Literals −

    Valid:
       ‘This is valid’
       "This is valid"
       ‘This isn’’t invalid’
    
    Invalid:
       ‘This is invalid”
       ‘This isn’t valid’

    Numeric Literal

    A Numeric Literal is a combination of digits from 0 to 9, +, –, or decimal point. Length can be up to 18 characters. Sign cannot be the rightmost character. Decimal point should not appear at the end.

    Example

    The following example shows valid and invalid Numeric Literals −

    Valid:
       100
       +10.9
       -1.9
    
    Invalid:
       1,00
       10.
       10.9-

    COBOL Word

    COBOL Word is a character string that can be a reserved word or a user-defined word. Length can be up to 30 characters.

    User-Defined

    User-defined words are used for naming files, data, records, paragraph names, and sections. Alphabets, digits, and hyphens are allowed while forming userdefined words. You cannot use COBOL reserved words.

    Reserved Words

    Reserved words are predefined words in COBOL. Different types of reserved words that we use frequently are as follows −

    • Keywords like ADD, ACCEPT, MOVE, etc.
    • Special characters words like +, -, *, <, <=, etc
    • Figurative constants are constant values like ZERO, SPACES, etc. All the constant values of figurative constants are mentioned in the following table.

    Figurative Constants

    Sr.No.Figurative Constants & Description
    1HIGH-VALUESOne or more characters which will be at the highest position in descending order.
    2LOW-VALUESOne or more characters have zeros in binary representation.
    3ZERO/ZEROESOne or more zero depending on the size of the variable.
    4SPACESOne or more spaces.
    5QUOTESSingle or double quotes.
    6ALL literalFills the data-item with Literal.
  • Program Structure

    A COBOL program structure consists of divisions as shown in the following image −

    Program Structure

    A brief introduction of these divisions is given below −

    • Sections are the logical subdivision of program logic. A section is a collection of paragraphs.
    • Paragraphs are the subdivision of a section or division. It is either a user-defined or a predefined name followed by a period, and consists of zero or more sentences/entries.
    • Sentences are the combination of one or more statements. Sentences appear only in the Procedure division. A sentence must end with a period.
    • Statements are meaningful COBOL statements that perform some processing.
    • Characters are the lowest in the hierarchy and cannot be divisible.

    You can co-relate the above-mentioned terms with the COBOL program in the following example −

    PROCEDURE DIVISION.
    A0000-FIRST-PARA SECTION.
    FIRST-PARAGRAPH.
    ACCEPT WS-ID            - Statement-1  -----|
    MOVE '10' TO WS-ID      - Statement-2       |-- Sentence - 1
    DISPLAY WS-ID           - Statement-3  -----|
    .

    Divisions

    A COBOL program consists of four divisions.

    Identification Division

    It is the first and only mandatory division of every COBOL program. The programmer and the compiler use this division to identify the program. In this division, PROGRAM-ID is the only mandatory paragraph. PROGRAM-ID specifies the program name that can consist 1 to 30 characters.

    Try the following example using the Live Demo option online.Live Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    PROCEDURE DIVISION.
    DISPLAY 'Welcome to Tutorialspoint'.
    STOP RUN.

    Given below is the JCL to execute the above COBOL program.

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    Welcome to Tutorialspoint
    

    Environment Division

    Environment division is used to specify input and output files to the program. It consists of two sections −

    • Configuration section provides information about the system on which the program is written and executed. It consists of two paragraphs −
      • Source computer − System used to compile the program.
      • Object computer − System used to execute the program.
    • Input-Output section provides information about the files to be used in the program. It consists of two paragraphs −
      • File control − Provides information of external data sets used in the program.
      • I-O control − Provides information of files used in the program.
    ENVIRONMENT DIVISION.
    CONFIGURATION SECTION.
       SOURCE-COMPUTER. XXX-ZOS.
       OBJECT-COMPUTER. XXX-ZOS.
    
    INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT FILEN ASSIGN TO DDNAME
       ORGANIZATION IS SEQUENTIAL.

    Data Division

    Data division is used to define the variables used in the program. It consists of four sections −

    • File section is used to define the record structure of the file.
    • Working-Storage section is used to declare temporary variables and file structures which are used in the program.
    • Local-Storage section is similar to Working-Storage section. The only difference is that the variables will be allocated and initialized every time a program starts execution.
    • Linkage section is used to describe the data names that are received from an external program.

    COBOL Program

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT FILEN ASSIGN TO INPUT.
    
      ORGANIZATION IS SEQUENTIAL.
      ACCESS IS SEQUENTIAL.
    DATA DIVISION. FILE SECTION. FD FILEN 01 NAME PIC A(25). WORKING-STORAGE SECTION. 01 WS-STUDENT PIC A(30). 01 WS-ID PIC 9(5). LOCAL-STORAGE SECTION. 01 LS-CLASS PIC 9(3). LINKAGE SECTION. 01 LS-ID PIC 9(5). PROCEDURE DIVISION. DISPLAY 'Executing COBOL program using JCL'. STOP RUN.

    The JCL to execute the above COBOL program is as follows −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO
    //INPUT DD DSN = ABC.EFG.XYZ,DISP = SHR

    When you compile and execute the above program, it produces the following result −

    Executing COBOL program using JCL
    

    Procedure Division

    Procedure division is used to include the logic of the program. It consists of executable statements using variables defined in the data division. In this division, paragraph and section names are user-defined.

    There must be at least one statement in the procedure division. The last statement to end the execution in this division is either STOP RUN which is used in the calling programs or EXIT PROGRAM which is used in the called programs.Live Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-NAME PIC A(30).
       01 WS-ID PIC 9(5) VALUE 12345.
    
    PROCEDURE DIVISION.
       A000-FIRST-PARA.
       DISPLAY 'Hello World'.
       MOVE 'TutorialsPoint' TO WS-NAME.
       DISPLAY "My name is : "WS-NAME.
       DISPLAY "My ID is : "WS-ID.
    STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    Hello World
    My name is : TutorialsPoint
    My ID is : 12345
    
  • Environment Setup

    Installing COBOL on Windows/Linux

    There are many Free Mainframe Emulators available for Windows which can be used to write and learn simple COBOL programs.

    One such emulator is Hercules, which can be easily installed on Windows by following a few simple steps as given below −

    • Download and install the Hercules emulator, which is available from the Hercules’ home site: www.hercules-390.eu
    • Once you have installed the package on Windows machine, it will create a folder like C:/hercules/mvs/cobol.
    • Run the Command Prompt (CMD) and reach the directory C:/hercules/mvs/cobol on CMD.
    • The complete guide on various commands to write and execute a JCL and COBOL programs can be found at:www.jaymoseley.com/hercules/installmvs/instmvs2.htm

    Hercules is an open-source software implementation of the mainframe System/370 and ESA/390 architectures, in addition to the latest 64-bit z/Architecture. Hercules runs under Linux, Windows, Solaris, FreeBSD, and Mac OS X.

    A user can connect to a mainframe server in a number of ways such as thin client, dummy terminal, Virtual Client System (VCS), or Virtual Desktop System (VDS). Every valid user is given a login id to enter into the Z/OS interface (TSO/E or ISPF).

    Compiling COBOL Programs

    In order to execute a COBOL program in batch mode using JCL, the program needs to be compiled, and a load module is created with all the sub-programs. The JCL uses the load module and not the actual program at the time of execution. The load libraries are concatenated and given to the JCL at the time of execution using JCLLIB or STEPLIB.

    There are many mainframe compiler utilities available to compile a COBOL program. Some corporate companies use Change Management tools like Endevor, which compiles and stores every version of the program. This is useful in tracking the changes made to the program.

    //COMPILE   JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID             
    //*            
    //STEP1     EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE
    //SYSIN     DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR
    //SYSLIB    DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR
    //SYSLMOD   DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR
    //SYSPRINT  DD SYSOUT=*
    //*

    IGYCRCTL is an IBM COBOL compiler utility. The compiler options are passed using the PARM parameter. In the above example, RMODE instructs the compiler to use relative addressing mode in the program. The COBOL program is passed using the SYSIN parameter. Copybook is the library used by the program in SYSLIB.

    Executing COBOL Programs

    Given below is a JCL example where the program MYPROG is executed using the input file MYDATA.URMI.INPUT and produces two output files written to the spool.

    //COBBSTEP  JOB CLASS=6,NOTIFY=&SYSUID
    //
    //STEP10    EXEC PGM=MYPROG,PARM=ACCT5000
    //STEPLIB   DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR
    //INPUT1    DD DSN=MYDATA.URMI.INPUT,DISP=SHR
    //OUT1      DD SYSOUT=*
    //OUT2      DD SYSOUT=*
    //SYSIN     DD *
    //CUST1     1000
    //CUST2     1001
    /*

    The load module of MYPROG is located in MYDATA.URMI.LOADLIB. This is important to note that the above JCL can be used for a non-DB2 COBOL module only.

    Executing COBOL-DB2 programs

    For running a COBOL-DB2 program, a specialized IBM utility is used in the JCL and the program; DB2 region and required parameters are passed as input to the utility.

    The steps followed in running a COBOL-DB2 program are as follows −

    • When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct.
    • The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL.
    • After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and the DBRM library as the input to the JCL.
    //STEP001  EXEC PGM=IKJEFT01
    //*
    //STEPLIB  DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR
    //*
    //input files
    //output files
    //SYSPRINT DD SYSOUT=*
    //SYSABOUT DD SYSOUT=*
    //SYSDBOUT DD SYSOUT=*
    //SYSUDUMP DD SYSOUT=*
    //DISPLAY  DD SYSOUT=*
    //SYSOUT   DD SYSOUT=*
    //SYSTSPRT DD SYSOUT=*
    //SYSTSIN  DD *
       DSN SYSTEM(SSID)
       RUN PROGRAM(MYCOBB) PLAN(PLANNAME) PARM(parameters to cobol program) -
       LIB('MYDATA.URMI.LOADLIB')
       END
    /*

    In the above example, MYCOBB is the COBOL-DB2 program run using IKJEFT01. Please note that the program name, DB2 Sub-System Id (SSID), and DB2 Plan name are passed within the SYSTSIN DD statement. The DBRM library is specified in the STEPLIB.

  • Overview

    Introduction to COBOL

    COBOL is a high-level language. One must understand the way COBOL works. Computers only understand machine code, a binary stream of 0s and 1s. COBOL code must be converted into machine code using a compiler. Run the program source through a compiler. The compiler first checks for any syntax errors and then converts it into machine language. The compiler creates an output file which is known as load module. This output file contains executable code in the form of 0s and 1s.

    Evolution of COBOL

    During 1950s, when the businesses were growing in the western part of the world, there was a need to automate various processes for ease of operation and this gave birth to a high-level programming language meant for business data processing.

    • In 1959, COBOL was developed by CODASYL (Conference on Data Systems Language).
    • The next version, COBOL-61, was released in 1961 with some revisions.
    • In 1968, COBOL was approved by ANSI as a standard language for commercial use (COBOL-68).
    • It was again revised in 1974 and 1985 to develop subsequent versions named COBOL-74 and COBOL-85 respectively.
    • In 2002, Object-Oriented COBOL was released, which could use encapsulated objects as a normal part of COBOL programming.

    Importance of COBOL

    • COBOL was the first widely used high-level programming language. It is an English-like language which is user friendly. All the instructions can be coded in simple English words.
    • COBOL is also used as a self-documenting language.
    • COBOL can handle huge data processing.
    • COBOL is compatible with its previous versions.
    • COBOL has effective error messages and so, resolution of bugs is easier.

    Features of COBOL

    Standard Language

    COBOL is a standard language that can be compiled and executed on machines such as IBM AS/400, personal computers, etc.

    Business Oriented

    COBOL was designed for business-oriented applications related to financial domain, defense domain, etc. It can handle huge volumes of data because of its advanced file handling capabilities.

    Robust Language

    COBOL is a robust language as its numerous debugging and testing tools are available for almost all computer platforms.

    Structured Language

    Logical control structures are available in COBOL which makes it easier to read and modify. COBOL has different divisions, so it is easy to debug.

  • 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;</code></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;</code></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;</code></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;</code></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"1rtue
    "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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></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;</code></pre>
  • Constants

    JavaScript Constants

    JavaScript constants are the variables whose values remain unchanged throughout the execution of the program. You can declare constants using the 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 redeclaredreassigned. 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 blcok.

    In the below example, the x declared within block is different from x declared outside the blcok. So we can redeclare the same variable outsite the block

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

    But we can’t redeclare the const varaible 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> Consant Arrays </title></head><body><script>// Defining the constant arrayconst arr =["door","window","roof","wall"];// Updating arr[0]
    
      arr&#91;0]="gate";// Inserting an element to the array
      arr.push("fence");//arr = &#91;"table", "chair"] // reassiging array will cause error.// Printing the array
      document.write(arr);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></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;</code></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

    Varaibles 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 redeclared 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
    RedeclareYesNoNo
    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.
    • Redeclaring variables is not a good practice. So, you should avoid it, but if necessary, you may use the var keyword.