Skillzam

JavaScript Language

HTML5 Home

  • JavaScript is the most popular programming language.
  • JavaScript is one of the top three core technologies of world wide web (www). The other two are HTML & CSS.
  • As of 2022, 98% of websites use JavaScript on the client side for webpage behavior. (as per w3techs)
  • JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods.
  • Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:
    1.  (a) Client-side JavaScript extends the core language by supplying objects to control a browser & its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
    2.  (b) Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.

    What is JavaScript ?

    JavaScript (JS) is a lightweight, interpreted, just-in-time compiled, high-level, prototype-based, dynamic typed, object-oriented programming language, with first-class functions.


    TERMINOLOGIES EXPLAINED

  • Programming Language :
    1.  (a) A programming language is any set of rules that converts strings, or graphical program elements in the case of visual programming languages, to various kinds of machine code output.
    2.  (b) Programming languages are one kind of computer language, and are used in computer programming to implement algorithms.
  • Lightweight Programming Language :
    1.  (a) These are designed to have small memory footprint, are easy to implement (important when porting a language to different computer systems)
    2.  (b) They have simple syntax and semantics, so one can learn them quickly and easily.
    3.  (c) Some lightweight languages : for Example - JavaScript, BASIC, Lisp, Forth, and Tcl
  • Interpreted Programming Language :
    1.  (a) It is a programming language which are generally interpreted, without compiling a program into machine instructions.
    2.  (b) It is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program.
    3.  (c) Interpreted language examples - JavaScript, Perl, Python, BASIC, etc.
  • just-in-time (JIT) compilation Language :
    1.  (a) just-in-time (JIT) compilation (also dynamic translation or run-time compilations) is a way of executing computer code that involves compilation during execution of a program (at run time) rather than before execution.
    2.  (b) This may consist of source code translation but is more commonly bytecode translation to machine code, which is then executed directly.
  • High-level Programming language :
    1.  (a) It refers to the higher level of abstraction from machine language.
    2.  (b) Rather than dealing with registers, memory addresses, and call stacks, high-level languages deal with variables, arrays and functions, loops and other abstract computer science concepts, with a focus on usability over optimal program efficiency.
    3.  (c) Examples: Python, JavaScript, PHP, Java, C#, Perl etc
  • Dynamic typed - programming Language :
    1.  (a) Are those where the interpreter assigns variables a type at runtime based on the variable's value at the time.
    2.  (b) Most dynamic languages are also dynamically typed, but not all are. Dynamic languages are frequently referred to as scripting languages.
    3.  (c) Popular dynamic programming languages include JavaScript, Python, Ruby, PHP, Lua and Perl.
  • Object-Oriented Programming (OOP) :
    1.  (a) OOP (Object-Oriented Programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts.
    2.  (b) JavaScript is heavily object-oriented. It follows a prototype-based model, but it also offers a class syntax to enable typical OOP paradigms.
  • Prototype-based programming :
    1.  (a) Prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object.
    2.  (b) In simple words: this type of style allows the creation of an object without first defining its class.
  • First-class Function language :
    1.  (a) A programming language is said to have First-class functions when functions in that language are treated like any other variable.
    2.  (b) For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
  • Things that JavaScript can do:

  • Making the websites interactive
    1.  (a) Show or hide more information by click of a button
    2.  (b) Change color of a button when mouse hovers
    3.  (c) Slide through a carousel of images on homepage
    4.  (d) Zooming in or zooming out on an image
    5.  (e) Displaying a timer or count-down on a website
    6.  (f) Playing audio & video in a web page
    7.  (g) Displaying animations & Using a drop-down hamburger menu
  • Creating Websites and Mobile apps
    1.  (a) Developers can use various JavaScript frameworks and libraries
    2.  (b) JavaScript front-end frameworks include React, React Native, Angular, and Vue
    3.  (c) A few famous examples include Paypal, LinkedIn, Netflix, Uber etc. use JavaScript.
  • Building web servers & developing server applications
    1.  (a) build simple web servers
    2.  (b) develop the back-end infrastructure using Node.js
  • Presentations
    1.  (a) JavaScript library, RevealJS is used to build a web-based slide deck
    2.  (b) Examples like slides.com
  • Flying Robots
    1.  (a) quadcopters come with a simple OS that makes it possible to install NodeJS.
    2.  (b) Which means, you can program a drone
  • Game development
  • History of JavaScript:

    Brendan Eich created the JavaScript in 1995. At that time, web pages could only be static, lacking the capability for dynamic behavior after the page was loaded in the browser.

    Brendan Eich

    JavaScript was called LiveScript earlier at Netscape corporation. It became very popular during the dot-com boom.

    ECMAScript standard

  • European Computer Manufacturer's Association has adopted ECMAScript as a JavaScript standard intended to ensure the interoperability of web pages across different browsers.
  • JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard.
  • JavaScript is standardized by ECMA International in the document ECMA-262.
  • The latest ECMA-262, 13th edition (ES2022) was released on June 2022. The documentation can be found at ECMA-262 - 13th edition.
  • JavaScript Engines

    JavaScript engine is a software component that executes JavaScript code and converts it into computer understandable language. All relevant modern engines use just-in-time compilation for improved performance. JavaScript engines are typically developed by web browser vendors, and every major browser has one.

  • V8 from Google : is the most used JavaScript engine. Google Chrome and the many other Chromium-based browsers use it.
  • SpiderMonkey : is developed by Mozilla for use in Firefox and its forks.
  • JavaScriptCore : is Apple's engine for its Safari browser. Other WebKit-based browsers also use it.
  • Chakra : is the engine of the Internet Explorer browser.
  • JavaScript Analogy : English Grammar

    JavaScript Analogy

    JavaScript: Install & Run

    Modern Web browser

    Getting started with JavaScript is easy: all you need is a modern Web browser.

    Install the either one of the prefered browsers like Google Chrome or Firefox Browser

    Web Console


    The Web Console tool built into browers like Google Chrome / Firefox is useful for experimenting with JavaScript; you can use it in two modes: single-line input mode, and multi-line input mode.

  • Single-line input in the Web Console : The Web Console shows you information about the currently loaded Web page, and also includes a JavaScript interpreter that you can use to execute JavaScript expressions in the current page. To open the Web Console (Ctrl + Shift + I on Windows and Linux or Cmd-Option-K on Mac).
  • Singleline Mode
  • Multi-line input in the Web Console : The single-line input mode of the Web Console is great for quick testing of JavaScript expressions, but although you can execute multiple lines, it's not very convenient for that. If you want to write multiple lines of commands in the Chrome console, first open the console (CMD + Shift + J on Mac / Ctrl + Shift + I on Windows). Now while inside the Console, write any line of code, and then hold down Shift + Enter.
  • Multiline Mode

    JavaScript language syntax

  • JavaScript borrows most of its syntax from Java, C, and C++, but it has also been influenced by Awk, Perl, and Python.
  • JavaScript is case-sensitive and uses the Unicode character set.
  • The source text of JavaScript gets scanned from left to right, and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments, or whitespace. (Spaces, tabs, and newline characters are considered whitespace.)
  • Syntax refers to the structure of the language, which is, what constitutes a correctly-formed program.

    Observe the below code:

    
    // Program to add two numbers
    
    // function declaration for adding two numbers
    function addNum(num1, num2) {
        let total = 0
        total = num1 + num2
        return (total)
    }
    
    let value1 = 0; value2 = 0
    value1 = parseInt(prompt('Enter the first number: '))   // Input first number
    value2 = parseInt(prompt('Enter the second number: '))  // Input second number
    
    /* 
       Invoking the function addNum() 
       and Printing the Output 
    */ 
    console.log(`The sum of ${value1} and ${value2} is ${addNum(value1, value2)}`)            
                
    
    OUTPUT
    Enter the first number: 24
    Enter the second number: 12
    The sum of 24 and 12 is 36
    

    This above script illustrates several of the important aspects of JavaScript syntax.
    Let's walk through it and discuss some of the syntactical features of JavaScript.

    Comments are marked by // or /* */

  • The script starts with a single line comment:
  • 
    // Program to add two numbers                               
    
    
  • Comments behave like whitespace, and are discarded during script execution.
  • Singleline Comments in JavaScript are indicated by two forward slash sign // and anything on the line following the sign // is ignored by the interpreter.
  • This means, for example, that you can have stand-alone comments like the one just shown, as well as inline comments that follow a statement. For example:
    
    value1 = parseInt(prompt('Enter the first number: '))   // Input first number
    
    
  • JavaScript also has a syntax for multi-line comments, such as the /* */ syntax.
    
    /* 
      Invoking the function addNum() 
      and Printing the Output 
    */ 
                                        
    
  • End-of-Line terminates a statement

  • The first line in the function declaration is:
    
    total = num1 + num2
                
    
  • This is an assignment operation, where a variable named total is assigned to sum of two numbers num1 + num2
  • Notice that the end of this statement is simply marked by the end of the line. This is in contrast to languages like C and C++, where every statement must end with a semicolon ;
  • Semicolon can optionally terminate a statement

    Sometimes it can be useful to put multiple statements on a single line. This shows in the example, how the semicolon ; familiar in C or Python Language, can be used optionally in JavaScript to put two statements on a single line.

    In JavaScript, instructions are called statements and are separated by semicolons ;. A semicolon is not necessary after a statement if it is written on its own line. But if more than one statement on a line is desired, then they must be separated by semicolons.

    
    let value1 = 0; value2 = 0;
              
    

    Functionally, this is entirely equivalent to writing

    
    let value1 = 0
    let value2 = 0
              
    

    Block scope represented by { }

    In addition, variables declared with let or const can belong to Block scope. This scope created with a pair of curly braces { } (a block).

    In the function declaration, the block of code looks:

    In programming languages, a block of code is a set of statements that should be treated as a unit.

    
    // function declaration for adding two numbers
    function addNum(num1, num2) {
        let total = 0
        total = num1 + num2
        return (total)
    }
              
    

    Whitespaces within lines does not matter

    White space within lines of JavaScript code does not matter

    For example, all three of these expressions are equivalent:

    
    sumNumbers=12+34
    sumNumbers = 12 + 34
    sumNumbers    =    12    +    34
    
    

    Abusing this flexibility can lead to issues with code readibility.

    Using whitespace effectively can lead to much more readable code, especially in cases where operators follow each other - compare the following two expressions for exponentiating by a negative number:

    Observe that second version with spaces much is more easily readable at a single glance.

    
    squareNumber=9**2
    // Check the below with SPACES
    squareNumber = 9 ** 2
                
    

    Parentheses are for grouping or calling

    Two major uses of parentheses. First, they can be used in the typical way to group statements or mathematical operations:

    
    12 * (34 + 56) 
    # 1080
    
    

    Secondly, they can also be used to indicate that a function is being invoked (called).

    In the below snippet, the addNum() is used to call the function with two arguments. The function call is indicated by a pair of opening and closing parentheses, with the arguments to the function contained within:

    
    addNum(value1, value2)
                
    

    Some functions can be called with no arguments at all, in which case the opening and closing parentheses still must be used to indicate a function evaluation. An example of this is the toUpperCase() method of string datatype.

    The "()" after toUpperCase indicates that the function should be executed, and is required even if no arguments are necessary.

    
    let firstString = 'Skillzam'.toUpperCase()
    console.log(firstString)
    
    // SKILLZAM
    
    

    Add JavaScript to HTML

    JavaScript is one of the top three core technologies of world wide web (www). The other two are HTML & CSS.

    JavaScript can be added to HTML file in 3 ways:

  • Inline JavaScript
  • Internal JavaScript
  • External JavaScript
  • Inline JavaScript

  • Inline JavaScript is used when we have to call a JavaScript method/function in the HTML event attributes.
  • There are many events in which we have to add JavaScript code directly. Example events: onmouseover, onclick, onchange etc.
  • There is no need to add the <script> tag in the HTML file.
  • For Example: The below HTML file contains a <button> tag, which has inline JavaScript handler -
    onclick="window.alert('You clicked the button!')"

    
    <html lang="en-US">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Add inline JavaScript to HTML</title>
    </head>
    <body>
    
    <!-- Inline JavaScript handlers - onclick="window.alert('You clicked the button!')" -->
    <button onclick="window.alert('You clicked the button!')">Click Me</button>
    
    </body>
    </html>
    
    
    OUTPUT


    Internal JavaScript

  • To add internal JavaScript code into HTML webpage, we use the <script>...</script> tag of HTML, that wrap around JavaScript code inside the HTML program.
  • Users can add the <script>...</script> tag with JavaScript code in the <body> tag or <head> tag, because it is completely depends on the structure of the web page being built.
  • For Exmaple: In the below HTML code, the <script>...</script> tag inside the <body> section, contains the JavaScript code to write a text (string) on the webpage:

    
    <html lang="en-US">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Add internal JavaScript to HTML</title>
    </head>
    <body>
    
      <!-- JavaScript code begins here -->
      <script>
          document.write("Example to demo the Internal JavaScript")
      </script>
      <!-- JavaScript code ends here -->
    
    </body>
    </html>
    
    
    OUTPUT

    internal JavaScript

    External JavaScript

  • JavaScript code can also be placed in external files.
  • External JavaScript file with the .js extension will be included in the HTML file using the src (source) attribute of the <script> tag.
  • It becomes very helpful, if we want to use the same code in multiple HTML programs.
  • External JavaScript files helps in reusability and readability of JavaScript code, as it saves us from the task of writing the same code over and over again thereby, makes it easier to maintain web pages.
  • External JavaScript reference can be placed in either <head> or <body>.
  • JavaScript will behave, as if it was located exactly where the <script> tag is located.
  • Please note that, External JavaScript files cannot contain <script> tags.
  • For Example: the below mentioned HTML file contains External JavaScript file "app.js", which is added using <script> tag with src attribute.

    
    <html lang="en-US">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Add external JavaScript to HTML</title>
      
      <!-- External JavaScript file "app.js" is added 
            using <script> tag with "src" attribute -->    
      <script src="app.js"></script>
    
    </head>
    <body>
    
    </body>
    </html>
    
    


    Below JavaScript code is added to external file app.js without adding the <script> tag

    
    document.write("Example to demo the External JavaScript")
     
    
    OUTPUT

    external JavaScript

    Display data in JavaScript

  • window.alert() : method shows an alert box with the defined message and an OK button in an HTML document i.e. writing into an alert box.
  • document.write() : method aims to display some particular content in the browser window i.e. writing into the HTML output.
  • console.log() : method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
  • innerHTML : property sets or returns the HTML content (inner HTML) of an element i.e. writing into an HTML element.
  • NOTE: JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript.

    
    // Using alert() method - alert box with a message
    alert("Hello World - By alert() method");
    
    // Using write() method - write content to the Document  
    document.write("Hello World - By write() method");
    
    // Using log() method - write message to the console  
    console.log("Hello World - By console.log() method");
    
    // Using DOM selection & manipulation
    document.getElementById("para").innerHTML = 
    "Hello World - By DOM selection & manipulation";
    
    

    JavaScript Statement

  • A JavaScript program is a list of programming statements.
  • JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
  • The statements are executed, one by one, in the same order as they are written.
  • Semicolons ( ; ) separate JavaScript statements.
  • JavaScript ignores multiple spaces & is a case-sensitive language.

  • JavaScript Statement
    
    // JavaScript Statement
    
    let amount = 88 + 2;
    console.log(amount)
    
    
    OUTPUT
    
    90
    
    

    Variables

  • The syntax of a programming language refers to structure of the language, that is, what constitutes a legal program.
  • The semantics of a programming language refers to the meaning of a legal program.
  • We will now understand the semantics of identifier keywords variables which are the main ways you store, reference, and operate on data within a JavaScript code.

    Identifiers

  • JavaScript Identifier is the name given to identify a variable, function, class, module or other object.
  • That means, whenever we want to give an entity a name, that's called identifier.
  • An identifier is used to link a value with a name.
  • In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (_), and dollar signs ($).
  • Identifiers are not allowed to start with numbers.
  • JavaScript identifiers are not only limited to ASCII — many Unicode codepoints are allowed as well.
  • Identifiers with special meanings: A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include: arguments, as, async, eval, from, get, of, set

    Keywords

  • Keywords have a special meaning in a language, and are part of the syntax. Example:
    1.  (a). function - Declares a function
    2.  (b). let - Declares a block variable
    3.  (c). try - Implements error handling
  • Reserved Words : Some keywords are reserved, meaning that cannot be used as an identifier for variable declarations, function declarations, etc.
  • NOTE: 16 reserved words in BOLD, have been removed from ECMAScript 5/6 standard.

    Here is a list of 64 Reserved words in JavaScript Language:
    abstract double in super
    arguments else instanceof switch
    await enum int synchronized
    boolean eval interface this
    break export let throw
    byte extends long throws
    case false native transient
    catch final new true
    char finally null try
    class float package typeof
    const for private var
    continue function protected void
    debugger goto public volatile
    default if return while
    delete implements short with
    do import static yield

    Variables

  • Variables are containers for storing values.
  • Creating a variable in JavaScript is called "declaring" a variable.
  • Variable declared without a value will have, value undefined
  • Cannot re-declare a variable declared with let or const.
  • Four Ways to declare a JavaScript Variable:
    1. - Using var
    2. - Using let
    3. - Using const
    4. - Using nothing
  • 
    // Declare a JavaScript Variable
    
    let $price = 12           // using let
    const PI = 3.142          // using const  
    var premium = 12500.25    // using var
    deductible = 500          // using nothing  
    
    console.log($price)
    console.log(PI)
    console.log(premium)
    console.log(deductible)
    
    
    OUTPUT
    
    12
    3.142
    12500.25
    500
    
    

    Naming Variable

  • Names can contain letters, digits, underscores, dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $(dollar) and _ (underscores)
  • Names are case-sensitive
  • Reserved words cannot be used as variable names.
  • 
    // Naming Variables & assignment 
    
    let price = 120             // variable names can contain letters
    var Price = 24              // price & Price are different as JavaScript is case-sensitive
    let interest_rate = 2.25    // '_' is a valid usage in variable name
    const QTY = 3               // All-caps is valid usage in variable name   
    let acct101 = 'skillzam'    // variable names can contain numbers
    var $amount = 200.25        // variable names can contain '$' sign                             
    let isGreater = true        // variable names can contain combination of small & capital letters
    
    


    JavaScript Variable Examples:

    
    // JavaScript Variable Example
    // Declare a JavaScript Variable using keywords var, let, const
    
    var num1 = 5;            // Variable name can contain numbers like num1
    const num2 = 6;  
    let total = num1 + num2; // variable "total" will store value of 11 = ( 5 + 6 )
    console.log("The value of total is: " + total)                                     
                
    
    OUTPUT
    
    The value of total is: 11
    
    
    
    // JavaScript Variable Example
    // Variable names can start with "$" symbol like in $price1
    
    const $price1 = 5;
    const $price2 = 5;
    let totalPrice = $price1 + $price2; 
    console.log("The total is: " + totalPrice)
    
    
    OUTPUT
    
    The total is: 10
    
    
    
    // JavaScript Variable Example
    // Variable names can start with "_" (underscore) symbol like in _name
    
    let _name = "FIFA ";
    _name += "World Cup 2022";
    console.log(_name)
      
    
    OUTPUT
    
    FIFA World Cup 2022
    
    
    
    // JavaScript Variable Example
    // variable declared without a value will have the value undefined
    
    let salary;
    console.log("The salary amount is : " + salary)
        
    
    OUTPUT
    
    The salary amount is : undefined
    
    
    
    // JavaScript Variable Example
    // If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated
    
    const intNum = 3;
    const str = "31";           // Numbers within quotes will be treated as strings
    let sumUp = str + intNum;   // concatenation of number and string
    console.log("Result (sumUp) is : " + sumUp + " and the typeof is : " + typeof(sumUp))
    
    
    OUTPUT
    
    Result (sumUp) is : 313 and the typeof is : string
    
    

    Variable names with multiple words

  • User defined Variable names with more than one word can be difficult to read.
  • There are several ways you can use to make them more readable:
  • 1. Camel Case

    Variable names where each word, except the first, starts with a capital letter:

    
    let firstName = 'Jack'                                    
                
    

    2. Snake Case

    Variable names where each word is separated by an underscore ( _ ) character:

    
    let last_name = 'Sparrow'                           
      
    

    3. Pascal Case

    Variable names where each word starts with a capital letter:

    
    var MyFavoriteTeam = 'F C Barcelona'
    
    

    Keywords let, const, var

    Ways to declare a JavaScript Variable:

    1. - Using var
    2. - Using let
    3. - Using const
    4. - Using nothing



    When to use const


    Always declare a variable with const when you know that the value should not be changed. Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new Regex
  • Block Scope

  • Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
  • ES6 introduced two important new JavaScript keywords: let and const
  • Variables declared inside a block "curly braces { }" cannot be accessed from outside the block.
  • Variables defined with let or const have Block Scope.
  • Variables declared with the var cannot have block scope.
  • 
    // JavaScript "let" Keyword to define variable
    // Cannot redclare a block-scoped variable using (let)
    
    let favColor = "BLUE";
    let favColor = "BLACK";    // SyntaxError
    console.log("Favorite color is : " + favColor)
    
    
    OUTPUT
     
    SyntaxError: Identifier 'favColor' has already been declared
    
    

    Redeclaring Variables

  • Variables defined with let or const cannot be redeclared in the same block.
  • Redeclaring a variable with let, in another block, is allowed
  • Redeclaring a variable inside a block using the let keyword, will not redeclare the variable outside the block.
  • Redeclaring a JavaScript variable with var is allowed anywhere in a program.
  • Redeclaring a variable inside a block using the var keyword, will also redeclare the variable outside the block.
  • 
    // JavaScript "var" Keyword to define variable
    // Redeclaring a variable inside a block will also redeclare the variable outside the block
    // var has "NO" block scope
    
    var  goals = 3; // Here goals variable container has the value 3
    {  
    var goals = 2;  // Here goals variable container has the value 2
    }
    
    // Here goals variable container has the value 2
    console.log("Number of Goals scored : " + goals) 
    
    
    OUTPUT
    
    Number of Goals scored : 2
                  
    
    
    // JavaScript "let" Keyword to define variable
    // Redeclaring a variable with let, in another block, is ALLOWED
    // let has block scope
    
    let tax = 30;   // ALLOWED - Here tax variable container has the value 30
    {
    let tax = 25;   // ALLOWED - Here tax variable container has the value 25
    console.log("Within Block scope : " + tax)  // value 25
    }
    {
    let tax = 33;   // ALLOWED - Here tax variable container has the value 33
    }
    console.log("Outside the Block : " + tax)   // Here tax variable container has the value 30
        
    
    OUTPUT
    
    Within Block scope : 25
    Outside the Block : 30
    
    

    Reassigning Variables

  • Variables defined with const cannot be reassigned.
  • Variables defined with let or var can be reassigned.
  • 
    // JavaScript "const" Keyword to define variable
    // "const" variable cannot be reassigned
    
    try {
      const PI = 3.141592653589793;
      PI = 3.14;      // TypeError 
      console.log(PI);
    }
    catch (err) {
      console.log(err)
    }
    
    
    OUTPUT
    
    TypeError: Assignment to constant variable.
                
    

    JavaScript Hoisting

  • Hoisting is JavaScript's default behavior of moving declarations to the top.
  • In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.
  • Variables defined with let or const are hoisted to the top of the block, but not initialized. This means block of code is aware of the variable, but it cannot be used until it has been declared.
  • Using a let variable before it is declared will result in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until it is declared.
  • Using a const variable before it is declared, is a syntax errror, so the code will simply not run.
  • Variables defined with var are hoisted to the top and can be initialized at any time. This means you can use the variable before it is declared.
  • To avoid bugs, always declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule.
  • 
    // JavaScript "let" Keyword to define variable
    // With "let" , you CANNOT use a variable before it is declared
    
    // "try" statement allows to define a block to be tested for errors while it is being executed
    try {                    
    countryName = "India";   // ReferenceError 
    let countryName;
    console.log(countryName);  
    }
    // "catch" statement allows  to define a block to be executed, if an error occurs in try block
    catch(err) {             
    console.log(err)
    }
    
    
    OUTPUT
    
    ReferenceError: Cannot access 'countryName' before initialization
                
    
    
    // JavaScript "const" Keyword to define variable
    // Using "const" , before it is declared, is a syntax errror, so code will not run
    
    cityName = "Bengaluru";
    const cityName;            // SyntaxError
    console.log("City of residence : " + cityName)
    
    
    OUTPUT
    
    SyntaxError: Missing initializer in const declaration
                
    

    JavaScript Operators

    Now we'll dig into the semantics of the various operators included in JavaScript language.

    Operators are reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. For example, in JavaScript the addition operator + adds numbers together and concatenates strings.

    Operand is part of an instruction representing data manipulated by the operator. For example, when you add two numbers, the numbers are the operand and "+" is the operator.

    Listed below are the major Operator categories:

  • Arithmetic Operators
  • Bitwise Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Conditional Operators
  • 1. Arithmetic Operators

  • JavaScript implements basic binary arithmetic operators.
  • Arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value.
  • These operators can be used and combined in intuitive ways, using standard parentheses ( ) to group operations.
  • They are summarized in the following table:

    Listed below are the links to the Examples
    Operator Name Description
    a + b Addition Sum of a and b
    a - b Subtraction Difference of a and b
    a * b Multiplication Product of a and b
    a / b True division Quotient of a and b
    a % b Modulus Remainder after division of a by b
    a ** b Exponentiation a raised to the power of b
    ++a Pre Increment returns operand 'a' after adding one
    a++ Post Increment returns operand 'a' before adding one
    --a Pre Decrement returns operand 'a' after substracting one
    a-- Post Decrement returns operand 'a' before substracting one
    -a Unary Negation The negative of a
    +a Unary plus a unchanged (rarely used)

    
    // addition, subtraction, multiplication
    
    (12 + 34) * (12.3 - 4)   // 381.8
    
    
    
    // division, Modulus, Exponentiation
    
    22 / 7                  // 3.142857142857143
    22 / 0                  // Infinity
    31 % 2                  // 1
    2 ** 3                  // 8
    
    
    
    // Increment Operator
    
    // Pre Increment
    let i = 9
    j = ++i        
    console.log("i = " + i)
    console.log("j = " + j)
    
    // Post Increment
    let x = 9
    y = x++         
    console.log("x = " + x)
    console.log("y = " + y)
    
    
    OUTPUT
    
    i = 10
    j = 10
    x = 10
    y = 9
    
    
    
    // Decrement Operator 
    
    // Pre Decrement
    let a = 9
    b = --a        
    console.log("a = " + a)
    console.log("b = " + b)
    
    // Post Decrement
    let p = 9
    q = p--         
    console.log("p = " + p)
    console.log("q = " + q)
    
    
    OUTPUT
    
    a = 8
    b = 8
    p = 8
    q = 9
    
    

    2. Bitwise Operators

  • JavaScript includes operators to perform bitwise logical operations.
  • bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.
  • Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
  • Bitwise operators are much less commonly used than the standard arithmetic operations.
  • Use number.toString(2) to convert number to binary.
  • Bitwise operators are summarized in the following table:

    Listed below are the links to the Examples
    Operator Name Description
    a & b Bitwise AND Bits defined in both a and b
    a | b Bitwise OR Bits defined in a or b or both
    a ^ b Bitwise XOR Bits defined in a or b but not both
    ~a Bitwise NOT Bitwise negation of a
    a << b Zero fill left shift Shift bits of a left by b units, shifting in zeros from the right.
    a >> b Signed right shift Shift bits of a right by b units, discarding bits shifted off.
    a >>> b Zero fill right shift Shift bits of a right by b units. discarding bits shifted off, and shifting in zeros from the left.
    
    // Number.toString(2) function returns the binary version of a specified integer
    
    let num = 8
    num.toString(2)     // '1000'
    
    
    
    // Bitwise AND
    
    9 & 10              // 8
    
    //   1001 (9 in Binary)
    // & 1010 (10 in Binary)
    //_______________________
    //   1000 (8 in Binary)
    
    
    
    // Bitwise OR
    
    9 | 10              // 11
    
    //   1001 (9 in Binary)
    // | 1010 (10 in Binary)
    //_______________________
    //   1011 (11 in Binary)
    
    
    
    // Bitwise XOR
    
    9 ^ 10              // 3
    
    //   1001 (9 in Binary)
    // ^ 1010 (10 in Binary)
    //_______________________
    //   0011 (3 in Binary)
    
    
    
    // Bitwise << 'Zero fill left shift'
    
    4 << 1           // 8
    
    //    0100 (4 in Binary)
    // << 0001 (1 in Binary)
    //_______________________
    //    1000 (8 in Binary)
    
    
    
    // Bitwise >> 'Signed right shift'
    
    4 >> 1           // 2
    
    //    0100 (4 in Binary)
    // >> 0001 (1 in Binary)
    //_______________________
    //    0010 (2 in Binary)
    
    
    
    // Bitwise >>> 'Zero fill right shift'
    
    4 >>> 1           // 2
    
    //     0100 (4 in Binary)
    // >>> 0001 (1 in Binary)
    //_______________________
    //     0010 (2 in Binary)
    
    
    
    // Bitwise NOT
    // JavaScript uses 32 bits signed integers, it will not return 10. It will return -6.
    // 00000000000000000000000000000101 (5)
    // 11111111111111111111111111111010 (~5 = -6)
    // A signed integer uses the leftmost bit as the minus sign
    
    ~5                  // 10
    
    // ~ 0101 (5 in Binary)
    //_______________________
    //   1010 (10 in Binary)
    
    

    3. Assignment Operators

  • Assignment operator assigns a value to its left operand based on the value of its right operand.
  • Simple assignment operator is = equal, which assigns the value of its right operand to its left operand.
  • 
    // Assignment Operator (=) equal
    
    let assignNum = 66
    console.log(assignNum)      
    
    // 66
    
    
  • We can use these variables in expressions with any of the operators mentioned earlier.
  • For example, to add 6 to assignNum we write:

    
    assignNum + 6
    
    // 72
    
    
  • We might want to update the variable assignNum with this new value; in this case, we could combine the addition and the assignment and write assignNum = assignNum + 6. Because this type of combined operation and assignment is so common, JavaScript includes built-in update operators for all of the arithmetic operations:
  • 
    // Assignment Operator with addition (+=)
    
    let assignNum = 66
    assignNum += 6     // equivalent to assignNum = assignNum + 6
    console.log(assignNum)      
    
    // 72
    
    
    JavaScript Assignment Operators
    Operator Description Same as
    a += b Add and equal operator a = a + b
    a -= b Subtract and equal operator a = a - b
    a *= b Asterisk and equal operator a = a * b
    a /= b Divide and equal operator a = a / b
    a **= b Exponent and equal operator a = a ** b
    a %= b Modulus and equal operator a = a % b
    a &= b Bitwise AND Assignment Operator a = a & b
    a |= b Bitwise OR Assignment Operator a = a | b
    a ^= b Bitwise XOR Assignment Operator a = a ^ b
    a << = b Bitwise Zero fill LEFT shift assignment operator a = a << b
    a >>= b Bitwise Signed RIGHT shift assignment operator a = a >> b
    a &&= b Logical AND assignment operator a = a && b
    a ||= b Logical OR assignment operator a = a || b
    a ??= b Nullish coalescing assignment operator a = a ?? b

    Each one is equivalent to the corresponding operation followed by assignment: that is, for any operator "■" the expression a ■= b is equivalent to a = a ■ b with a slight catch.

    
    // Demo the Add and Assignment Operators 
    
    let num1 = 6,  
        num2 = 2;
    
    num1 += num2     //  num1 = num1 + num2
    console.log( "Value of num1 = " + num1)  
            
    
    OUTPUT
    
    Value of num1 =  8 
    
    
    
    // Demo the Substract and Assignment Operators 
    
    let num1 = 6,  
        num2 = 2;
    
    num1 -= num2     // num1 = num1 - num2
    console.log( "Value of num1 = " + num1)              
                
    
    OUTPUT
     
    Value of num1 =  4
    
    
    
    // Demo the Multiple and Assignment Operators 
    
    let num1 = 6,  
        num2 = 2;
      
    num1 *= num2     // num1 = num1 * num2
    console.log( "Value of num1 = " + num1)            
                
    
    OUTPUT
     
    Value of num1 =  12
      
    
    
    // Demo the Divide and Assignment Operators 
    
    let num1 = 22,  
        num2 = 7;
    
    num1 /= num2     // num1 = num1 / num2
    console.log( "Value of num1 = " + num1)       
                
    
    OUTPUT
     
    Value of num1 = 3.142857142857143
    
    
    
    // Demo the Exponent and Assignment Operators 
    
    let num1 = 3,  
        num2 = 2;
    
    num1 **= num2     // num1 = num1 ** num2
    console.log( "Value of num1 = " + num1)       
                
    
    OUTPUT
     
    Value of num1 =  9
      
    
    
    // Demo the Modulus  and Assignment Operators 
    
    let num1 = 7,  
        num2 = 4;
    
    num1 %= num2     // num1 = num1 % num2
    console.log( "Value of num1 = ", num1)        
                
    
    OUTPUT
     
    Value of num1 =  3
      
    
    
    // Demo the Bitwise AND Assignment Operator 
    
    let num1 = 6,  
        num2 = 13;
    
    num1 &= num2     // num1 = num1 & num2
    console.log( "Value of num1 = " + num1)  
    
    //   0110  (6 in binary)  
    // & 1101  (13 in binary)  
    //  ________  
    //   0100 = 4 (In decimal)  
      
    
    OUTPUT
     
    Value of num1 =  4
      
    
    
    // Demo the Bitwise OR Assignment Operator
    
    let num1 = 6,  
        num2 = 13;
    
    num1 |= num2    // num1 = num1 | num2
    console.log( "Value of num1 = " + num1)  
    
    //   0110  (6 in binary)  
    // | 1101  (13 in binary)  
    //  ________  
    //   1111 = 15 (In decimal)   
                
    
    OUTPUT
     
    Value of num1 =  15
      
    
    
    // Demo the Bitwise XOR Assignment Operator
    
    let num1 = 9,  
        num2 = 10;
    
    num1 ^= num2    // num1 = num1 ^ num2
    console.log( "Value of num1 = " + num1)  
    
    //   1001 (9 in Binary)
    // ^ 1010 (10 in Binary)
    //_______________________
    //   0011 (3 in Binary)
          
    
    OUTPUT
    
    Value of num1 =  3
      
    
    
    // Demo the Bitwise 'Zero fill LEFT shift' Assignment Operator
    
    let num1 = 4,  
        num2 = 1; 
    
    num1 <<= num2    // num1 = num1 << num2
    console.log("Value of num1 = " + num1)  
    
    //    0100 (4 in Binary)
    // << 0001 (1 in Binary)
    //_______________________
    //    1000 (8 in Binary)
                
    
    OUTPUT
    
    Value of num1 =  8
      
    
    
    // Demo the Bitwise 'Signed RIGHT shift' assignment operator
    
    let num1 = 4,  
        num2 = 1; 
    
    num1 >>= num2    // num1 = num1 >> num2
    console.log("Value of num1 = " + num1)  
    
    //    0100 (4 in Binary)
    // >> 0001 (1 in Binary)
    //_______________________
    //    0010 (2 in Binary)
                
    
    OUTPUT
     
    Value of num1 =  2
      
    
    
    // Demo the Logical AND assignment operator
    
    let num1 = 9,  
        num2 = 10; 
    
    num1 &&= num2    // num1 = num1 && num2
    console.log("Value of num1 = " + num1)  
    
    
    OUTPUT
    
    Value of num1 =  10
    
    
    
    // Demo the Logical AND assignment operator
    
    let num1 = 9,  
        num2 = 10; 
    
    num1 ||= num2    // num1 = num1 || num2
    console.log("Value of num1 = " + num1)  
    
    
    OUTPUT
    
    Value of num1 = 9
    
    
    
    // Demo Nullish coalescing assignment operator
    // Also called logical nullish assignment operator
    // only assigns if a is nullish (null or undefined) (a ??= b)
    
    
    let num1 = null, // Oberve that num1 is null 
        num2 = 10; 
    
    num1 ??= num2    // num1 = num1 ?? num2
    console.log("Value of num1 = " + num1)  
    
    
    OUTPUT
    
    Value of num1 = 10
    
    
    
    // Demo Nullish coalescing assignment operator
    // On object data structures 
    
    const player = {
      sport : 'hockey',
      country : 'India'
    }
    
    // Note that 'name' key is undefined in  'player' object
    // player.name = player.name ?? 'Dhanraj Pillay'
    player.name ??= 'Dhanraj Pillay'    
    console.log("Value of player.name = " + player.name)  
    
    
    OUTPUT
    
    Value of player.name = Dhanraj Pillay
    
    

    4. Comparison Operators

  • JavaScript implements standard comparison operators, which return Boolean values true and false.
  • The operands in the comparison operators expression, can be numerical, string, logical, or object values.
  • In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically.
  • The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality.
  • Comparison operations are listed below:
    Operation Description
    a == b a equal to b
    a === b a equal to b & has same type
    a != b a not equal to b
    a < b a less than b
    a > b a greater than b
    a <= b a less than or equal to b
    a >= b a greater than or equal to b

    Comparison operators can be combined with the arithmetic and bitwise operators to express a virtually limitless range of tests for the numbers.

    For example, we can check if a number is odd by checking that the modulus with 2 returns 1:

    
    // 13 is odd
    
    13 % 2 == 1         // returns true
    
    
    
    // 24 is even
    
    24 % 2 == 0         // returns true 
    
    
    
    // Equal and Strict Equal
    
    let num1 = 99,
        num2 = '99';
        
    isEqual = (num1 == num2)         // returns true 
    console.log(isEqual)            
    
    isStrictEqual = (num1 === num2)  // returns false 
    console.log(isStrictEqual)
    
    isNotEqual = (num1 != num2)      // returns false 
    console.log(isNotEqual)     
    
    
    OUTPUT
    
    true 
    false 
    false
    
    

    We can string-together multiple comparisons to check more complicated relationships:

    
    // string-together multiple comparisons
    // Example : check if givenNum is between 9 and 19
    
    let givenNum = 18
    9 < givenNum < 19  // true
    
    

    5. Logical Operators

  • Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value.
  • Logical operators are also used with non-Boolean values, they may return a the value of one of the specified operands (non-Boolean value).
  • Logical operators are listed below:
    Operator Usage Description
    Logical AND a && b Returns a if it can be converted to false; otherwise, returns b. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
    Logical OR a || b Returns a if it can be converted to true; otherwise, returns b. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
    Logical NOT !a Returns false if its single operand that can be converted to true; otherwise, returns true.
    
    // logical AND (&&) 
    
    const result1 = true && true;        // t && t returns true
    const result2 = false && false;      // f && f returns false
    const result3 = false && true;       // f && t returns false
    const result4 = false && 6 === 9;    // f && f returns false
    const result5 = 'bat' && 'ball';     // t && t returns 'ball'
    const result6 = 'false' && 'false'   // t && t returns 'false' 
    
    
    
    // logical OR (||) 
    
    const value1 = true || true;         // t || t returns true
    const value2 = false || false;       // f || f returns false
    const value3 = false || true;        // f || t returns true
    const value4 = false || 6 === 9;     // f || f returns false
    const value5 = 'bat' || 'ball';      // t || t returns 'bat'
    const value6 = 'false' || 'false'    // t || t returns 'false' 
    
    
    
    // logical NOT (!) 
    
    const op1 = !true;                   // !t returns false
    const op2 = !false;                  // !f returns true
    const op3 = !"code";                 // !t returns false
    const op4 = !null;                   // !f returns true
    const op5 = !undefined;              // !f returns true
    
    
    
    // logical AND (&&) Example 
    
    let testNum = 11;
    (testNum < 15) && (testNum > 10)     // true
    
    
    
    // Logical OR (||) Example 
    
    let testNum = 11;
    (testNum > 9) || (testNum % 2 == 0)  // true
    
    
    
    // Logical NOT (!)
    
    let testNum = 11;
    !(testNum < 7)                      // true
    
    

    Boolean algebra aficionados might notice that the XOR operator is not included; this can of course be constructed in several ways from a compound statement of the other operators.

    Otherwise, a clever trick you can use for XOR of Boolean values is the following:

    
    // (testNum > 1) ^ (testNum < 10)  // return 0 or 1 
    
    let testNum = 11;
    (testNum > 1) != (testNum < 10)    // true            
    
    

    These sorts of Boolean operations will become extremely useful when we begin discussing control flow statements such as conditionals and loops

    6. Conditional Operators

  • Conditional operator is the only JavaScript operator that takes three operands.
  • The operator can have one of two values based on a condition.
  • Conditional operator is also know as “Question mark” or "Ternary" operator.
  • It is the simplified operator of if/else statement.

  • SYNTAX : variableName = (condition) ? valueOne : valueTwo


    Conditional operator assigns a value to a variable based on some condition (true or false).

    1.  (a). Expression consists of three operands: the condition, valueOne and valueTwo.
    2.  (b). Evaluation of the condition should result in either true/false or a boolean value.
    3.  (c). The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.
    
    // Conditional (Ternary) Operator
    // Example to demo voting rights eligibility
    
    let age = 24,               // Actual Age
        eligibleAge = 18,       // Eligible Age  
        votingRights;
        
    votingRights = (age > eligibleAge) ? "eligible to vote!" : "NOT eligible to vote!";
    console.log("Age of the citizen is " + 
                age + 
                " years. \n" + 
                "Hence, citizen is " + 
                votingRights);
    
    
    OUTPUT
    
    Age of the citizen is 24 years. 
    Hence, citizen is eligible to vote!
    
    

    typeof() Operator

  • typeof operator returns a string indicating the type of a variable or unevaluated operand.
  • Operand is the string, variable, keyword, or object for which the type is to be returned.
  • The parentheses are optional.
  • typeof operator has higher precedence than binary operators like addition (+).
  • SYNTAX :
    typeof(operand)
    typeof operand


    Listed below are types returned from typeof operator :

  • number (for integers, decimals, NaN, Infinity, -Infinity )
  • string (for strings)
  • boolean (for Boolean)
  • undefined (for value that is not assigned / undefined)
  • object (for null i.e. nothing, empty, value unknown)
  • bigint (for integer values larger than (253 -1) )
  • symbol (for a unique "hidden" identifier)
  • function (for functions & classes (are functions as well))
  • object (for any other object )
  • 
    // typeof value returned from a 'integer' operand
    
    const intNum = 123
    typeof intNum     
    
    // 'number'
    
    
    
    // typeof value returned from a 'decimal' operand
    
    let decimalNum = 3.142
    typeof decimalNum    
    
    // 'number'
    
    
    
    // typeof value returned from a 'string' operand
    
    let CompanyName = "Workzam"
    typeof(CompanyName)                    
    
    // 'string'
    
    
    
    // typeof value returned from a 'boolean' operand
    
    let isGreater = true
    typeof(isGreater)         
    
    // 'boolean'
    
    
        
    // typeof value returned from a 'unassigned' operand
                       
    let randNum;
    typeof(randNum)
    
    // 'undefined'
    
    
    
    // typeof value returned from a 'null' operand
    
    let tickerSym = null
    typeof(tickerSym)        
      
    // 'object'
    
    
    
    // typeof value returned from a 'bigint' operand
    
    const largeNumber = 1234567890123456789012345678901234567890n;   
    typeof(largeNumber)
    
    // 'bigint'
    
    
    
    // typeof value returned from a 'symbol' operand
    
    const player = {
      fname: "Leo",
      lname: "Messi",
      position: "Forward" 
    };
    
    let uid = Symbol('uid');
    player[uid] = 98765;
    typeof(uid)
    
    // 'symbol'
    
    
    
    // typeof value returned from a 'function' operand
    
    function printVal () {
      console.log('Hello')
    }
    
    typeof printVal
                
    // 'function'
    
    
    
    // typeof value returned from a 'array' operand
    
    const cricketer = ['Sachin', 'Dhoni', 'Virat']
    typeof cricketer
    
    // 'object'
    
    
    
    // typeof value returned from a 'object' operand
    
    const player = {
      fname: "Leo",
      lname: "Messi",
      position: "Forward" 
    };
    
    typeof player
    
    // 'object'
    
    

    Data Types

  • ECMAScript standard (ECMA-262) defines seven primitive data types.
  • To be able to operate on variables, it is important to know something about the type.
  • JavaScript has dynamic types. This means that the same variable can be used to hold different data types.
  • All primitive datatype values are immutable i.e. whose content cannot be changed without creating an entirely new value.
    Using immutable datatypes has several benefits :
    1.   (1). To improve performance (no planning for the object's future changes)
    2.   (2). To reduce memory use (make object references instead of cloning the whole object)
    3.   (3). Thread-safety (multiple threads can reference the same object without interfering with one other)
    4.   (4). Lower developer mental burden (the object's state won't change and its behavior is always consistent)

  • Seven primitive datatypes

  • number (for integers & decimal numbers)
  • string (for strings)
  • boolean (for Boolean data like true / false)
  • undefined (for value that is not assigned)
  • null (for nothing, empty, value unknown)
  • bigint (for integer values larger than 253- 1)
  • symbol (for a unique "hidden" identifier)

  • Object wrapper

    Each primitive type (except for the types of undefined and null) has a corresponding wrapper class. The key purpose of these classes is to provide properties (mostly methods) for primitive values.

    There are two ways of invoking wrapper classes:

  • All wrapper classes can be function-called, which converts an arbitrary value to the primitive type that the class represents. This is a descriptive way of converting to primitive types.
  • Only the wrapper classes Number, String and Boolean can be instantiated via new. Doing this (explicitly) is almost never useful for programmers.
  • Primitive datatypes & its Object wrapper:
    Datatype typeof() return value Object wrapper
    Number "number" Number
    String "string" String
    Boolean "boolean" Boolean
    Bigint "bigint" BigInt
    Symbol "symbol" Symbol
    Undefined "undefined" N/A
    Null "object" N/A

    Primitive Methods

  • JavaScript allows us to work with primitives (string, number, boolean, bigint, symbol) as if they were objects. They also provide methods to call as such.
  • Objects are “heavier” than primitives. They require additional resources to support the internal machinery.
  • primitive as an object:
    1.   (1). Primitives are still primitive. A single value, as desired
    2.   (2). JavaScript allows access to methods(functions) and properties of string, number, boolean, bigint and symbol
    3.   (3). In order for that to work, a special “object wrapper” that provides the extra functionality is created, and then is destroyed.
    4.   (4). Primitives null and undefined are exceptions. They have no corresponding “wrapper objects” and provide no methods. In a sense, they are “the most primitive”.
  • For Example: There exists a string method slice() that returns a substring of a string.

    
    // slice() returns substring
    
    let city = "Mumbai"
    city.slice(0, 3)    // returns substring
    
    
    OUTPUT
    
    'Mum'
    
    

    number

  • number is a built-in primitive data type in JavaScript.
  • number represents both integer and floating point numbers.
  • Numbers also includes Infinity, -Infinity and NaN (Not a Number).
  • Number is a numeric data type in the double-precision 64-bit floating point format.
  • Number are always stored as decimal numbers (floating point) in JavaScript.
  • Extra large or extra small numbers can be written with scientific (exponential) notation.
  • Integer Numbers i.e. numbers without a period or exponent notation are accurate up to 15 digits and maximum number of decimals is 17.
  • Number can also use underscore _ as the separator, which plays the role of the “syntactic sugar”, it makes the number more readable. For Example: The number 1_000_000_000 represents a million.
  • number is capable of safely storing integers in the range - (253- 1) (Number.MIN_SAFE_INTEGER) to 253- 1 (Number.MAX_SAFE_INTEGER).
  • number is capable of storing positive floating-point numbers between 2-1074 (Number.MIN_VALUE) and 21024 (Number.MAX_VALUE)
  • Numerical values outside the range ± (2-1074  to  21024) are automatically converted:
    1.  (a). Positive values greater than Number.MAX_VALUE are converted to +Infinity.
    2.  (b). Positive values smaller than Number.MIN_VALUE are converted to +0.
    3.  (c). Negative values smaller than - Number.MAX_VALUE are converted to -Infinity.
    4.  (d). Negative values greater than - Number.MIN_VALUE are converted to -0.
  • 
    // JavaScript DataType : number
    
    const x = 5;            
    const y = 10.75;
    const z = 0;
    let value1 = x + y;      // number datatype
    let value2 = "string"/x; // NaN - Not a number 
    let value3 = x/z;        // Infinity  
    console.log("value1 = " + value1 + " and typeof(value1) is " + typeof(value1))
    console.log("value2 = " + value2 + " and typeof(value2) is " + typeof(value2))
    console.log("value3 = " + value3 + " and typeof(value3) is " + typeof(value3))
    
    
    OUTPUT
    
    value1 = 15.75 and typeof(value1) is number
    value2 = NaN and typeof(value2) is number
    value3 = Infinity and typeof(value3) is number
    
    
    
    // DataType number (integer/decimals) precision
    
    let intNum1 = 999999999999999       // accurate up to 15 digits    
    let intNum2 = 9999999999999999      // round-off        
    let intNum3 = 1 / 3                 // maximum number of decimals is 17       
    console.log(intNum1)
    console.log(intNum2)
    console.log(intNum3)
    
    
    OUTPUT
    
    999999999999999
    10000000000000000
    0.3333333333333333
    
    
    
    // Number in Exponential notation
    
    let num1 = 12345e10      // exponential notation (e)     
    let num2 = 12345e1000    // very large number         
    console.log(num1)
    console.log(num2)
                  
    
    OUTPUT
    
    123450000000000
    Infinity
    
    
    
    // Adding number and string 
    
    let academy = "Skillzam"
    const num = 99
    let addUp = academy + num    // '+' operand will result in string datatype 
    console.log("addUp = " + addUp + " and typeof(addUp) is " + typeof(addUp))
    
    
    OUTPUT
    
    addUp = Skillzam99 and typeof(addUp) is string
    
    

    NaN (Not a Number)

    NaN is a reserved word indicating that a number is not a legal number.

    Five different types of operations that return NaN:

  • Failed number conversion - Example: explicit ones like parseInt("skillzam"), Number(undefined), or implicit ones like Math.abs(undefined).
  • Math operation where the result is not a real number - Example: Math.sqrt(-1)
  • Indeterminate form - Example: 0 * Infinity, 1Infinity, Infinity / Infinity, Infinity - Infinity
  • A method or expression whose operand is or gets coerced to NaN. This means NaN is contagious - Example: 9NaN, 7 * "workzam"
  • Other cases where an invalid value is to be represented as a number - Example: an invalid Date new Date("skillzam").getTime(), "".charCodeAt(1)
  • 
    // Types of operations that return NaN - Not a Number 
    
    console.log(parseInt("skillzam"))    // NaN
    console.log(Number(undefined))       // NaN 
    console.log(Math.abs(undefined))     // NaN
    console.log(Math.sqrt(-9))           // NaN
    console.log(Infinity - Infinity)     // NaN
    console.log(9 ** NaN)                // NaN
    console.log(9 * "workzam")           // NaN
    console.log("".charCodeAt(9))        // NaN
    let dTime = new Date("skillzam").getTime()
    console.log(dTime)                   // NaN
    
    

    Infinity or -Infinity

  • The global property Infinity is a numeric value representing infinity.
  • The value Infinity (positive infinity) is greater than any other number.
  • Infinity is the value JavaScript will return, if you calculate a number outside the largest possible number.
  • 
    // Infinity or -Infinity
    
    console.log(Infinity);            // Infinity 
    console.log(Infinity * 9);        // Infinity 
    console.log(Math.pow(9, 999));    // Infinity 
    console.log(Math.log(0));         // -Infinity
    console.log(9 / Infinity);        // 0 
    console.log(9 / 0);               // Infinity
                
    

    string

  • string is a built-in primitive data type in JavaScript.
  • string represents a collection of alphanumeric characters within a single quotes '...' or double quotes "..." or Backticks `...`
  • Whenever you create a string by surrounding text with quotation marks, the string is called a string literal.
  • You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
    For Example: 'Camel is called the "ship" of the desert'
  • Each element in the string occupies a position in the string. The first element is at index 0, the next at index 1, and so on.
  • JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.
  • Strings are encoded as a sequence of 16-bit unsigned integer values representing UTF-16 code units.
  • String literals (denoted by double or single quotes) and strings returned from String() calls in a non-constructor context (that is, called without using the new keyword) are primitive strings.
  • String with new keyword returns a string wrapper object.
  • String primitives and String objects also give different results when using eval(). Primitives passed to eval() are treated as source code; String objects are treated as all other objects are, by returning the object.

  • 
    // Strings created using Single quotes ('...')
    
    let academy = 'Skillzam'          
    console.log(academy)
              
    
    OUTPUT
    
    Skillzam
    
    

    
    // Strings created using Double quotes ("...") 
    
    let tagLine = "Learn without limits!"    
    console.log(tagLine)
    
    
    OUTPUT
    
    Learn without limits!
    
    

    
    // Strings created using Backticks (`...`) 
    
    let moreLine = `A CURE platform: 
                    - Cross-Skill 
                    - Up-Skill
                    - Re-Skill 
                    - Expert-Skill`
    
    console.log(moreLine)
      
    
    OUTPUT
    
    A CURE platform: 
                    - Cross-Skill 
                    - Up-Skill
                    - Re-Skill 
                    - Expert-Skill
    
    

    
    // Primitive string using String() method without "new" keyword
    
    let techHiring = String('www.' + 'workzam'  + '.com')   // '+' is used for concatenation
    console.log("techHiring = " + techHiring)
    console.log("typeof(techHiring) is " + typeof(techHiring))
    
    
    OUTPUT
    
    techHiring = www.workzam.com
    typeof(techHiring) is string
    
    
    
    // string wrapper object using "new" keyword
    
    // String with new returns a string wrapper object
    let playerType = new String("Midfielder")        
    let player = "Ronaldinho is a " + playerType
    console.log("playerType = " + playerType)
    console.log("typeof(playerType) is " + typeof(playerType))
    console.log("player = " + player)
    console.log("typeof(player) is " + typeof(player))
    
    
    OUTPUT
    
    playerType = Midfielder  
    typeof(playerType) is object
    player = Ronaldinho is a Midfielder 
    typeof(player) is string
    
    

  • Under the hood the string Object wrapper "Midfielder" is of object type.
  • 
    String {'Midfielder'}
    0: "M"
    1: "i"
    2: "d"
    3: "f"
    4: "i"
    5: "e"
    6: "l"
    7: "d"
    8: "e"
    9: "r"
    length: 10
    [[Prototype]]: String
    [[PrimitiveValue]]: "Midfielder"
    
    

    String Properties

    Strings have three important properties:

  • Strings contain individual letters or symbols called characters and are immutable.
  • Strings have a length, defined as the number of characters the string contains.
  • Characters in a string appear in a sequence, which means that each character has a numbered position in the string.
  • 
    // String contains characters/symbols  
    
    let strVar01 = "$killzam 2023"
    let strVar02 = "ಕನ್ನಡ"
    console.log("typeof strVar01 = " + typeof(strVar01))
    console.log("typeof strVar02 = " + typeof(strVar02))
    
    
    OUTPUT
    
    typeof strVar01 = string 
    typeof strVar02 = string
    
    
    
    // Length of a given string using String attribute "length" 
    // It returns number of characters contained in a string including SPACES
    
    let strVar03 = ' JAVASCRIPT '    
    console.log("Length of strVar03 = " + strVar03.length)
    
    
    OUTPUT
    
    Length of strVar03 = 12
    
    
    
    // Strings are immutable
    
    let fruit = "GATES"
    fruit[0] = "D"      // Using indexing, to change first charater to "D"    
    console.log(fruit)  // No change in the original string value "GATES"
    
    
    OUTPUT
    
    GATES
    
    

    Escape Characters

  • To insert characters that are illegal in a string, use an escape character.
  • An escape character is a backslash \ followed by the character you want to insert.
  • The escape characters New Line, Backspace, Carriage Return, Tab were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.
  • Escape Character usuage
    Code Description
    \' Single Quote
    \" Double Quote
    \` Backticks
    \\ Backslash
    \n New Line
    \b Backspace
    \r Carriage Return
    \t Tab
    
    // Double quotes inside a string, which is surrounded by double quotes
    
    var sentence = "Camel is called the "ship" of the desert"    // SyntaxError
    
    
    OUTPUT
    
    SyntaxError: Unexpected identifier 'ship'
    
    
    
    // Escape character \" to avoid SyntaxError
    
    var sentence = "Camel is called the \"ship\" of the desert"     
    console.log(sentence)          
    
    
    OUTPUT
    
    Camel is called the "ship" of the desert
    
    

    Template literals

  • Template literals are literals delimited with backtick `...` characters.
  • Template Literals are also called "Template Strings" or "String Templates" or "Back-Tics Syntax"
  • Template Literals were introduced as a part of ES6 feature (JavaScript 2015).
  • Template literals allows for :
    1.  (1). multi-line strings
    2.  (2). string interpolation with embedded expressions
    3.  (3). tagged templates which are special constructs


    Multi-line Strings


    A string with multi-lines can be created by template Literals using backticks.

    
    // Multi-line strings created using Backticks (`...`) 
    
    let multiLine = `A CURE platform: 
                    - Cross-Skill 
                    - Up-Skill
                    - Re-Skill 
                    - Expert-Skill`
    
    console.log(multiLine)
      
    
    OUTPUT
    
    A CURE platform: 
                    - Cross-Skill 
                    - Up-Skill
                    - Re-Skill 
                    - Expert-Skill
    
    

    String Interpolation

  • Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation.
  • String Interpolation : It is the process of substituting values of variables or/and expressions into placeholders in a string.
  • Placeholders : Template literals contains embedded expressions delimited by a dollar sign $ and curly braces { } i.e. ${expression}.
  • 
    // String interpolation using single variable placeholders
    
    let name = 'Michael Phelps'
    console.log(`${name} is called 'Flying Fish'!`)
    
    
    OUTPUT
    
    Michael Phelps is called 'Flying Fish'!
    
    
    
    // String interpolation using multiple variable placeholders
    
    let name = 'Challenger Deep'
    let location = 'Mariana Trench'
    let txt = `The ${name} in the ${location}, is the deepest part of the ocean.`
    
    console.log(txt)
    
    
    OUTPUT
    
    The Challenger Deep in the Mariana Trench, is the deepest part of the ocean.
    
    
    
    // String Interpoltion using expression placeholder
    // Solve Quadratic Equation: x**2 - 8x + 15 = 0
    
    const a = 1
    const b = -8
    const c = 15
    const root1 = `Value of root1 = ${(-b + ((b**2 - 4*a*c)**0.5)) / (2*a)}`
    const root2 = `Value of root2 = ${(-b - ((b**2 - 4*a*c)**0.5)) / (2*a)}`
    
    console.log("The roots of Quadratic Equation are :")
    console.log(root1)
    console.log(root2)
    
    
    OUTPUT
    
    The roots of Quadratic Equation are :
    Value of root1 = 5
    Value of root2 = 3
      
    

    Tagged Templates

  • A more advanced form of template literals are tagged templates.
  • Tags allow you to parse template literals with a function.
  • Tagged template is written like a function definition. However, do not pass parentheses () when calling the literal.
  • The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
  • 
    // Template literals are also Tagged templates
    
    const championName = 'Garry Kasparov'
    const championAge = 22
    const isChampion = true;
    
    function tagChampion(strings, champName, champAge) {
        let str0 = strings[0];    // ''
        let str1 = strings[1];    // ' became the youngest ever undisputed World Chess Champion at ' 
        let str2 = strings[2];    // '.' 
    
        if(isChampion) {
            return `${str0}${champName}${str1}${champAge}${str2}`;
        }
    }
    
    // creating tagged template by passing two arguments "championName" & "championAge"
    const output = tagChampion`${championName} became the youngest ever undisputed World Chess Champion at ${championAge}.`;
    
    console.log(output);
                
    
    OUTPUT
    
    Garry Kasparov became the youngest ever undisputed World Chess Champion at 22.
    
    

    String concatenation, Indexing & Slicing

    Three basic string operations:

  • Concatenation: which joins two strings together.
  • Indexing: which gets a single character from a string.
  • Slicing: which gets several characters (substring) from a string at once.

  • String Concatenation

    You can combine, or concatenate, two strings using the + operator or or concat() string method.

    
    // String Concatenation using "+" Operator 
    
    let academy;
    academy = 'Skill' + 'zam'    // String Concatenation
    console.log(academy)
            
    
    OUTPUT
    
    Skillzam
    
    
    
    // String Concatenation using "concat()" string method
    
    let fname = "Brendan"
    let lname = 'Eich'
    let fullname = fname.concat(" ", lname)    // String Concatenation
    console.log(fullname)
            
    
    OUTPUT
    
    Brendan Eich
    
    

    String Indexing :

  • Each character in a string has a numbered position called an index
  • Index counting always starts at zero. To get the character at the beginning of a string, you need to access the character at position [0]
  • You can access the character at the nth position by putting the number n between two square brackets [ ] immediately after the string.
  • at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the string/array.
  • 
    // String Indexing 
    
    let rhyme = "Twinkle, Twinkle, Little Star"
    rhyme[4]    //returns the character at index position 4
    
    
    OUTPUT
    
    'k'
    
    
    
    // Access an index beyond end of string, 
    // then JavaScript returns "undefined" 
    
    let rhyme = "Twinkle, Twinkle, Little Star"
    rhyme[100]    // returns "undefined" 
    
    
    OUTPUT
    
    undefined
    
    
    
    // Reverse Indexing using "at()" method
    
    let river = "Kaveri"
    let reverseIndex = river.at(-6)     // allows for negative indexing as well
    console.log(reverseIndex)
    
    let beyondIndex = river.at(100)     // returns "undefined"  
    console.log(beyondIndex)
    
    
    OUTPUT
    
    K
    undefined
    
    

    String Slicing :

    You can extract a portion of a string, called a substring. This substring is called Slice

    slice() method:

  • This string method returns part of the string from start to end(but not including).
  • If there is no second argument, then slice() goes till the end of the string.
  • slice() also allows for negative values for start and end arguments, which means the position is counted from the string end (i.e. reverse indexing).
  • If end argument is omitted, undefined, or cannot be converted to a number (using Number(end)), or if end >= str.length, slice() extracts to the end of the string.
  • SYNTAX : slice(start [, end])

    
    // slice() method returns the substring
    
    let city = "Mumbai"
    city.slice(0,3)    // returns first three characters in string "Mumbai"
    
    
    OUTPUT
    
    'Mum'
    
    

    It's important to note that, JavaScript won't raise an Error when you try to slice between boundaries that fall outside the starting or ending boundaries of a string.

    
    // slice() boundaries that fall outside starting or ending 
    
    let city = "Mumbai"
    city.slice(0,100)    // returns entire string
    
    
    OUTPUT
    
    'Mumbai'
    
    

    when you try to get a slice in which the entire range is out of bounds, Instead of raising an error, JavaScript returns the empty string ("").

    
    //  slice() method's entire range is out of bounds
    
    let city = "Mumbai"
    city.slice(6,10)        // returns the empty string ''
    
    
    OUTPUT
    
    ''
    
    
    
    // slice() method with no second arguments
    
    let stadium = "Maracanã"
    stadium.slice(4)     // start at position index 4, goes to end of string
    
    
    OUTPUT
    
    'canã'
    
    
    
    // slice() method with negative values for start/end argument
    
    let stadium = "Maracanã"
    stadium.slice(-8,-4)     // start at 8th position from right, end at 4th from right
    
    
    OUTPUT
    
    'Mara'
    
    
    
    // slice() method with no arguments
    // copying the entry string
    
    let stadium = "Maracanã"
    let newStadium = stadium.slice()     // return entire string
    console.log(newStadium)
    
    
    OUTPUT
    
    Maracanã
    
    

    String Methods

  • JavaScript allows us to work with primitives (string, number, boolean, bigint, symbol) as if they were objects. They also provide methods to call as such.
  • In JavaScript these built-in methods / functions of these object, can perform actions or commands on itself.
  • We call methods with a period and then method name. Methods are in the form: object.method(parameters)
  • Here, parameters are extra arguments we can pass into the method.
  • JavaScript has many extremely useful string functions/methods; here are a few of them:

    1.  (1). slice() :

      returns part of the string from start to end(but not including). If there is no second argument, then slice() goes till the end of the string. slice() also allows for negative values for start and end arguments, which means the position is counted from the string end (i.e. reverse indexing).
      If end parameter is omitted, undefined, or cannot be converted to a number (using Number(end)), or if end >= str.length, slice() extracts to the end of the string.

      SYNTAX : slice(start [, end])


    2. 
      // slice() method returns the substring
      
      let city = "Mumbai"
      
      // returns first three characters in string "Mumbai"
      city.slice(0,3)    
      
      
      OUTPUT
      
      'Mum'
      
      
    3.  (2). substring() :

      returns a new string containing characters of the calling string from (or between) the specified index (or indices). The difference between slice() & substring() is that start and end values less than 0 are treated as 0 in substring().
      If end parameter is omitted, substring() extracts characters to the end of the string.

      SYNTAX : substring(start [, end])


    4. 
      // substring() new string containing characters
      
      let city = "Mumbai"
      
      // returns last three characters in string "Mumbai"
      city.substring(3,6)    
      
      
      OUTPUT
      
      'bai'
      
      
    5.  (3). substr() :

      returns a portion of the string, starting at the specified index and extending for a given number of characters (length) afterwards. The difference between slice() & substr() is that the second parameter specifies the length of the extracted part.
      If length is omitted or undefined, or if start + length >= str.length, substr() extracts characters to the end of the string.

      SYNTAX : substr(start [, length])


    6. 
      // substr() returns a portion of the string
      
      let city = "Newyork"
      
      // returns first three chars in string "Newyork"
      city.substr(0,3)    
      
      
      OUTPUT
      
      'New'
      
      
    7.  (4). replace() :

      returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged. By default, the replace() method is case sensitive.

      SYNTAX : replace(pattern, replacement)


    8. 
      // replace() replaces a pattern (string) with another
                    
      let academy = "Skillzam - Learn without limits!"
      academy.replace('-','=>')
      
      
      OUTPUT
      
      'Skillzam => Learn without limits!'
      
      
      
      // replace() replaces a pattern (RegExp) with string
      // Regular expressions are written without quotes
      
      let goat = "Ronaldo is the GOAT in football!"
      
      // regular Expression -  /i flag (case-insensitive)
      const regex = /ronaldo/i;   
      goat = goat.replace(regex, 'Messi');
      console.log(goat)
      
      
      OUTPUT
      
      Messi is the GOAT in football!
      
      
    9.  (5). replaceAll() :

      returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged. If pattern is a regex, then it must have the global /g flag set, or a TypeError is thrown.

      SYNTAX : replaceAll(pattern, replacement)


    10. 
      // replaceAll() replaces a string with string
      
      let iFeel = 'I love cricket. Most popular sport is "cricket".'
      iFeel = iFeel.replaceAll("cricket","football");
      console.log(iFeel)
      
      
      OUTPUT
      
      I love football. Most popular sport is "football".
      
      
      
      // replaceAll() replaces a RegExp with string
      // Regular expressions are written without quotes
      
      let whatIfeel = 'I love cricket. Cricket is a team sport. Most popular sport is "cricket".'
      
      // regular expression - /g flag (global match)
      whatIfeel = whatIfeel.replaceAll(/Cricket/g,"Football");    
      whatIfeel = whatIfeel.replaceAll(/cricket/g,"football");
      console.log(whatIfeel)
      
      
      OUTPUT
      
      I love football. Football is a team sport. Most popular sport is "football".
      
      
    11.  (6). toUpperCase() :

      returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). This method does not affect the value of the string itself since JavaScript strings are immutable.

      SYNTAX : toUpperCase()


    12. 
      // toUpperCase() - make string upper-case
      
      const academy = "Skillzam - Learn without limits!"
      academy.toUpperCase()
      
      
      OUTPUT
      
      'SKILLZAM - LEARN WITHOUT LIMITS!'
      
      
    13.  (7). toLowerCase() :

      returns the value of the string converted to lower case. toLowerCase() does not affect the value of the original string itself.

      SYNTAX : toLowerCase()


    14. 
      // toLowerCase() - make string lower-case 
      
      const pangram = "The quick brown FOX jumps over the lazy DOG."
      const lowerPangram = pangram.toLowerCase()
      console.log(lowerPangram)
      
      
      OUTPUT
      
      the quick brown fox jumps over the lazy dog.
      
      
    15.  (8). trim(), trimStart(), trimEnd() :

      removes whitespace from both sides of a string and returns a new string, without modifying the original string. To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

      SYNTAX :
      trim()
      trimStart()
      trimEnd()


    16. 
      // trim() - trimStart() - trimEnd()
      // removes whitespace 
      
      let fastestBird = "    Peregrine Falcon is the fastest bird in the world.    "
      
      let trimBird = fastestBird.trim()  // removes whitespace from both sides of string
      console.log(`${trimBird}`)
      
      let trimEndBird = fastestBird.trimEnd() // removes whitespace from End of string only 
      console.log(`${trimEndBird}`)
      
      fastestBird.trimStart()            // removes whitespace from start of string only
      
      
      OUTPUT
      
      Peregrine Falcon is the fastest bird in the world.
          Peregrine Falcon is the fastest bird in the world.
      'Peregrine Falcon is the fastest bird in the world.    '
      
      
    17.  (9). padStart(), padEnd() :

      pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. In padStart(), padding is applied from the start of the current string. In padEnd(), padding is applied from the end of the current string. The default value for padString parameter is unicode "space" (" ") , character (U+0020).

      SYNTAX :
      padStart(targetLength [, padString])
      padEnd(targetLength [, padString])


    18. 
      // padStart() - pads start of the current string
      
      // Demo1 : padStart()
      const numStart = '7';
      console.log(numStart.padStart(3, '0'));  // string output: 007
       
      // Demo2 : padStart() 
      const cardNumber = '4321987612346789';
      const lastFour = cardNumber.slice(-4);
      const cardMask = lastFour.padStart(cardNumber.length, '*');
      console.log(cardMask);                  // string output: ************6789
      
      
      OUTPUT
      
      007
      ************6789
      
      
      
      // padEnd() - pads end of the current string
      
      // Demo1 : padEnd()
      const numEnd = '7';
      console.log(numEnd.padEnd(3, '0'));  // string output: 700
      
      // Demo2 : padEnd() 
      const cellNumber = '7173334444';
      const firstThree = cellNumber.slice(0,3);
      const cellMask = firstThree.padEnd(cellNumber.length, '*');
      console.log(cellMask);               // string output: 717*******
      
      
      OUTPUT
      
      700
      717*******
      
      
    19.  (10). at() :

      returns the character at a specified index (position) in a string. This method allows for positive and negative integers as parameters. Negative integers count back from the last string character.

      SYNTAX : at(index)


    20. 
      // at() - returns the character at a specified Index
      // Example of VIN - vehicle identification number
      
      let vin = "1G8MB35B48Y105252"     // 17 charaters VIN 
      const countryID = vin.at(0);      // returns character at '0' index position
      console.log("Country Code is : " + countryID)
      
      
      OUTPUT
       
      Country Code is : 1
      
      
    21.  (11). charCodeAt() :

      returns the unicode of the character at a specified index in a string. The return value is a integer between 0 and 65535 representing the UTF-16 code unit

      SYNTAX : charCodeAt(index)


    22. 
      // charCodeAt() - returns unicode of character at specified index
      
      let holdingCompany = "Alphabet Inc."    
      const utf16 = holdingCompany.charCodeAt(0);     // returns unicode 'A'
      console.log(utf16)
      
      
      OUTPUT
      
      65
      
      
    23.  (12). split() :

      method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
      There are two arguments separator and limit. separatoris a pattern describing where each split should occur. limit is a non-negative integer specifying a limit on the number of substrings to be included in the array.

      SYNTAX : split(separator [, limit])


    24. 
      // split() - returns the array
      // Example 1
      
      let text = 'She sells seashells on the seashore.'
      
      const wordsArray = text.split(' ') // returns array of words
      console.log(wordsArray)       
      console.log(wordsArray[2])     
      
      
      OUTPUT
      
      ['She', 'sells', 'seashells', 'on', 'the', 'seashore.']
      seashells
      
      
      
      // split() - returns the array
      // Example 2
      
      let text = 'She sells seashells on the seashore.'
      
      const charArray = text.split(''); // returns array of single characters
      console.log(charArray) 
      console.log(charArray[1])
        
      
      OUTPUT
      
      ['S', 'h', 'e', ' ', 's', 'e', 'l', 'l', 's', ' ', 's', 'e', 'a', 's', 'h', 'e', 'l', 'l', 's', ' ', 'o', 'n', ' ', 't', 'h', 'e', ' ', 's', 'e', 'a', 's', 'h', 'o', 'r', 'e', '.']
      h
      
      
      
      // split() - returns the array
      // Example 3
      
      let text = 'She sells seashells on the seashore.'
      const newText = text.split();     // returns array with single "text" string
      console.log(newText);
      
      
      OUTPUT
      
      ['She sells seashells on the seashore.']
      
      
    25.  (13). indexOf(), lastIndexOf() :

      searches the entire calling string, and returns the index of the first occurrence of the specified substring. If the searchString not found, then the method returns -1. The second argument position is a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

      lastIndexOf() method returns the index of last occurrence of a specified text in a string. lastIndexOf() return -1 if the text is not found. The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is position, the search starts at that position index, and searches to the beginning of the string.

      The difference between search() and indexOf() is search() does not have second position argument whereas indexOf() cannot take regular expressions as search values.

      SYNTAX :
      indexOf(searchString [, position])
      lastIndexOf(searchString [, position])


    26. 
      // indexOf() returns index of first occurrence of specified substring
      // NOT specifying the second argument "position" will default to 0
      
      let vibgyor = "violet indigo blue green yellow orange red"
      
      const poistionIndigo = vibgyor.indexOf('indigo')   // 'indigo' is at index 7
      console.log("Index position where 'indigo' was found is " + poistionIndigo)
       
      const poistionBrown = vibgyor.indexOf('brown')     // 'brown' does not exists
      console.log("Index position where 'brown' was found is " + poistionBrown)
      
      
      OUTPUT
      
      Index position where 'indigo' was found is 7
      Index position where 'brown' was found is -1
      
      
      
      // indexOf() returns index of occurrence of specified substring
      // specifying the second argument "position"
      
      let searchWhale = "The biggest whale in the world is Antarctic blue whale."
      
      // negative position' argument will be assumed as 0 index position
      const firstWhale = searchWhale.indexOf('whale',-15)   
      console.log("Index position where 'whale' was found is " + firstWhale)
        
      // 'position' argument is specified as 17 index position
      const secondWhale = searchWhale.indexOf('whale',17)  
      console.log("Index position where 'whale' was found is " + secondWhale)
      
      
      OUTPUT
      
      Index position where 'whale' was found is 12
      Index position where 'whale' was found is 49
      
      
      
      // lastIndexOf() returns index of last occurrence of specified substring
      
      let searchWhale = "The biggest whale in the world is Antarctic blue whale."
      
      const lastWhale = searchWhale.lastIndexOf('whale', searchWhale.length)    
      console.log("Index position of last occurance of 'whale' is " + lastWhale)
        
      
      OUTPUT
      
      Index position of last occurance of 'whale' is 49
      
      
    27.  (14). search() :

      executes a search for a match between a regular expression and String object i.e. this method searches a string or a regular expression in a String Object and returns the position of the match. If not match found, then the method will return -1.

      The difference between search() and indexOf() is search() does not have second position argument whereas indexOf() cannot take regular expressions as search values.

      SYNTAX :
      search(searchString)
      search(regex)


    28. 
      // search() returns the position of first match of string/RegExp
      // Argument passed is a "string"
      
      const academy = "Skillzam - Learn without limits!"
      let matchIndex = academy.search('Learn')  // search for first match of 'Learn' 
      
      console.log(`The first match for searchString occurs at index position ${matchIndex}`)
      
      
      OUTPUT
      
      The first match for searchString occurs at index position 11
      
      
      
      // search() returns the position of first match of string/RegExp
      // Argument passed is a "Regular Expression"
      
      const academy = "Skillzam - Learn without limits!"
      
      // Any character which is not word or whitespace
      const regex = /[^\w\s]/g                
      
      // Search for first match of regex '-'
      let matchIndex = academy.search(regex)  
      let matchChar = academy[academy.search(regex)]
      
      console.log(`The first match for character "${matchChar}" is at index position ${matchIndex}`)
      
      
      OUTPUT
      
      The first match for character "-" is at index position 9
      
      
    29.  (15). includes() :

      performs a case-sensitive search to determine whether one string may be found within another string, returning boolean values true or false as appropriate.

      SYNTAX : includes(searchString [, position])


    30. 
      // includes() returns true/false depending on the strind found
      // NOT specifying the second argument "position" will default to 0
      
      const rhyme = "Baa, baa, black sheep, have you any wool?"
      const isExists = rhyme.includes('baa')   // 'baa' exits and returns true
      console.log(isExists)
      
      
      OUTPUT
      
      true
      
      
      
      // includes() returns true/false depending on the strind found
      // specifying the second argument "position"
      
      const rhyme = "Baa, baa, black sheep, have you any wool?"
      
      // Check if a string includes "Baa" - start at position 10
      let isExists = rhyme.includes('Baa',10)   
      console.log(isExists)
      
      
      OUTPUT
      
      false
      
      
    31.  (15). startsWith() :

      determines whether a string begins with the characters of a specified string, returning boolean values of either true or false as appropriate. If the position argument is not specified, then it will default to 0

      SYNTAX : startsWith(searchString [, position])


    32. 
      // startsWith() returns whether a string begins with the characters
      
      const mountain = "Mount Kilimanjaro is the highest mountain in Africa"
      let doesBegin = mountain.startsWith('Mount')
      console.log(doesBegin)
      
      
      OUTPUT
      
      true
      
      
      
      // startsWith() returns whether a string begins with the characters
      // specifying the second argument "position"
      
      const mountain = "Mount Kilimanjaro is the highest mountain in Africa"
      
      // Check if a string starts with "Kili" - start at position 10
      let doesBegin = mountain.startsWith('Kili', 10)    
      console.log(doesBegin)   // specify position as '6', it will return true
      
      
      OUTPUT
      
      false
      
      
    33.  (16). endsWith() :

      determines whether a string ends with the characters of a specified string, returning boolean values of either true or false as appropriate. If the position argument is not specified, then it will default to 0

      SYNTAX : endsWith(searchString [, position])


    34. 
      // endsWith() returns whether a string ends with the characters
      
      const mountain = "Mount Kilimanjaro is the highest mountain in Africa"
      let doesEnd = mountain.endsWith('Africa')
      console.log(doesEnd)
      
      
      OUTPUT
      
      true
      
      
      
      // endsWith() returns whether a string ends with the characters
      // specifying the second argument "position"
      
      const mountain = "Mount Kilimanjaro is the highest mountain in Africa"
      
      // Check if first 32 characters of a string ends with "highest"
      let doesEnd = mountain.endsWith('highest', 32)    
      console.log(doesEnd)      
      
      
      OUTPUT
      
      true
      
      
    35.  (17). raw() :

      static method is a tag function of template literals. This is similar to the r prefix in Python, or the @ prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. ${amount}) are processed, but escape sequences (e.g. \n) are not.

      SYNTAX :
      raw(strings, ...substitutions)
      raw`templateString`


    36. 
      // raw() returns raw string form of a given template literal
      // substitutions are processed, but escape sequences are not
      
      const filePath = `C:\Users\Skillzam\Desktop\code\script.js`
      console.log(filePath)    // Observer the escape characters being ommited
      
      const scriptPath = String.raw`C:\Users\Skillzam\Desktop\code\script.js`
      console.log(`JavaScript file is located at ${scriptPath}`)
      
      
      OUTPUT
      
      C:UsersSkillzamDesktopcodescript.js
      JavaScript file is located at C:\Users\Skillzam\Desktop\code\script.js
      
      

      Notice the first argument is an object with a raw property, whose value is an array-like object (with a length property and integer indexes) representing the separated strings in the template literal. The rest of the arguments are the substitutions. Since the raw value can be any array-like object, it can even be a string!
      For example, 'ABCD' is treated as ['A', 'B', 'C', 'D']. The following is equivalent to `A${0}B${1}C${2}D`

      
      // raw() returns raw string form of a given template literal
      // substitutions are processed 
      
      let text = String.raw({ raw: "ABCD" }, 0, 1, 2);  
      console.log(text)
      
      
      OUTPUT
      
      A0B1C2D
      
      
    37.  (18). repeat() :

      constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. The argument count indicating the number of times to repeat the string.

      SYNTAX : repeat(count)


    38. 
      // repeat() returns a string with a number of copies
      // Example 1
      
      let word = 'buz'
      let newWord = word + 'z'.repeat(5)
      console.log(newWord)
      
      
      OUTPUT
      
      buzzzzzz
      
      
      
      // repeat() returns a string with a number of copies
      // Example 2
      
      let website = 'w'.repeat(3).concat('.workzam.com')
      console.log(website)
      
      
      OUTPUT
      
      www.workzam.com
      
      
      
      // repeat() returns a string with a number of copies
      // Example 3
      
      let academy = 'Skillzam '
      academy = academy.repeat(3) 
      console.log(academy)
      
      
      OUTPUT
      
      Skillzam Skillzam Skillzam 
      
      
    39.  (19). toString() :

      returns a string representing the specified string value.

      SYNTAX : toString()


    40. 
      // toString() returns a string representation
      
      // new keyword will create a object from a constructor function (String())
      const academyObj = new String('Skillzam'); 
      console.log(academyObj);     
      
      const academy = academyObj.toString()
      console.log(academy);
      
      
      OUTPUT
      
      String {'Skillzam'}
      Skillzam
      
      
    41.  (20). valueOf() :

      returns the primitive value of a String object.

      SYNTAX : valueOf()


    42. 
      // valueOf() returns the primitive value
      
      const jsObj = new String('JavaScript is everywhere.');
      console.log(jsObj);
      console.log(jsObj.valueOf());
      
      
      OUTPUT
      
      String {'JavaScript is everywhere.'}
      JavaScript is everywhere.
      
      
    43.  (21). match() :

      method retrieves the result of matching a string against a regular expression i.e it returns an array containing the results of matching a string against a string or a regular expression. If a regular expression does not include the g modifier (global search), match() will return only the first match in the string.

      SYNTAX :
      match(searchString)
      match(regex)


    44. 
      // match() return array containing results of matching string
      // Argument passed is a "string"
                      
      let tongueTwister = `Betty Botter bought a bit of butter, 
                           but the bit of butter was bitter, 
                           so Betty Botter bought a bit of better butter, 
                           to make the bit of bitter butter better.`
      
      const matchResult = tongueTwister.match('butter')
      console.log(matchResult)
      
      
      OUTPUT
      
      ['butter']
      
      
      
      // match() return array containing results of matching Regex
      // Argument passed is a "Regex" with 'g' modifier (global search )
                      
      let tongueTwister = `Betty Botter bought a bit of butter, 
                           but the bit of butter was bitter, 
                           so Betty Botter bought a bit of better butter, 
                           to make the bit of bitter butter better.`
      
      const regex = /butter/g    // regex with g modifier (global search )
      const matchResult = tongueTwister.match(regex)
      console.log(matchResult)
      
      
      OUTPUT
      
      ['butter', 'butter', 'butter', 'butter']
      
      
      
      // match() return array containing results of matching Regex
      // Argument passed is a "Regex"  
      // using global(g) and ignoreCase(i) flags with match()
      
      let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
      const regex = /[A-D]/gi        // regex with global & ignoreCase flags
      const matchResults = alphabets.match(regex);
      console.log(matchResults)
      
      
      OUTPUT
      
      ['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
      
      
    45.  (22). matchAll() :

      returns an iterator of all results matching a string against a "string or regular expression" including capturing groups. If the parameter is a regular expression, the global flag g must be set, otherwise a TypeError is thrown.

      SYNTAX :
      matchAll(searchString)
      matchAll(regex)


    46. 
      // matchAll() return iterator of all results matching a "string"
      // Argument passed is a "string"  
                      
      let tongueTwister = `Betty Botter bought a bit of butter, 
                           but the bit of butter was bitter, 
                           so Betty Botter bought a bit of better butter, 
                           to make the bit of bitter butter better.`
      
      const iterator = tongueTwister.matchAll("butter")    // string as argument
      console.log(iterator)
      
      const resultArray = Array.from(iterator)
      console.log(resultArray)
      
      
      OUTPUT
      
      [object RegExp String Iterator]
      [['butter'], ['butter'], ['butter'], ['butter']]
      
      
      
      // matchAll() return iterator of all results matching a "regex"
      // Argument passed is a "Regex" with 'g' modifier (global search )
                      
      let tongueTwister = `Betty Botter bought a bit of butter, 
                           but the bit of butter was bitter, 
                           so Betty Botter bought a bit of better butter, 
                           to make the bit of bitter butter better.`
      
      const regex = /butter/g    // regex with g modifier (global search )
      const iterator = tongueTwister.matchAll(regex)
      console.log(iterator)
      
      const resultArray = Array.from(iterator)
      console.log(resultArray)
      
      
      OUTPUT
      
      [object RegExp String Iterator]
      [['butter'], ['butter'], ['butter'], ['butter']]
      
      

    boolean

  • boolean is a built-in primitive data type in JavaScript.
  • Booleans represent one of two values: true or false.
  • When you compare two values, the expression is evaluated and JavaScript returns the Boolean answer
  • Booleans can also be constructed using the Boolean() object constructor.
  • Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean value — use Boolean as a function or a double NOT !! instead.
  • Booleans are often used in conditional testing.
  • Any numeric type is false if equal to zero or null, and true otherwise:
  • 
    // Boolean values numeric type
    
    Boolean(2017)              // true
    Boolean(-123)              // true
    Boolean(2.728281)          // true
    Boolean(Infinity)          // true
    Boolean(-Infinity)         // true
    Boolean(0)                 // false
    Boolean(NaN)               // false
    
    
  • For strings, Boolean() is false for empty strings and true otherwise:
  • 
    // Boolean values for string type
    
    Boolean("Workzam")         // true
    Boolean("2023")            // true
    Boolean('')                // false
    
    
    
    // Boolean values for other values
    
    Boolean(true)              // true  
    Boolean([12,24,36])        // true  
    Boolean({name: 'Brendan'}) // true  
    Boolean([])                // true  
    Boolean({})                // true  
    Boolean()                  // false
    Boolean(false)             // false
    Boolean(null)              // false
    Boolean(undefined)         // false
    
    

    Truthy & Falsy values

  • All JavaScript values have an inherent truthyness or falsyness about them.
  • Any object can be tested for "truth value", for use in an if or else if or while condition or as operand of the Boolean operations.
  • Falsy values listed below, rest all are truthy:
    1.     ➤  false
    2.     ➤  0 (zero)
    3.     ➤  NaN
    4.     ➤  '' (empty string)
    5.     ➤  null
    6.     ➤  undefined
  • In JavaScript, a nullish value is the value which is either null or undefined. Nullish values are always falsy.
  • 
    // Falsy values
    
    Boolean(false)             // false
    Boolean(0)                 // false
    Boolean(NaN)               // false
    Boolean('')                // false
    Boolean(null)              // false
    Boolean(undefined)         // false
    
    

    Boolean Methods

    1.  (1). toString() :

      returns a string of either true or false depending upon the value of the object.

      SYNTAX : toString()


    2. 
      // toString() returns string of either true or false
      
      // new keyword will create a object from a constructor function (Boolean())
      const boolAcademyObj = new Boolean('Skillzam'); 
      console.log(boolAcademyObj);     
      
      const academy = boolAcademyObj.toString()
      console.log(academy)
      console.log(typeof(academy))
      
      
      OUTPUT
      
      Boolean {true}
      true
      string
      
      
    3.  (2). valueOf() :

      returns the primitive value of a Boolean object.

      SYNTAX : valueOf()


    4. 
      // valueOf() returns the primitive value
      
      const boolworkzamObj = new Boolean('Workzam')
      console.log(boolworkzamObj)
      
      const techHire = boolworkzamObj.valueOf()
      console.log(techHire)
      console.log(typeof(techHire))
      
      
      OUTPUT
      
      Boolean {true}
      true
      boolean
      
      

    undefined

  • undefined is a built-in primitive data type in JavaScript.
  • In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
  • It is a property of the global object. That is, it is a variable in global scope.
  • Any variable can be emptied, by setting the value to undefined.
  • An empty value has nothing to do with undefined. An empty string has both a legal value and a type string
  • Boolean value of undefinedis false.
  • 
    // undefined datatype
    
    let studentCount;
    typeof(studentCount)
    
    
    OUTPUT
    
    'undefined'
    
    
    
    // undefined boolean value
    
    let btc
    Boolean(btc)
    
    
    OUTPUT
    
    false
    
    
    
    // undefined datatype used in "if"
    
    let premium;
    if (typeof(premium) === "undefined") {
      console.log("Premium value not assigned.")
    }
    typeof(premium)
    
    
    OUTPUT
    
    Premium value not assigned.
    'undefined'
    
    
    
    // undefined - any variable can be emptied
    
    let price = 200
    price = undefined    // NOT recommend doing this
    console.log(price)
    
    
    OUTPUT
    
    Premium value not assigned.
    'undefined'
    
    

    null

  • null is a built-in primitive data type in JavaScript.
  • null is a special value which represents “nothing”, “empty” or “value unknown”.
  • null is not the same as 0, false, or an empty string. null is a data type of its own.
  • null value represents the intentional absence of any object value. It is treated as falsy for boolean operations.
  • null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object.
  • 
    // null Datatype
    
    const studentCount = null
    console.log(studentCount)
    console.log(typeof(studentCount))      // typeof null
    console.log(Boolean(studentCount))     // Boolean value of null
    
    
    OUTPUT
    
    null
    object
    false 
    
    

    Difference between null and undefined

    
    //null and undefined
    
    typeof null               // "object" (not "null" for legacy reasons)
    typeof undefined          // "undefined"
    null === undefined        // false
    null  == undefined        // true
    null === null             // true
    null  == null             // true
    !null                     // true
    isNaN(1 + null)           // false
    isNaN(1 + undefined)      // true
    
    

    bigint

  • bigint is a built-in primitive data type in JavaScript.
  • bigint values represent numeric values which are too large to be represented by the number primitive.
  • bigint is created by appending n to the end of an integer literal, or by calling the BigInt() function (without the new operator) and giving it an integer value or string value.
  • bigint variables can also be created using the BigInt() object constructor method. BigInt() can only be called without new. Attempting to construct it with new throws a TypeError. Syntax : BigInt(value)
  • bigint value cannot be used with methods in the built-in Math object like the number datatype.
  • bigint value cannot be mixed with a number value in operations.
  • 0n is falsy, everything else is truthy.
  • bigint value is not strictly equal to a number value. Example : 1n !== 1 , this is true
  • bigint values and number values may be mixed in arrays and sorted.
  • bigint value follows the same conversion rules as number when:
    1.  (1). it is converted to a boolean: via the Boolean() function
    2.  (2). when used with logical operators ||, &&, and !
    3.  (3). within a conditional test like an if statement
  • 
    //  bigint explained in examples
    //  Example 1 
    
    // create bigint variable
    const largeNum = 9007199254740992n     // (Number.MAX_SAFE_INTEGER + 1) 
    console.log(largeNum)                  // 9007199254740992n
    console.log(typeof(largeNum))          // bigint
    
    
    
    //  bigint explained in examples
    //  Example 2
    
    // typeof Operator
    typeof(999n) === 'bigint'              // true
    typeof(Object(999n)) === 'object'      // true
    
    
    
    //  bigint explained in examples
    //  Example 3
    
    // Operators
    let bigNum = BigInt(9007199254740992)  // BigInt() : 9007199254740992n
    const bigNumPlus = bigNum + 7n         // Addition : 9007199254740999n
    const bigNumMinus = bigNum - 7n        // Substract : 9007199254740992n
    const bigNumProd = bigNum * 2n         // Multiply : 18014398509481984n
    const bigNumBy = 10n / 3n              // Divide : 3n (decimal places are truncated)
    const bigNumMod = bigNum % 10n         // Mod : 2n
    const bigNumPow = 2n ** 53n            // Power : 9007199254740992n
    
    
    
    //  bigint explained in examples
    //  Example 4
    
    // Comparisons
    9n === 9                // false
    9n == 9                 // true
    9n > 99                 // false   
    9n <= 9                 // true
    
    // Conditionals 
    !9n                     // false
    !0n                     // true
    
    
    
    //  bigint explained in examples
    //  Example 5
    
    // Array 
    mixedArray = [8, 2n, 0, -6n, 10, 0n]   // BigInt & Number values may be mixed
    
    

    Bigint Methods

    1.  (1). toString() :

      returns a string representing this BigInt value in the specified radix (base).

      SYNTAX : toString(radix)


    
    // toString() returns string representing BigInt value
    // Without "radix" argument
    
    // number dataype with big Value
    const hugeNumber = 1234567890123456789012345678901234567890  
    console.log(`hugeNumber value is ${hugeNumber} and datatype is ${typeof(hugeNumber)}`)
    
    // create a bigint object from a constructor function - Bigint()
    const bigintNumObj = BigInt(hugeNumber)     
    console.log(`bigintNumObj value is ${bigintNumObj} and datatype is ${typeof(bigintNumObj)}`)
    
    // apply toString() method to bigintNumObj
    const largeNumber = bigintNumObj.toString()   
    console.log(`largeNumber value is ${largeNumber} and datatype is ${typeof(largeNumber)}`)
    
    
    OUTPUT
    
    hugeNumber value is 1.2345678901234568e+39 and datatype is number
    bigintNumObj value is 1234567890123456846996462118072609669120 and datatype is bigint
    largeNumber value is 1234567890123456846996462118072609669120 and datatype is string
    
    
    
    // toString() returns string representing BigInt value
    // with "radix" argument
    
    const bigN = 9007199254740991n
    bigN.toString(2)   // '11111111111111111111111111111111111111111111111111111'
    bigN.toString(10)  // '9007199254740991'
    bigN.toString(16)  // '1fffffffffffff'
    
    
    1.  (2). valueOf() :

      returns the wrapped primitive value of a BigInt object.

      SYNTAX : bigIntObj.valueOf()


    
    // valueOf() returns the primitive value
    
    // BigInt variable created by adding 'n' at the end
    const largeNum = 1234567890123456789012345678901234567890n   
    
    // Using BigInt() method, BigInt variable created 
    const bigNum = BigInt(9007199254740992)   
    
    const largeNumValue = largeNum.valueOf()
    const bigNumValue = bigNum.valueOf()
    
    console.log(largeNumValue)          // 1234567890123456789012345678901234567890n
    console.log(typeof(largeNumValue))  // bigint
    console.log(bigNumValue)            // 9007199254740992n
    console.log(typeof(bigNumValue))    // bigint
    
    
    OUTPUT
    
    1234567890123456789012345678901234567890n
    bigint
    9007199254740992n
    bigint
    
    

    symbol

  • symbol is a built-in primitive data type in JavaScript.
  • symbol represents a unique "hidden" identifier that no other code can accidentally access.
  • All seven primitive types contain only a single value, whereas object are used to store collections of data. The symbol type is used to create unique identifiers for objects.
  • symbol type doesn't have a literal form. To create a new symbol, you use the global Symbol() method/function.Symbol() function creates a new unique value each time you call it. The function accepts a description as an optional argument. The description argument will make your symbol more descriptive. Attempting to construct it with new throws a TypeError.

    Syntax : Symbol(description)
  • 
    // symbol DataType creation using Symbol() method
    // with 'description' argument as 'pid'
    
    const player = {
      fname: "Leo",
      lname: "Messi",
      position: "Forward" }
    
    let pid = Symbol('pid')   // description argument as 'pid'
    player[pid] = 98765;
    console.log('Player pid using Symbol: ' + player[pid])
    console.log('typeof(pid) is ' + typeof(pid))
    console.log('Player pid using Object: ' + player.pid)
                            
    
    OUTPUT
    
    Player pid using Symbol: 98765
    typeof(pid) is symbol
    Player pid using Object: undefined
    
    

    Shared Symbols in global registry

  • In the above example using the Symbol() function will create a Symbol pid whose value (98765) remains unique throughout the lifetime of the program.
  • ECMAScript provides you with a global symbol registry that allows you to share symbols globally.
  • Note that the "global Symbol registry" is only a fictitious concept and may not correspond to any internal data structurein the JavaScript engine — and even if such a registry exists, its content is not available to the JavaScript code, except through the for() and keyFor() methods.

  • Symbol.for(key)
    1.  (1). Symbol.for(key) method takes a string key as argument and returns a symbol value from the registry.
    2.  (2). To create a symbol that will be shared, use the Symbol.for() method instead of calling the Symbol() function.
    3.  (3). Symbol.for(key) method accepts a single parameter that can be used for symbol's description.
    4.  (4). Symbol.for(key) method first searches for the symbol with the key in the global symbol registry. It returns the existing symbol if there is one. Otherwise, the Symbol.for(key) method creates a new symbol, registers it to the global symbol registry with the specified key, and returns the symbol.

  • Symbol.keyFor(symbol)
    1.  (1). Symbol.keyFor() method takes a symbol value and returns the string key corresponding to it.
    2.  (2). To get the key associated with a symbol, you use the Symbol.keyFor() method.
    3.  (3). If a symbol that does not exist in the global symbol registry, the Symbol.keyFor() method returns undefined.
  • 
    // Symbol.for() method 
     
    let aadhar = Symbol.for('aadhar')
    let citizenID = Symbol.for('aadhar')
    
    console.log(aadhar)                    // Symbol(aadhar)    
    console.log(citizenID)                 // Symbol(aadhar)   
    console.log(aadhar === citizenID)      // true
    console.log(typeof aadhar)             // symbol
    console.log(typeof citizenID)          // symbol
                            
    
    
    // Symbol.keyFor() method 
      
    let keyAadhar = Symbol.keyFor(aadhar)
    let keyCitizenID = Symbol.keyFor(citizenID)
    
    console.log(keyAadhar)                // aadhar   
    console.log(keyCitizenID)             // aadhar 
    
    

    Symbol Methods

    1.  (1). toString() :

      returns a string containing the description of the Symbol.

      SYNTAX : toString()


    
    // toString() returns string containing description of Symbol
    
    Symbol('skill').toString()     // "Symbol(skill)"
    Symbol.iterator.toString()     // "Symbol(Symbol.iterator)
    Symbol.for('zam').toString()   // "Symbol(zam)"
    
    
    1.  (2). valueOf() :

      method returns the primitive value of a Symbol object.

      SYNTAX : valueOf()


    
    // valueOf() returns the primitive value of Symbol
    
    const symbolSSN = Symbol('ssn')
    typeof (symbolSSN)                  // "symbol"
    symbolSSN.valueOf()                 // Symbol(ssn)
    typeof Object(symbolSSN)            // "object"
    typeof Object(symbolSSN).valueOf()  // "symbol"
    
    

    Arrays

  • Arrays are simple data structures.
  • Arrays are Ordered collections of values.
  • Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list.
  • It is a common practice to declare arrays with the const keyword. It does NOT define a constant array. It defines a constant reference to an array.
  • Arrays are mutable by default i.e. their properties and elements can be changed without reassigning a new value.
  • Arrays are resizable and can contain a mix of different data types.
  • Arrays are zero-indexed i.e. the first element of an array is at index 0, the second is at index 1, and so on .
  • the length property will determine the length of an array.
  • Arrays have no fixed size, meaning we don't have to specify how big a array will be.
  • SYNTAX:
    const arrayName = [item1, item2, item2, ...];

    
    // Array Indexing Example
    
    const academy = ['S','K','I','L','L','Z','A','M']
    console.log("type of academy array is " + typeof(academy))
    console.log("Length of academy array is " + academy.length)
    console.log("The element at the '0' index is " + academy[0])
    
    
    OUTPUT
    
    type of academy array is object
    Length of academy array is 8
    The element at the '0' index is S
    
    
    list Indexing slicing
    
    // Create array of English Vowels (string)
    // using array literals
    
    const vowels = ['a', 'e', 'i', 'o', 'u']
    console.log(vowels)
    
    
    OUTPUT
    
    ['a', 'e', 'i', 'o', 'u']
    
    
    
    // Create array of Fibonacci series (number)
    // using array literals
    
    const fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    console.log(fibo)
    
    
    OUTPUT
    
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    
    
    // Create array of elements of different datatype
    
    let three = "Three";
    const mixData = [];         // creating an empty array
    
    // Adding elements to array
    mixData[0] = 'One'          // Array element is a string
    mixData[1] = 2              // Array element is a integer
    mixData[2] = three          // Array element is a variable
    mixData[3] = [4, "five", 6] // Array element is an array
    mixData[4] = 7.8            // Array element is a decimal
    mixData[5] = {key:9}        // Array element is an object   
    
    console.log(mixData)
    
    
    OUTPUT
    
    ['One', 2, 'Three', [4, 'five', 6], 7.8, {key: 9}]
    
    

    Creating array

    Arrays may be created in several ways:

  • Using a pair of square brackets to denote the empty array and then add items by indexing: [ ]
  • Using array literals i.e. square brackets, separating items with commas: [a], [a, b, c]
  • Using a string method split(): 'SKILLZAM'.split('') returns ['S', 'K', 'I', 'L', 'L', 'Z', 'A', 'M']
  • Using the array constructor function Array(item1, item2, item2,...) or Array(arrayLength)
    Array() can be called with or without new keyword. Both create a new Array instance.
  • The constructor builds a array whose items are the same and in the same order as iterable's items.

    For example
    Array('a','b','c') returns ['a', 'b', 'c']

    Array(1, 2, 3) returns [1, 2, 3]

    If the only argument passed to the Array() constructor, is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with its length property.
    Array(3) returns [,,]

    
    // Creating array using pair of square brackets 
    // Example: array of single digit even number
    
    // creating Empty Array 
    const arrayOne = []      
    
    // Adding elements/items using index
    arrayOne[0] = 6
    arrayOne[1] = 28
    arrayOne[2] = 496
    arrayOne[3] = 8128
    
    console.log(arrayOne)
    
    
    OUTPUT
    
    [6, 28, 496, 8128]
    
    
    
    // Creating arrays using different ways
    // use of 'new' keyword is optional
    
    const arrayTwo = [[1],[2,3],[4,5,6]]       // array from square brackets, separating items with commas
    const arrayThree = new Array("WORKZAM")    // array from single string argument
    const arrayFour = new Array(9)             // empty array with length 9 
    const arrayFive = "ಅ,ಆ,ಇ,ಈ".split(',')  // array from string method split()
    console.log(arrayTwo)
    console.log(arrayThree)
    console.log(arrayFour)
    console.log(arrayFive)
                
    
    OUTPUT
    
    [[1],[2,3],[4,5,6]]
    ['WORKZAM']
    [,,,,,,,,]
    ['ಅ', 'ಆ', 'ಇ', 'ಈ']
    
    

    Working with array

  • Add item(s) to an array.
  • 
    // Add item to an array 
    
    const shoppingArray = ["tea", "coffee", "milk", "eggs"]
    shoppingArray[4] = "honey"
    console.log(shoppingArray)
    
    
    OUTPUT
    
    ['tea', 'coffee', 'milk', 'eggs', 'honey']
    
    

  • Modify item in an array.
  • 
    // Modify item in an array
    
    const shoppingArray = ["tea", "coffee", "milk", "eggs", "honey"]
    shoppingArray[4] = "bread"     // Change item from 'honey' to 'bread'
    console.log(shoppingArray)
    
    
    OUTPUT
    
    ['tea', 'coffee', 'milk', 'eggs', 'bread']
    
    

  • Remove array elements using the keyword delete .
    Using delete creates sparse array i.e. an array which the elements are not sequential, and they don't always start at 0.
    They are essentially Array's with "holes", or gaps in the sequence of their indices.
  • 
    // using "delete" remove item from array 
    
    const shoppingArray = ["tea", "coffee", "milk", "eggs", "bread"]
    delete shoppingArray[0]            // Remove the last item "honey" in the array
    console.log(shoppingArray)
    console.log(shoppingArray[0])      // deleted element at index(0) is removed 
    console.log(shoppingArray.length)  // no change in length of array 
    
    
    OUTPUT
    
    ['tea', 'coffee', 'milk', 'eggs']
    undefined
    5
    
    

  • Concatenation of arrays will return a string.
  • 
    // Concatenation of arrays
    
    const letters = ['A','B','C']
    const numbers = [1,2,3]
    let result = letters + numbers    // Concatenation using '+' operator
    console.log(result)
    console.log("type of 'result' is " + typeof(result))
    
    
    OUTPUT
    
    A,B,C1,2,3
    type of 'result' is string
    
    

    Nested array

  • JavaScript arrays support nesting.
  • This means we can have arrays within array.
  • Nested array is a multi-dimensional array.
  • We can think of multi-dimensional array as a table with rows (r) and columns (c).
  • Nested array

    For example: An array inside an array.

    
    // Matrix like structure using arrays
    
    const row1 = [1, 2, 3]
    const row2 = [4, 5, 6]
    const row3 = [7, 8, 9]
    
    // Nesting of arrays within a array 
    const matrixOne = [row1, row2, row3]
    console.log(matrixOne)
    
    
    OUTPUT
    
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    
    
    // Access first list item in matrix array
    
    matrixOne[0]
    
    
    OUTPUT
    
    [1, 2, 3]
    
    
    
    // access first element of first array item in matrix array
    
    matrixOne[0][0]
    
    
    OUTPUT
    
    1
    
    

    Basic Array Methods

  • JavaScript allows us to work with "arrays" data structures, as if they were objects. They also provide methods to call as such.
  • In JavaScript these built-in methods / functions of these object, can perform actions or commands on itself.
  • We call methods with a period and then method name. Methods are in the form: object.method(parameters)
  • Here, parameters are extra arguments we can pass into the method.
  • JavaScript has many extremely useful string functions/methods; here are a few of them:
  • (1)  pop()

  • removes (pops) the last element from an array and returns that element.
  • pop() is a mutating method i.e. it changes length of the array.

  • SYNTAX : pop()

    
    // pop() removes last element of an array
    
    const players = ["Sachin", "Dhoni", "Virat", "Zaheer", "Rahul"];
    const popped = players.pop();    // removes last element 'Rahul'
    console.log(popped)
    console.log(players)
                  
    
    OUTPUT
    
    Rahul  
    ['Sachin', 'Dhoni', 'Virat', 'Zaheer']
    
    

    (2)  push()

  • push() adds one or more elements to the end of an array.
  • It returns the new length of the array.
  • push() is a mutating method i.e. it changes length of the array.

  • SYNTAX : push(element1, element2,...)

    
    // push() adds new items to the end of an array
    // push() method with single 'item' as argument
    
    const capitalCities = ["NewDelhi", "NewYork", "London"]
    const arraylength = capitalCities.push("Istanbul")
    console.log(arraylength)
    console.log(capitalCities)
    
    
    OUTPUT
    
    4
    ['NewDelhi', 'NewYork', 'London', 'Istanbul']
    
    
    
    // push() adds new items to the end of an array
    // push() method with multiple 'items' as argument
                   
    const numbers = [12, 24, 45, 67]
    const arraylength = numbers.push(78, 89, 91)
    console.log(arraylength)
    console.log(numbers)
    
    
    OUTPUT
    
    7
    [12, 24, 45, 67, 78, 89, 91]
    
    

    (3)  shift()

  • removes first element from an array & returns the removed element.
  • pop() method has similar behavior to shift(), but applied to the last element in an array.
  • shift() is a mutating method i.e. it changes length of the array.
  • shift() method is often used in condition inside while loop.

  • SYNTAX : shift()

    
    // shift() removes first element from an array
    
    const players = ["Sachin", "Dhoni", "Virat", "Zaheer", "Rahul"];
    const shifted = players.shift(); // removes first element 'Sachin'
    console.log(shifted)
    console.log(players)
    
    
    OUTPUT
    
    Sachin
    ['Dhoni', 'Virat', 'Zaheer', 'Rahul']
    
    
    
    // shift() removes first element from an array
    // shift() method is used in 'while' loop
    
    const players = ['Messi', 'Neymar', 'Ronaldo', 'Benzema']
    
    // every iteration will remove next element from an array, until it is empty
    while (typeof (player = players.shift()) !== "undefined") {
      console.log(player)
    }
    
    console.log("The 'players' array contains ", players)
    
    
    OUTPUT
    
    Messi
    Neymar
    Ronaldo
    Benzema
    The 'players' array contains []
    
    

    (4)  unshift()

  • unshift() adds one or more elements to the beginning of an array and returns the new length of an array.
  • If multiple elements are passed as arguments, they are inserted in the exact same order they were passed.

  • SYNTAX : unshift(element1, element2,...)

    
    // unshift() adds one or more elements to beginning of Array
    
    const healthyFood = ['Avocado', 'Kiwi', 'Moringa']
    const arrayLen = healthyFood.unshift('Spinach', 'Kale', 'Collard')
    console.log(arrayLen)
    console.log(healthyFood)
    
    
    OUTPUT
    
    6
    ['Spinach', 'Kale', 'Collard', 'Avocado', 'Kiwi', 'Moringa']
    
    

    (5)  includes()

  • specifies whether an array includes a certain element, returning true or false as appropriate.
  • The optional argument fromIndex will specify from which index position should the search start.

  • SYNTAX : includes(element [, fromIndex])

    
    // includes() returns true if an array contains 'element'
    // Example contains one argument : 'element'
    
    const fishes = ['Catfish', 'Bass', 'Carp', 'Tuna', 'Salmon']
    let isExists = fishes.includes('Carp')    // search for 'Carp'
    console.log(isExists)
    
    
    OUTPUT
    
    true 
    
    
    
    // includes() returns true if an array contains 'element'
    // Example contains two argument : 'element' & 'fromIndex'
    
    const fishes = ['Catfish', 'Bass', 'Carp', 'Tuna', 'Salmon']
    
    // search for 'Tuna' from index position 3
    let isExists = fishes.includes('Tuna', 3)    
    console.log(isExists)
    
    
    OUTPUT
    
    true 
    
    

    (6)  indexOf()

  • returns the first index at which a given element can be found in the array, or -1 if it is not present.
  • indexOf() method compares element to items of the array using strict equality ===.
  • The optional argument fromIndex will specify from which index position should the search start.
  • For NaN values in the array, the indexOf() method will return -1.

  • SYNTAX : indexOf(element [, fromIndex])

    
    // indexOf() returns first index of the found element else -1
    // Example contains one argument : 'element'
    
    const ranNum = [11, 12, 34 ,76, 11, 98]
    let searchIndex = ranNum.indexOf(11)
    console.log(searchIndex)
    
    
    OUTPUT
    
    0
    
    
    
    // indexOf() returns first index of the found element else -1
    // Example contains two argument : 'element' & 'fromIndex'
    
    const ranNum = [11, 12, 34 ,76, 11, 98]
    
    // search for 11 from index position 3
    let searchIndex = ranNum.indexOf(11, 3)
    console.log(searchIndex)
    
    
    OUTPUT
    
    4
    
    

    (7)  concat()

  • method is used to merge two or more arrays.
  • concat() method does not change the existing arrays, but instead returns a new array.
  • The resultant array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array.
  • concat() is a copying method. It does NOT alter any of arrays provided as arguments but instead returns a shallow copy.
  • The argument value can be an arrays and/or values to concatenate into a new array.

  • SYNTAX : concat(value1, value2,...)

    
    // concat() merge two or more arrays and returns a new array
    
    const symOne = ['INR', 'USD', 'EUR']
    const symTwo = ['JPY', 'CNY']
    const symThree = symOne.concat(symTwo)
    console.log("symThree = ", symThree)
    
    // no change to the original arrays
    console.log("symOne = ", symOne)
    console.log("symTwo = ", symTwo)
    
    
    OUTPUT
    
    symThree =  ['INR', 'USD', 'EUR', 'JPY', 'CNY']
    symOne =  ['INR', 'USD', 'EUR']
    symTwo =  ['JPY', 'CNY']
    
    
    
    // concat() merge two or more arrays and returns a new array
    // Example to concatenate array1 with array2 and values 7 & 8
    
    const array1 = [2, 4, 6]
    const array2 = [1, 3, 5]
    
    // concatenate array1 with array2 and values 7 & 8
    const array3 = array1.concat(array2, 7, 8)
    console.log("array3 = ", array3)
    
    // no change to the original arrays
    console.log("array1 = ", array1)
    console.log("array2 = ", array2)
    
    
    OUTPUT
    
    array3 =  [2, 4, 6, 1, 3, 5, 7, 8]
    array1 =  [2, 4, 6]
    array2 =  [1, 3, 5]
    
    
    
    // concat() merge two or more arrays and returns a new array
    // concat() with no arguments
    
    const fruits = ['apples', 'oranges', 'kiwi']
    const newArray = fruits.concat()   // creates a shallow copy
    console.log("newArray = ", newArray)
    
    
    OUTPUT
    
    newArray =  ['apples', 'oranges', 'kiwi']
    
    

    (8)  join()

  • returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
  • If the array has only one item, then that item will be returned without using the separator.
  • The optional argument separator specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma ,.

  • SYNTAX : join([separator])

    
    // join() returns a new string by concatenating elements in an array 
    
    const shopList = ["Tea", "Milk", "Sugar"]
    
    shopList.join()         // 'Tea,Milk,Sugar'
    shopList.join(", ")     // 'Tea, Milk, Sugar'
    shopList.join(" + ")    // 'Tea + Milk + Sugar'
    shopList.join("")       // 'TeaMilkSugar'
    
    // array with one element
    ['SKILLZAM'].join()     // 'SKILLZAM'
    
    

    (9)  reverse()

  • method reverses an array in place and returns the reference to the same array.
  • The elements order in the array will be turned towards the direction opposite to that previously stated.
  • reverse() method does not have any arguments.
  • reverse() is a mutating method i.e. it changes order of the array. reverse() method returns reference to the original array, so mutating the returned array will mutate the original array as well.
  • In case you want reverse() to NOT mutate the original array, but return a shallow copy array, then before calling reverse(), using the spread(...) operator syntax or Array.from()

  • SYNTAX : reverse()

    
    // reverse() method reverses an array 
    
    const colors = ['red', 'green', 'blue', 'orange', 'cyan']
    colors.reverse()
    console.log(colors)
    
    
    OUTPUT
    
    ['cyan', 'orange', 'blue', 'green', 'red']
    
    
    
    // reverse() method reverses an array 
    // Mutating returned array will mutate original array 
    
    const fibonacci  = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]
    const newFibo = fibonacci.reverse()
    console.log("newFibo = ", newFibo)
    
    // Modify one element of new array 'newFibo'
    // original array 'fibonacci' is also modified
    newFibo[0] = 89
    console.log("newFibo = ", newFibo)
    console.log("fibonacci = ", fibonacci) 
    
    
    OUTPUT
    
    newFibo = [80, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
    newFibo = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
    fibonacci = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
    
    
    
    // reverse() method reverses an array 
    // NOT mutate the original array
    
    const fibonacci  = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]
    
    // spread(...) operator, will create a shallow-copied array
    const newFibo = [...fibonacci].reverse()    
    console.log("newFibo = ", newFibo)
    
    // Modify one element of new array 'newFibo'
    // No change to original array 'fibonacci'
    newFibo[0] = 89
    console.log("newFibo = ", newFibo)
    console.log("fibonacci = ", fibonacci)     
    
    
    OUTPUT
    
    newFibo = [80, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
    newFibo = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
    fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 80]
    
    

    (10)  slice()

  • slice() method returns a shallow copy of a portion of the original array into a new array object.
  • slice() method will NOT modifiy the original array.
  • The two optional arguments start and end will specify the starting and ending (end index not included), index position of the array.
  • If start is ommited, then it will default to 0 value.
  • If end argument is ommitted, then array.length is used, which means all elements until the end of array, to be extracted.

  • SYNTAX : slice([start], [end])

    
    // slice() returns shallow-copied portion of array
    // Single optional argument 'start' is used
    
    const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
    const carniDino = dinosaurs.slice(2)
    console.log(carniDino)
    
    
    OUTPUT
    
    ['Spinosaurus', 'Tyrannosaurus']
    
    
    
    // slice() returns shallow-copied portion of array
    // Both optional argument 'start' & 'end' are used
    
    const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
    const herbiDino = dinosaurs.slice(0,2)
    console.log(herbiDino)
    
    
    OUTPUT
    
    ['Brachiosaurus', 'Patagosaurus']
    
    
    
    // slice() returns shallow-copied portion of array
    // NO optional arguments are used
    
    const dinosaurs = ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
    const newDino = dinosaurs.slice()    // creates a shallow-copied full array
    console.log(newDino)
    
    
    OUTPUT
    
    ['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
    
    

    (11)  splice()

  • method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
  • splice() method is a mutating method.
  • If the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed as well.
  • The start argument specifies the starting index position of the array. If start is omitted, then 0 is used.
  • The optional argument deleteCount specifies the number of elements in the array to remove from start index. If deleteCount is omitted, then all the elements from start to the end of the array will be deleted.
  • The optional argument item specifies the elements to add to the array, beginning from start. If we do not specify any elements, splice() will only remove elements from the array.

  • SYNTAX : splice(start [, deleteCount] [, item1, item2... ])

    
    // splice() changes the contents of an array 
    // Using all three arguments with 0 'deleteCount'
    
    const animals = ['Ape', 'Cow', 'Dog', 'Fox']
    animals.splice(1, 0, 'Cat')    // Inserts 1 element at index 1
    console.log(animals)
    
    
    OUTPUT
    
    ['Ape', 'Cat', 'Cow', 'Dog', 'Fox']
    
    
    
    // splice() changes the contents of an array 
    // Using all three arguments
    
    const animals = ['Ape', 'Cow', 'Dog', 'Fox']
    
    // Replaces 1 element with 1 element at index 3
    animals.splice(3, 1, 'Elk')     
    console.log(animals)
    
    
    OUTPUT
    
    ['Ape', 'Cow', 'Dog', 'Elk']
    
    
    
    // splice() changes the contents of an array 
    // Using all three arguments
    
    const animals = ['Ape', 'Cow', 'Dog', 'Fox']
    
    // Replaces 1 element with 3 elements at index 3
    animals.splice(3, 1, 'Elk', 'Kob', 'Yak')    
    console.log(animals)
    
    
    OUTPUT
    
    ['Ape', 'Cow', 'Dog', 'Elk', 'Kob', 'Yak']
    
    
    
    // splice() changes the contents of an array 
    // Using two arguments 'start' & 'deleteCount'
    
    const animals = ['Ape', 'Cow', 'Dog', 'Fox']
    animals.splice(3, 1)    // Removes 1 element at index 3   
    console.log(animals)
    
    
    OUTPUT
    
    ['Ape', 'Cow', 'Dog']
    
    

    Objects

  • Object is a complex datatypes in JavaScript.
  • Objects are variables too. But objects can contain many values.
  • JavaScript objects are containers for named values called properties.
  • Objects are collections of properties. Object properties can be defined within curly brackets { } and have a comma-separated key : value pairs (key and value separated by a colon : ).
  • It is a common practice to declare objects with the const keyword.
  • The values in object properties can be of any data type.
  • Objects does not allow duplicate properties.
  • Objects are utable. They are addressed by reference, not by value.
  • For Example: Consider Football Player Leo Messi's Bio

    messi Object

    This player bio example can be represented by a object data structure.

    
    // Object Literal Example:
    
    const playersBio = {
        name: "Leo Messi",
        team: "Paris Saint-Germain",
        position: "Forward",
        height: 170,
        weight: 159,
        birthdate: "24/6/1987",
        age: 35,
        nationality: "Argentina",
        careerHistory: ["Barcelona","PSG","Argentina"], 
        isRetired: false
    }
    
    
    // Objects do not allow duplicate keys
    
    const numbers = {Keyone:1, Keyone:2, Keythree:3}
    console.log(numbers)
    
    
    OUTPUT
    
    {Keyone: 2, Keythree: 3}
    
    
    
    // Object values can be of any dataType
    
    const students = {
      fName: "Jasmine",    
      lName: "Dsouza",     
      gender: "Female",     // value is string DataType
      age: 20,              // value is number(integer) DataType  
      isGraduate: true,     // value is boolean DataType
      cgpa: 8.4,            // value is number(decimal) DataType 
      favSub: ["Physics","Computers"] // value is array 
    }
    console.log(students)
    
    
    OUTPUT
    
    {fName: 'Jasmine', lName: 'Dsouza', gender: 'Female', age: 20, isGraduate: true, cgpa: 8.4, favSub: ['Physics', 'Computers', 'History']}
    
    

    Creating Object

  • Object Literal: use a comma-separated list of key : value pairs within braces. Example: { uid: 4098, name: 'Ravi Patil' }
  • Using the new keyword with in-built Object constructor function. Example: const cars = new Object()
  • Using new with user-defined constructor function.
  • Using Object.create() to create new objects.
  • Using Object.assign() to create new objects.
  • Using ES6 class to create objects
  • 
    // Creating Object: 'Object Literal'
    
    const fruitCost = { apples:123, oranges:456}    // using key:value pairs
    console.log(fruitCost)      
    
    
    OUTPUT
    
    {apples: 123, oranges: 456}
    
    
    
    // Creating Object: using new keyword with 
    // in-built Object constructor function
    
    const car = new Object()
    
    // Add properties to 'car' object
    car.year = 2022
    car.make = 'Mahindra'
    car.model = 'XUV700'
    
    console.log(car)      
    
    
    OUTPUT
    
    {year: 2022, make: 'Mahindra', model: 'XUV700'}
    
    
    
    // Creating Object: using new with 
    // user-defined constructor function
    
    // constructor function with 'this' keyword
    function Cricketer (name, score) {
      this.fullName = name;
      this.runsScored = score;
    }
    
    // Create new Object 'playerOne'
    const playerOne = new Cricketer('Virat Kohli', 183)
    console.log(playerOne)      
    console.log(playerOne.runsScored)      
    
    
    OUTPUT
    
    Cricketer {fullName: 'Virat Kohli', runsScored: 183}
    183
    
    
    
    // Creating Object: using Object.assign() 
    // to create new objects
    
    // Object 'biography'
    const biography = {
        name: "Cristiano Ronaldo",
        team: "Manchester United",
        position: "Forward",
        height: 187,
        weight: 183,
        birthdate: "5/2/1985",
        age: 37
    }
    
    // Object 'playerHist'
    const playerHist = {
        nationality: "Portugal",
        careerHistory: ["ManU","Juventus","Real Madrid"], 
        isRetired: false
    }
    
    // Create new Object 'PlayerBio' using Object.assign()
    const PlayerBio = Object.assign({}, biography, playerHist)
    
    console.log(PlayerBio)      
    console.log(PlayerBio.name)      
    
    
    OUTPUT
    
    {name: 'Cristiano Ronaldo', team: 'Manchester United', position: 'Forward', height: 187, weight: 183, birthdate: "5/2/1985", age: 37, nationality: "Portugal", careerHistory: ["ManU","Juventus","Real Madrid"], isRetired: false }
    Cristiano Ronaldo
    
    
    
    // Creating Object: using class to create objects
    
    // class created with constructor function
    class Employee {
      constructor(name, location) {
        this.fullname = name
        this.city = location
      }
    }
    
    // Create new object
    const empOne = new Employee('Fred Silva', 'Rio de Janeiro') 
    
    console.log(empOne.fullname) 
    console.log(empOne.city) 
    console.log(empOne) 
    
    
    OUTPUT
    
    Fred Silva
    Rio de Janeiro
    Employee {fullname: 'Fred Silva', city: 'Rio de Janeiro'}
    
    

    Working with Object

    Almost "everything" is an object in JavaScript. All values, except primitives, are objects.

  • Booleans can be objects (if defined with the new keyword)
  • Numbers can be objects (if defined with the new keyword)
  • Strings can be objects (if defined with the new keyword)
  • Dates are always objects
  • Maths are always objects
  • Regex are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are always objects

  • Access the properties of an object by referring to its key, inside square brackets.

    
    // Accessing the items of a Object
    // Using key inside square brackets
    
    const students = {
        fName: "Jasmine",    
        lName: "Dsouza",     
        gender: "Female",     
        age: 20,                
        isGraduate: true,     
        cgpa: 8.4,            
        favSub: ["Physics","Computers","History"]  
    }
    
    firstname = students['fName']
    favSubject = students['favSub'][0]
    console.log(firstname + ' loves ' + favSubject + '!')
    
    
    OUTPUT
    
    Jasmine loves Physics!
      
    

    Access the properties of an object by referring to its key, using dot(.).

    
    // Accessing the items of a Object
    // Using object name & key seperated by dot(.)
    
    const students = {
      fName: "Jasmine",    
      lName: "Dsouza",     
      gender: "Female",     
      age: 20,                
      isGraduate: true,     
      cgpa: 8.4,            
      favSub: ["Physics","Computers","History"]  
    }
    
    firstname = students.fName
    scoreCGPA = students.cgpa
    console.log(firstname + ' scored ' + scoreCGPA + '!')
    
    
    OUTPUT
    
    Jasmine scored 8.4!
    
    

    Adding new properties of an object by giving it a value.

    
    // Adding new properties to the Object 
    
    const vehicle = {
      year: 2021,
      make: 'Mahindra'
    }
    
    // add new porperty - model: 'XUV700'
    vehicle.model = "XUV700"   
    console.log(vehicle)
    
    
    OUTPUT
    
    {year: 2021, make: 'Mahindra', model: 'XUV700'}
    
    

    Change/Modify the value of a specific property of an object, by referring to its key name.

    
    // Change value of a specific property of an object
    
    const users = {
    fname: 'Guido',
    lname: 'van Rossum',
    email: 'guido@junkmail.com'
    }
    
    // Change 'email' property value
    users['email'] = 'guido@example.com'   
    console.log(users)
    
    
    OUTPUT
    
    {fname: 'Guido', lname: 'van Rossum', email: 'guido@example.com'}
    
    

    Computed properties of an object using square brackets [] in an object literal, when creating an object.

    
    // Computed properties of an object
    
    let brand = 'Samsung';
    
    const mobile = {
      [brand]: 25000,    // 'Samsung' property key is taken from variable 'brand'
      year: 2022
    }
    
    console.log(mobile)
    
    
    OUTPUT
    
    {Samsung: 25000, year: 2022}
    
    

    Deleting a properties of an object by using delete keyword.

    
    // Deleting a properties from the object 
    
    const vehicle = {
      year: 2021,
      make: 'Mahindra',
      model: 'XUV700'
    }
    
    delete vehicle.model  // same as: delete vehicle['model']
    console.log(vehicle)
    
    
    OUTPUT
    
    {year: 2021, make: 'Mahindra'}
    
    

    in Keyword is used to determine, if a specified key is present in an object. For any a non-existing property, in operator just returns undefined.

    
    // Check if a key exists 'in' the object 
    
    const users = {
    fname: 'Guido',
    lname: 'van Rossum',
    email: 'guido@example.com'
    }
    
    isEmailExists = 'email' in users
    console.log(isEmailExists)
      
    
    OUTPUT
    
    true
    
    

    Static Methods in Object:

  • Object.entries() returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
  • Object.keys() returns an array containing the key names of all of the given object's own enumerable string properties.
  • Object.values() returns an array containing the values that correspond to all of a given object's own enumerable string properties.
  • 
    // Object - static methods 
    // Object.entries(), Object.keys(), Object.values()
    
    const employee = {
      empName: "Javid Khan",
      designation: "Software Developer",
      city: "Paris",
      zip: 70123
    }
    
    const allItems = Object.entries(employee)
    console.log(allItems)
    
    const allKeys = Object.keys(employee)
    console.log(allKeys)
    
    const allValues = Object.values(employee)
    console.log(allValues)
    
    
    OUTPUT
    
    [['empName', 'Javid Khan'], ['designation', 'Software Developer'], ['city', 'Paris'], ['zip', 70123] ]
    ['empName', 'designation', 'city', 'zip']
    ['Javid Khan', 'Software Developer', 'Paris', 70123]
    
    

    Nested Objects

    JavaScript data structures support nesting. This means we can have data structures within data structures. For object, property values in an object can be another object. You can access nested objects using the dot (.) notation or the bracket [] notation
    For example: An object containing another object.

    
    // Nested Object : Example 1
    
    const team = {
      player1: {
          name: 'Leo Messi',
          position: 'Forward'
      },
    
      player2: {
          name: 'Andres Iniesta',
          position: 'Midfield'
      },
    
      player3: {
          name: 'Xavi Hernandez',
          position: 'Midfield'
      }
    }
    
    team['player1']['name']
    
    
    OUTPUT
    
    'Leo Messi'
    
    
    
    // Nested Object : Example 2
    
    const player1 = {
      name: 'Leo Messi',
      position: 'Forward'
    }
    
    const player2 = {
        name: 'Andres Iniesta',
        position: 'Midfield'
    }
    
    const player3 = {
        name: 'Xavi Hernandez',
        position: 'Midfield'
    }
    
    const team = {
        player1 : player1,
        player2 : player2,
        player3 : player3
    }
    
    team['player1']
    
    
    OUTPUT
    
    {name: 'Leo Messi', position: 'Forward'}
    
    

    Object Methods

    1.  (1). hasOwnProperty() :

      method returns a boolean indicating whether the object has the specified property as its own property, as opposed to inheriting it.
      The argument property is the String name or Symbol of the property to test.

      SYNTAX : hasOwnProperty(property)


    2. 
      // hasOwnProperty() returns whether object has property
      
      const player = {
        name: 'Leo Messi',
        position: 'Forward'
      }
      
      player.hasOwnProperty('position')  // returns true
      
      
      OUTPUT
      
      true 
      
      
    3.  (2). toString() :

      method returns a string representing the object.
      This method is meant to be overridden by derived objects for custom type conversion logic.

      SYNTAX : toString()


    4. 
      // toString() returns string representing the object
      
      function Player(name, position) {
        this.name = name
        this.position = position
      }
      
      const player1 = new Player('Leo Messi', 'Forward')
      
      Player.prototype.toString = function playerToString() {
        return `${this.name} plays as ${this.position}`;
      }
      
      console.log(player1.toString())
      
      
      OUTPUT
      
      Leo Messi plays as Forward
      
      
    5.  (3). valueOf() :

      method of Object converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

      SYNTAX : valueOf()


    6. 
      // valueOf() methods 
      // Example : Area of a circle
      
      function SquareRad(num) {
        this.square = num * num
      }
      
      SquareRad.prototype.valueOf = function() {
        return this.square;
      }
      
      const radiusObj = new SquareRad(5)
      console.log("Area of circle = " + 3.142 * radiusObj )
      
      
      OUTPUT
      
      Area of circle = 78.55
      
      

    Control Flow in JavaScript

  • Control flow is where the rubber really meets the road in programming. Without it, a program is simply a list of statements that are sequentially executed.
  • With control flow, you can execute certain code blocks conditionally and/or repeatedly.
  • A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
  • Control flow statements in JavaScript can be put into three broad categories:
    1. [1]. Decision Making statements ( if, else if, else, switch )
    2. [2]. Loop statements ( for, for...in, for...of, while, do...while)
    3. [3]. Jump statements ( break, continue )
  • Decision making statements

  • Decision making statements are sometimes also known as "Conditional statements" often referred to if-else statements, allow the programmer to execute certain pieces of code depending on some Boolean condition.
  • Decision making statements in JavaScript are:
    1. [1]. if statement
    2. [2]. else if statement
    3. [3]. else statement
    4. [4]. switch statement
  • Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided.
  • JavaScript adopts the if, else if and else statements. In these conditional clauses, else if and else blocks are optional; additionally, you can optinally include as few or as many else if statements as you would like.
  • Simple if statement

  • if statement is the most simple decision-making statement.
  • An "if statement" is written by using the if keyword.
  • It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
  • The condition after evaluation will be either true or false
  • JavaScript relies on block scope (curly brackets {}) to define scope in the code. Other programming language like Python, often use "indentation" for this purpose.
  • Example of Simple if statement:

    
    // Simple 'if' statement
    
    let num1 = 24,
        num2 = 12;
    
    // 'if' condition is true, hence the block will be executed
    if (num1 > num2) {
      console.log(`num1(${num1}) is greater than num2(${num2})`)
    }        
    
    // if condition is false, hence "if" block will NOT be executed
    if (num2 > num1) {
      console.log(`num2(${num2}) is greater than num1(${num1})`)
    }                         
                    
    
    OUTPUT
    
    num1(24) is greater than num2(12)
    
    

    if...else statement

  • The if statement alone tells us that, if a condition is true, it will execute a block of statements and if the condition is false it won't.
  • But what if we want to do something else, if the condition is false. Here comes the else statement.
  • We can use the else statement with if statement to execute a block of code when the condition is false.
  • 
    // 'if...else' statement
    
    let num1 = 36,
        num2 = 48;
    
    // if condition is false, hence "if" block will NOT be executed
    // hence, else block will be executed    
    if (num1 > num2) {
      console.log(`num1(${num1}) is greater than num2(${num2})`)
    }    
    else {
      console.log(`num1(${num1}) is lesser than num2(${num2})`)
    }    
    
    
    OUTPUT
    
    num1(36) is lesser than num2(48)
    
    

    Nested if statement

  • A nested if is an if statement that is the target of another if or else.
  • Nested if statements mean an if statement inside an if statement.
  • Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
  • 
    // Nested "if/else" statement       
    
    let ranNum = 28
    
    // if condition is true, hence "if" block will be executed
    if (ranNum == 28 || ranNum <= 30) {
    
      // if condition is true, hence nested "if" block will be executed
      if (ranNum < 30) {
        console.log('ranNum is smaller than 30')
      } 
    
      // if condition is false, hence nested "if" block will NOT be executed               
      if (ranNum < 15) {
        console.log('ranNum is smaller than 15')
      }               
    }
    
    // never executes else block
    else {
      console.log('ranNum is larger than 30')
    }
    
    
    OUTPUT
    
    ranNum is smaller than 30
    
    

    if...else if...else ladder statement

  • The if statements are executed from the top down.
  • As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
  • If none of the conditions is true, then the final else statement will be executed.
  • 
    // if...else if...else ladder statement
    
    let givenNum = 100
    
    // if condition is false, hence "if" block will NOT be executed
    if (givenNum == 25) {
      console.log('givenNum is 25')
    }            
    
    // if condition is false, hence "else if" block will NOT be executed
    else if (givenNum == 50) {
      console.log('givenNum is 50')  
    }          
          
    // if condition is false, hence "else if" block will NOT be executed
    else if (givenNum == 75) {
      console.log('givenNum is 75')
    }          
        
    // if condition is true, hence "else if" block will be executed 
    else if (givenNum == 100) {
      console.log('givenNum is 100')
    }         
        
    // never executes else block 
    else {
      console.log('givenNum is INVALID')
    }                             
                
    
    OUTPUT
    
    givenNum is 100
    
    

    switch statement

  • switch statement is to be used, when one of many code blocks is to be executed.
  • The switch statement evaluates an expression, matching the expression's value against a series of case clauses.
  • It executes statements after the first case clause with a matching value (using the strict equality comparison), until a break statement is encountered.
  • The default clause of a switch statement will be executed, if no case matches the expression's value.
  • 
    // switch statement 
    // Example: Based on billing rate, decide salay of employee
    
    const billRate = 40
    
    switch (billRate) {
      case 25:
        console.log("Salary paid per month = 80000");
        break;  
      case 40:
      case 45:
        console.log("Salary paid per month = 125000");
        break;   
      case 60:
        console.log("Salary paid per month = 190000");
        break; 
      case 90:
        console.log("Salary paid per month = 300000");
        break; 
      default:
        console.log("He/She is unbillable resource.");
    }
    
    
    OUTPUT
    
    Salary paid per month = 125000
    
    

    Shorthand if statement

  • If you have only one statement to execute, you can put it on the same line as the if statement, without curly brackets.
  • 
    // Shorthand "if" statement
    
    let weightOne = 225, 
        weightTwo = 125;
    
    if (weightOne > weightTwo) console.log("weightOne is heavier")
    console.log("***End of Code***")
                    
    
    OUTPUT
    
    weightOne is heavier
    ***End of Code***
    
    

    Shorthand if...else or "Ternary" operator

  • If you have only one statement to execute, one for if, and one for else, you can put it all on the same line, without curly brackets.
  • This technique is known as Ternary Operators, or Conditional Operators.
  • 
    // Shorthand "if...else" statement
    //  “Question mark” or "Ternary" operator
    
    let num1 = 144, 
        num2 = 169;
    
    // (condition) ? (If 'true') : (If 'false')   
    (num1 > num2) ? console.log("num1 is largest") :  console.log("num2 is largest") 
                            
    
    OUTPUT
    
    num2 is largest
      
    

    Loops in JavaScript

  • Loops are basically a simple set of instructions that gets repeated until a condition is met.
  • The various loop mechanisms offer different ways to determine the start and end points of the loop.
    1. In JavaScript, we have different kind of looping statements:
    2. (1). while loops through a block of code while a specified condition is true
    3. (2). do while also loops through a block of code while a specified condition is true
    4. (3). for loops through a block of code a number of times
    5. (4). for...of loops through the values of an iterable object
    6. (5). for...in loops through the properties of an object

    [1]. while Loop

  • while loop is used to execute a block of statements repeatedly until a given condition is satisfied (true).
  • When the condition becomes false, the line immediately after the loop in the program is executed.
  • while loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn't specified explicitly in advance.
  • When a while loop is executed, expression is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the expression is checked again, if it is still true then the body is executed again and this continues until the expression becomes false.
  • If you forget to increase the variable used in the condition, the loop will never end.
  • A nested while loop is a while loop inside a while loop.
  • 
    // while loop to print numbers : 1 to 5
    
    let i = 1
    
    while (i < 6) {
      console.log(i)
      i += 1   // remember to increment i, or else loop will continue forever
    }
      
    
    OUTPUT
    
    0
    1
    2
    3
    4
    5
    
    
    
    // Nested "while" loop
    
    let j = 0,
        i = 1,
        str = '';
    
    while (i <= 5) {
      j = 1
      while (j <= i) {
        str += (j + ' ')
        j += 1
      }
      str += "\n";
      i += 1
    }
    console.log(str)
    
    
    OUTPUT
    
    1 
    1 2 
    1 2 3 
    1 2 3 4 
    1 2 3 4 5 
    
    

    [2]. do while Loop

  • do while also loops through a block of code while a specified condition is true.
  • Unlike the while loop, the do while loop always executes the statement at least once before evaluating the expression.
  • In the below Syntax of do while loop :
    • Block of codeis always executed once before the condition is checked.
    • If conditionis true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do while.
  • SYNTAX:

    
      do {
        // Block of code to be executed
      }
      while (condition);
              
    
    // do while loop Example 
    
    let counter = 1
    
    do {
      console.log(counter)
      counter++
    } while (counter <= 3)
    
    
    OUTPUT
    
    1
    2
    3
    
    

    [3]. for Loop

  • for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.
  • A nested for loop is a for loop inside a for loop.
  • In the below Syntax of for loop :
    • expression1 = initial Expression Eg: let i = 0;
    • expression2 = Condition Eg: i <= 10;
    • expression3 = increment Expression Eg: i++
  • SYNTAX:

    
        for (expression1; expression2; expression3) {
          // Block of code to be executed  
        }
                  
      When a for loop executes, the following ordered steps occurs:
    1.   (1). Initializing expression expression1, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
    2.   (2). Condition expression expression2 is evaluated. If the value of condition is true, the loop statements execute. Otherwise, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.)
    3.   (3). Block of code within curly braces {} executes multiple statements.
    4.   (4). Increment expression expression3, if any, is executed.
    5.   (5). Control returns to Step (2) i.e. condition expression expression2 is evaluated.
    
    // for loop     
    // Example : Adding all single digit numbers as elements of an array 
    
    const numArray = []    // create empty array
    let singleDigit,
        index = 0;
    
    for (singleDigit = 0; singleDigit <= 9; singleDigit += 1) {
      numArray[index] = singleDigit
      index++
    }
    console.log(`The "numArray" contains = [${numArray}]`)
    
    
    
    /****************************************************/
    // Tracing 'for' loop in the above example
    //
    // 1st: singleDigit=0; true; o/p: 0 added to the array
    // 2nd: singleDigit=1; true; o/p: 1 added to the array
    // 3rd: singleDigit=2; true; o/p: 2 added to the array
    // ....
    // .... continue adding to the array
    // ....
    // 9th: singleDigit=8; true; o/p: 8 added to the array
    // 10th:singleDigit=9; true: o/p: 9 added to the array
    // 11th:singleDigit=10; false; exit the for loop
    //
    // The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
    /*****************************************************/
    
    
    OUTPUT
     
    The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
    
    
    
    // for loop 
    // Example : Find sum of all number in an array 
    
    let evenNum = [22, 44, 66];    // array length = 3
    let sumNum = 0;
    for (let x = 0; x < evenNum.length; x++) {
      sumNum = sumNum + evenNum[x];
    }
    console.log(`Sum of all the number in an array = ${sumNum}`)
     
    
    
    /*****************************************************/
    // Tracing 'for' loop in the above example
    //
    // 1st: x = 0; true; sumNum = 0 + 22 = 22
    // 2nd: x = 1; true; sumNum = 22 + 44 = 66
    // 3rd: x = 2; true; sumNum = 66 + 66 = 132
    // 4th: x = 3; false; Exit the 'for' loop
    //
    // Sum of all the number in an array =   132 
    /*****************************************************/
    
    
    OUTPUT
     
    Sum of all the number in an array = 132
    
    
    
    // Nested "for" loop example
    
    for (let p = 1; p <= 2; p++) {  //p:  1,2 
        console.log(`p is: ${p}`)  
        for (let q = 1; q < 4; q++) {   //q: 1,2,3
            console.log(`    q is: ${q}`)
        }
    }
    
    
    /*****************************************************/ 
    // Tracing Nested 'for' loop in the above example
    //
    // Outer for loop - 1st of p: p = 1; true; o/p: p is:1
    // 1st of q: q = 1; true; o/p: q is:1
    // 2nd of q: q = 2; true; o/p: q is:2
    // 3rd of q: q = 3; true; o/p: q is:3
    // 4th of q: q = 4; false; Exit the inner q loop
    // Outer for loop - 2nd of p: p = 2; true; o/p: p is:2
    // 1st of q: q = 1; true; o/p: q is:1
    // 2nd of q: q = 2; true; o/p: q is:2
    // 3rd of q: q = 3; true; o/p: q is:3
    // 4th of q: q = 4; false; Exit the inner q loop
    // Outer for loop - 3rd of p: p = 3; false; Exit the outer p loop
    //
    /*****************************************************/        
    
    
    OUTPUT
    
    p is: 1
        q is: 1
        q is: 2
        q is: 3
    p is: 2
        q is: 1
        q is: 2
        q is: 3
    
    
    
    // "for" loop : Iterate multi-dimension array using "for" loop 
    // Example : Print the country name and Flag colors
    
    const arrFlags = [  
        ["INDIA","Orange","White","Green"],  
        ["GERMANY","Black","Red","Yellow"],  
        ["RUSSIA","White","Red","Blue"],
        ["COLOMBIA","Yellow","Blue","Red"],
        ["EGYPT","Red","White","Black"]  
    ]
    
    for (let a = 0; a < arrFlags.length; a++) {     // arrFlags.length = 5
        let flagRow = arrFlags[a];  
        console.log(flagRow[0] + " Flag Colors");  
        for (let b = 1; b < flagRow.length ; b++) { // flagRow.length = 4
            console.log(flagRow[b]);
        }
    }
    
    
    /*****************************************************/
    // Tracing nested 'for' loop in the above example
    //
    // Outer for loop - 1st of a: a = 0; true; flagRow = ["INDIA","Orange","White","Green"] ; O/P: INDIA Flag Colors
    // 1st of b: b = 1; true : O/P: Orange
    // 2nd of b: b = 2; true : O/P: White
    // 3rd of b: b = 3; true : O/P: Green
    // 4th of b: b = 4; false  Exit the inner b loop
    // Outer for loop - 2nd of a: a = 1; true; flagRow = ["GERMANY","Black","Red","Yellow"] ; O/P: GERMANY Flag Colors
    // 1st of b: b = 1; true : O/P: Black
    // 2nd of b: b = 2; true : O/P: Red
    // 3rd of b: b = 3; true : O/P: Yellow
    // 4th of b: b = 4; false  Exit the inner b loop
    // ... continue 
    //
    /*****************************************************/
    
    
    OUTPUT
    
    INDIA Flag Colors
    Orange
    White
    Green
    GERMANY Flag Colors
    Black
    Red
    Yellow
    RUSSIA Flag Colors
    White
    Red
    Blue
    COLOMBIA Flag Colors
    Yellow
    Blue
    Red
    EGYPT Flag Colors
    Red
    White
    Black
    
    

    [4]. for...of Loop

  • for...of statement loops through the values of an iterable objects such as arrays, strings, maps, NodeLists etc.
  • In the below Syntax of for...of loop :
    • variable : For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
    • iterable : An object that has iterable properties.
    • Block of code within curly braces {} executes multiple statements.
  • SYNTAX:

    
      for (variable of iterable) {
        // Block of code to be executed
      }
    
    
    // "for .. of" loop iterating arrays 
    // Example : Sum of all the number in an array
    
    let total = 0;
    let arrayNum = [10, 20, 30, 40]
    
    for (let n of arrayNum) {  
        total = total + n;  
    }
    console.log(`Sum of all the number in an array = ${total}`)
    
    
    /*****************************************************/
    // Tracing 'for...of' loop in the above example
    //
    // 1st : n = 10; total = 0 + 10 = 10
    // 2nd : n = 20; total = 10 + 20 = 30
    // 3rd : n = 30; total = 30 + 30 = 60
    // 4th : n = 40; total = 60 + 40 = 100
    // No more values in the array, hence exit the for loop
    //
    // Sum of all the number in an array = 100
    /*****************************************************/
    
    
    OUTPUT
    
    Sum of all the number in an array = 100
    
    
    
    // "for .. of" loop iterating strings 
    // Example : convert string into an array of characters
    
    const charArray = []
    let charIndex = 0
    
    for (let singleChar of "SKILLZAM") {
        charArray[charIndex] = singleChar;
        charIndex++;
    }
    console.log(`The "charArray" contains = [${charArray}]`)
    
    
    /******************************************************/
    // Tracing 'for...of' loop in the above example
    //
    // 1st: singleChar = S; o/p: S is added to the array
    // 2nd: singleChar = K; o/p: K is added to the array
    // 3rd: singleChar = I; o/p: I is added to the array
    // 4th: singleChar = L; o/p: L is added to the array
    // 5th: singleChar = L; o/p: L is added to the array
    // 6th: singleChar = Z; o/p: Z is added to the array
    // 7th: singleChar = A; o/p: A is added to the array
    // 8th: singleChar = M; o/p: M is added to the array
    // No more charaters in the string "SKILLZAM", 
    // hence exit the for loop
    //
    // The "charArray" contains =  [S,K,I,L,L,Z,A,M]
    /*****************************************************/
            
    
    OUTPUT
    
    The "charArray" contains = [S,K,I,L,L,Z,A,M]
    
    
    
    // "for .. of" loop iterating Object 
    // Example : Iterate values in Object - turn data into an array
    
    let gTotal = 0
    
    const goalScores = {
        Messi:     44,
        Ronaldo:   43,
        Diogo:     43,
        Robert:    39,
        Turpel:    37,
        Suarez:    36,
        Salah:     35,
        Griezmann: 35,
        Cifuente:  34,
        Kane:      33
    }
    
    // Using Object constructor, create array of 'values'
    let goals = Object.values(goalScores)
    
    // goals = [44,43,43,39,37,36,35,35,34,33]
    for (let goal of goals) {
        gTotal += goal;    
    }
    
    console.log(`The array of object values is = [${goals}]`)
    console.log(`Total goals scored by top 10 players in the year 2018: ${gTotal}`)
    
    
    OUTPUT
    
    The array of object values is = [44,43,43,39,37,36,35,35,34,33]
    Total goals scored by top 10 players in the year 2018: 379
    
    

    [5]. for...in Loop

  • for...in statement loops through the properties of an Object.
  • Difference between a for...of loop and a for...in loop is, while for...in iterates over property names, for...of iterates over property values.
  • Do not use for...in over an Array. It is better to use a for loop, a for...of loop, or Array.forEach() when the order is important.
  • In the below Syntax of for...in loop :
    • key : the key from the key : value pair of an object.
    • object : is a complex datatypes containing named values called properties.
    • Block of code within curly braces {} executes multiple statements.
  • SYNTAX:

    
      for (key in object) {
        // Block of code to be executed
      } 
    
    
    // "for .. in" loop 
    // Example : Use "for .. in" loop to iterate Object literals
    
    let str = ""
    
    const car = {
      year: 2022, 
      make: 'Mahindra', 
      model: 'XUV700'
    }
    
    for (let item in car) {
      str += car[item]
      str += ' '
    }
    
    console.log(str)             
    
    
    OUTPUT
    
    2022 Mahindra XUV700 
    
    
    
    // "for .. in" loop 
    // Example : Use "for .. in" loop to iterate Object literals
    
    const bioMessi = {
        name: "Leo Messi",
        team: "PSG",
        position: "Forward",
        height: 170,
        weight: 159,
        birthdate: "24/6/1987",
        age: 35,
        country: "Argentina",
        careerHist: ["PSG","FCB","Argentina"], 
        isRetired: false
    }
    
    for (let bio in bioMessi) {
        console.log(`${bio.toUpperCase()} is ${bioMessi[bio]}`);
    }
    
     
    /**************************************************************************************************/
    // Tracing for loop
    //
    // 1st: bio = name;        bioMessi[bio] = Leo Messi; o/p: NAME is Leo Messi
    // 2nd: bio = team;        bioMessi[bio] = PSG;       o/p: TEAM is PSG
    // 3rd: bio = position;    bioMessi[bio] = Forward;   o/p: POSITION is Forward
    // 4th: bio = height;      bioMessi[bio] = 170;       o/p: HEIGHT is 170
    // 5th: bio = weight;      bioMessi[bio] = 159;       o/p: WEIGHT is 159
    // 6th: bio = birthdate;   bioMessi[bio] = 24/6/1987; o/p: BIRTHDATE is 24/6/1987
    // 7th: bio = age;         bioMessi[bio] = 35;        o/p: AGE is 35
    // 8th: bio = country;     bioMessi[bio] = Argentina; o/p: COUNTRY is Argentina
    // 9th: bio = careerHist;  bioMessi[bio] = PSG,FCB,Argentina; o/p: CAREERHIST is PSG,FCB,Argentina
    // 10th: bio = isRetired;  bioMessi[bio] = false;    o/p: ISRETIRED is false
    // No more name:value pair exists in the object literal, hence exit the for loop
    //
    /**************************************************************************************************/       
                    
    
    OUTPUT
    
    NAME is Leo Messi
    TEAM is PSG
    POSITION is Forward
    HEIGHT is 170
    WEIGHT is 159
    BIRTHDATE is 24/6/1987
    AGE is 35
    COUNTRY is Argentina
    CAREERHIST is PSG,Barcelona,Argentina
    ISRETIRED is false
    
    

    Jump statements : break & continue

    Jump statements are the loop control statements that change the execution from its normal sequence.

    Examples:

  • break statement
  • continue statement
  • break statement

  • The break statement breaks-out of the loop entirely.
  • It was used to jump out of a switch statement as well.
  • The combination infinite loop + break as needed is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.
  • With the break statement, we can stop the for or for...of or for...in loop before it has looped through all the items.
  • With the break statement, we can stop the while or do while loop even if the condition is true.
  • Example of using break statement for a less trivial task. This loop will fill a list with all Fibonacci numbers up to a certain value:

    
    // "break" statement for printing Fibonacci numbers 
    
    let a = 0, 
        b = 1,
        n,
        maxNum = 100,
        index = 0;
    const listFibo = [];
    
    while (true) {
      listFibo[index] = a;
      index++;
      n = a + b;
      a = b;
      b = n;
      if (a > maxNum) {
        break;    // usuage of break statement to exit the loop
      }
    }
    
    console.log(listFibo)
    
    
    OUTPUT
    
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    

    continue statement

  • continue statement: The continue statement skips the remainder of the current loop, and goes to the next iteration.
  • continue statement breaks one iteration (in the loop).
  • With the continue statement we can stop the current iteration of the for or while loop, and continue with the next.
  • Example of using continue to print a string of odd numbers. In this case, the result could be accomplished just as well with an if...else statement, but sometimes the continue statement can be a more convenient way to express the idea you have in mind:

    
    // "continue" statement for printing ODD numbers
    
    const numArray = [1,2,3,4,5,6,7,8,9,10]
    let str = "";
    
    for (let num in numArray) {
      // if the remainder of num / 2 is 0, skip the rest of current loop
      if (num % 2 == 0) {
            continue;
      }
      str += num + ' '
    }
    console.log(str)
    
    
    OUTPUT
    
    1 3 5 7 9
    
    

    label statement

  • label provides a statement with an identifier that lets you refer to it elsewhere in your program.
  • To label JavaScript statements you precede the statements with a label name and a colon :
  • With a label reference, the break statement can be used to jump out of any code block.
  • label names can not be a reserved words.
  • SYNTAX:

    
      label:
        statements
    
    
    
    // label statement Example 
    
    let total = 0, 
        i = 1;
    
    whileloop1: while (true) {
        i = 1;  
        whileloop2: while (i < 3) {
          total += i;
            if (total > 3) {  
                break whileloop1;  // break using 'label' statement
            }
            console.log("total = " + total);
            i++;
        }
    }
    
    
    OUTPUT
    
    total = 1
    total = 3
    
    

    Functions in JavaScript

  • A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
  • One way to organize our JavaScript code and to make it more readable and reusable is to factor-out useful pieces into reusable function.
  • The function will allow you to call the same block of code without having to write it multiple times. This in turn will allow you to create more complex scripts.
  • To use a function, you must define it somewhere in the scope from which you wish to call it.
  • Function definition

    To create a function, we can use a function definition/declaration.

    A function definition (also called function declaration, or function statement ) consists of :

  • The function keyword, followed by name of the function.
  • Then a list of parameters to the function, enclosed in parentheses () and separated by commas ,
  • Followed by Block of code i.e. JavaScript statements that define the function, enclosed in curly brackets, {}
  • Function hoisting only works with function declarations — not with function expressions. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope.
  • For example, the following code defines a simple function named createFullName :

    
    // Function definition or declaration Example 
    
    function createFullName() {
      let fname = "Brendan",
          lname = "Eich",
          fullname = fname + " " + lname;
          
      console.log(fullname)
    }
    
    

    Function invoking

    Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.

  • Calling a function is also known as invoking a function.
  • To call a function, you use its name followed by arguments enclosing in parentheses ()
  • When calling a function, JavaScript executes the code inside the function body (Block of code within curly brackets {} .
  • Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code).
  • The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).
  • The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function.
  • A function can call itself. It is said to be recursive function.
  • Remember that funcName() and window.funcName() is the same function.
  • 
    // Function definition/invoking Example 
    
    // function definition or declaration
    function createFullName() {
      let fname = "Brendan",
          lname = "Eich",
          fullname = fname + " " + lname;
          
      console.log(fullname)
    }
    
    // function invoking / calling
    createFullName()    
    
    
    OUTPUT
    
    Brendan Eich
    
    

    Function Arguments & Parameters

  • Information / data can be passed into functions as arguments.
  • An argument is the value that is sent to the function when it is called/invoked.
  • A parameter is the variable listed inside the parentheses () in the function definition.
  • Arguments/Parameters are specified after the function name, inside the parentheses (). You can add as many arguments/parameters as you want, just separate them with a comma ,
  • By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
  • To let a function return a value, use the return statement
  • What is the difference between return and console.log() ?

    The return keyword allows you to actually save the result of the output of a function as a variable.
    The console.log() function simply displays the output to web console, but doesn't save it for future use. console.log() doesn't return any value, as it returns undefined

    
    // function Parameters & Arguments
    
    // Two Parameters (fname & lname) used in function declaration
    function createFullName(fname, lname) {   
      let fullname = fname + " " + lname
      return fullname     // function returns a value
    }
    
    let firstName = "Brendan",
        lastName = "Eich";
    
    // Two Arguments used in function invoking   
    let funcReturn = createFullName(firstName, lastName)           
    console.log(funcReturn)
    
    
    OUTPUT
    
    Brendan Eich
    
    

    Default parameters

  • The most useful form is to specify a default value for one or more parameter.
  • Defaulting parameter values will creates a function that can be called with fewer arguments than it is defined to allow.
  • If we call the function without argument, it uses the default value.
  • 
    // Default function Parameter values
    
    function playerClub(club = "no one") {
      console.log(`I play for ${club}.`)
    }
    
    playerClub("Barcelona")
    playerClub()           // default parameter is set 
    playerClub("Al-Nassr")
      
    
    OUTPUT
    
    I play for Barcelona.
    I play for no one.
    I play for Al-Nassr.
    
    
  • The below example function can be called/invoked in several ways:
    1. [a]. giving only the mandatory argument: ask_ok('Enter the capital city: ')
    2. [b]. giving one of the optional arguments: ask_ok('Enter the capital city: ', 2)
    3. [c]. or even giving all arguments: ask_ok('Enter the capital city: ', 2, 'Just asked to enter city name!')
  • 
    // Default function Parameter values
    
    function ask_ok(place, retries=3, reminder='Please try again!') {
      while (true) {
        let city = prompt(place);
        if (city === 'Bengaluru' || city === 'Hyderabad' || city === 'Chennai') {
          return true
        }
        if (city === 'Kanpur' || city === 'Surat') {
          return false
        }
        retries = retries - 1;
        if (retries < 0) {
          console.log('invalid user response')
        }  
        console.log(reminder)
      }
    }
            
    // function invoking using only mandatory argument        
    ask_ok('Enter the capital city: ')
    
    
    OUTPUT
    
    Enter the capital city: Hyderabad
    true
    
    

    Recursion Function

  • A Recursion function is defined as a function that calls itself.
  • Recursion has the benefit of meaning that you can loop through data to reach a result.
  • The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
  • In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).
  • In the below example, factorial() is a function that we have defined to call itself ("recurse").
  • Suppose we want to find the factorial of 5, then it will goes as below:

    0! = 1
    1! = 1 x 0! = 1 x 1 = 1
    2! = 2 x 1! = 2 x 1 = 2
    3! = 3 x 2! = 3 x 2 = 6
    4! = 4 x 3! = 4 x 6 = 24
    5! = 5 x 4! = 5 x 24 = 120

    
    // Function recursion example
    
    function factorial(num) {
      let result = 0;
      if (num === 1) {
        return 1;
      } else {
        result = num * factorial(num-1);
        return result;
      }
    }
    
    let randNum = 5,
        funcRtn = factorial(randNum);
    
    console.log(`The factorial of ${randNum} is ${funcRtn}`)
    
    
    OUTPUT
    
    The factorial of 5 is 120
    
    

    Nested Function

  • A function within another function.
  • The nested (inner) function is private to its containing (outer) function.
  • Nested functions have access to the scope "above" them.
  • 
    // Nested Function Example  
    
    function indiaWorldCup() {
        const runScored = [317,350,322,301];
        function announceScores() {
            let matchNum = 1;
            function scoreBoard() {
                for (let run of runScored) {
                    console.log(`${matchNum} : Team India scored ${run} runs.`);
                    matchNum++;
                }
            }
            scoreBoard();
        }
        announceScores();
    }
    indiaWorldCup();
    
    
    OUTPUT
    
    1 : Team India scored 317 runs.
    2 : Team India scored 350 runs.
    3 : Team India scored 322 runs.
    4 : Team India scored 301 runs. 
    
    

    JavaScript Examples

    JavaScript Notes contains many examples for your understanding. With our online editor, you can edit and test each example yourself.

    Listed below are the links to the Examples
    Description of Example Links
    Display - Hello World Code
    Add internal JS to HTML Code
    Add inline JS to HTML Code
    Variables : let, var & const Code
    Data Types Code
    typeof Operator Code
    Aritmetic Operators Code
    Assignment Operators Code
    Comparison Operators Code
    Logical Operators Code
    Conditional Operator Code
    Decision Making Code
    Truthy & Falsy Code
    Arrays Code
    Array Methods - Part -1 Code
    Objects Code
    for Loop Code
    while Loop Code
    Function declaration & invoking Code
    Function parameters & arguments Code
    Function Block & Lexical scope Code
    Functions : Object Methods Code
    Function with try & Catch Code
    Function Expression Code
    Arrow Function Expression Code
    Nested & Callback Functions Code
    Default Params Code
    Array Methods - Part -2 Code
    spread Operator Code
    Destructuring Code

    JavaScript Interview Questions

    Get the hold of actual interview questions during job hiring.

    What is JavaScript, and how is it used in web development?

    JavaScript is a programming language that is used primarily to add interactivity and dynamic behavior to websites. JavaScript code can be embedded directly into HTML web pages or included in external script files, and it can be used to manipulate HTML and CSS, handle user input, and interact with web servers through APIs. JavaScript is a crucial component of modern web development, and it is used extensively in frameworks and libraries such as React, Angular, and Vue.

    What is the difference between null and undefined in JavaScript?

    null and undefined are both used to represent absence of a value, but they have slightly different meanings. Undefined is a value that is assigned to a variable that has not been initialized, or to a function parameter that has not been passed a value. Null, on the other hand, is a value that is explicitly assigned to a variable or object property to represent the absence of a value. In practice, null is often used as a default value when an object property is expected to be set later, while undefined is typically used to represent a programming error or oversight.

    What is hoisting in JavaScript, and how does it work?

    Hoisting in JavaScript is a feature that allows variables and functions to be declared after they are used in a program. This is possible because JavaScript uses two passes to interpret code: the first pass scans the code for variable and function declarations and "hoists" them to the top of their respective scopes, and the second pass executes the code. This means that a variable or function can be used before it is declared, as long as it is declared somewhere in the same scope. However, hoisted variables and functions are not initialized until their declaration statements are reached, so they may have the value "undefined" until they are explicitly assigned a value.

    What are the differences between JavaScript and other programming languages like Java and Python?

    There are several differences between JavaScript and other programming languages like Java and Python:

  • JavaScript is a scripting language, while Java and Python are compiled languages.
  • JavaScript is mainly used for web development, while Java and Python are used for a variety of applications, including web development, mobile app development, and data analysis.
  • JavaScript has a loose type system, while Java and Python have strict type systems.
  • JavaScript uses prototype-based inheritance, while Java and Python use class-based inheritance.
  • JavaScript is single-threaded, while Java and Python can support multithreading.
  • What are arrow functions in JavaScript?

    Arrow functions are a concise way to define functions in JavaScript. They were introduced in ECMAScript 6 and provide a shorter syntax for defining functions compared to traditional function declarations. Arrow functions are also automatically bound to the scope of their parent function or the global scope, depending on how they are defined.

    What are the different types of events in JavaScript?

    There are many types of events in JavaScript, including mouse events (such as click, mouseover, and mouseout), keyboard events (such as keypress and keydown), form events (such as submit and change), and document and window events (such as load and resize).

    What is the purpose of the async/await keywords in JavaScript?

    The async/await keywords were introduced in ECMAScript 7 as a way to simplify asynchronous programming in JavaScript. Async/await allows developers to write asynchronous code that looks and behaves like synchronous code, making it easier to reason about and debug. Async/await works by allowing developers to mark a function as asynchronous using the "async" keyword, and then use the "await" keyword to wait for a Promise to resolve before continuing with the execution of the code.

    What is the difference between a primitive data type and an object data type in JavaScript?

    A primitive data type is a value that is not an object and has no methods. Examples of primitive data types in JavaScript include numbers, strings, booleans, null, and undefined. An object data type, on the other hand, is a complex data type that can contain properties and methods. Examples of object data types in JavaScript include arrays, functions, and objects.

    What is a callback function in JavaScript?

    A callback function is a function that is passed as an argument to another function and is then executed when the parent function completes. Callback functions are commonly used in JavaScript for asynchronous programming tasks, such as handling events or making API calls.

    What is the event loop in JavaScript, and how does it work?

    The event loop in JavaScript is a mechanism that allows for asynchronous execution of code in a single-threaded environment. When an asynchronous operation is initiated, such as a network request or a timer, the operation is placed in a queue and the program continues to execute. When the operation is completed, a callback function is added to another queue. The event loop constantly checks the callback queue and executes any functions that are waiting, in the order they were added. This allows JavaScript to handle multiple asynchronous operations simultaneously, without blocking the main thread.

    What is closure in JavaScript, and how is it used?

    A closure in JavaScript is a function that has access to variables and functions defined in its outer scope, even after the outer function has returned. Closures are created when a function returns another function that references variables in its parent scope. This allows the inner function to access and modify the parent scope's variables, even though the parent function has already completed execution. Closures are often used to create private variables and functions in JavaScript, or to implement higher-order functions that return functions with customized behavior.

    What is the difference between let, const, and var in JavaScript?

    let and const are block-scoped declarations, while var is function-scoped. Variables declared with let and const cannot be redeclared in the same block, while var allows for redeclaration. Additionally, variables declared with const cannot be reassigned a new value, while let and var can be. Let and const are relatively new features of JavaScript that were introduced in ES6, while var has been part of the language since its inception.

    What is the difference between == and === in JavaScript?

    The double equals (==) operator in JavaScript compares two values for equality, allowing for type coercion if necessary. For example, the expression "5" == 5 would evaluate to true, because the string "5" is coerced into the number 5 for comparison. The triple equals (===) operator, on the other hand, compares two values for equality without type coercion, so the expression "5" === 5 would evaluate to false, because the types are different.

    What are the different data types in JavaScript?

    JavaScript has several primitive data types, including number, string, boolean, null, undefined, bigint and symbol. Additionally, JavaScript has a complex data type called object, which can store collections of key-value pairs and functions. Arrays are a special type of object that can store collections of values, and functions are a type of object that can be called like a regular function.

    What is a promise in JavaScript, and how does it work?

    A promise in JavaScript is an object that represents a value that may not be available yet, but will be resolved at some point in the future. Promises are used to handle asynchronous operations, such as network requests or database queries, and allow the program to continue executing while the operation is in progress. Promises have three states: pending, fulfilled, and rejected. When a promise is fulfilled, it means that the value is available and the promise's then() method is called with the value as an argument. When a promise is rejected, it means that an error occurred and the promise's catch() method is called with the error as an argument.

    What is the difference between call and apply in JavaScript?

    Both call() and apply() are methods in JavaScript that allow a function to be called with a specific value for the "this" keyword, and with arguments passed in as an array-like object. The main difference between call() and apply() is in how the arguments are passed in. With call(), the arguments are passed in as a comma-separated list, while with apply(), the arguments are passed in as an array. This means that apply() is useful when the number of arguments is not known ahead of time, or when the arguments are already in an array-like object.

    How do you declare a variable in JavaScript?

    You can declare a variable in JavaScript using the var, let, or const keyword, like this:

    
    var greet = 'Hello, world!';
    let num = 123;
    const PI = 3.14;
    
    

    What is the difference between a closure and a callback in JavaScript?

    A closure in JavaScript is a function that has access to variables and functions defined in its outer scope, even after the outer function has returned. A callback function, on the other hand, is a function that is passed as an argument to another function and is called at a later time, usually after some asynchronous operation has completed. While both closures and callbacks are used to handle asynchronous operations in JavaScript, closures are used to maintain access to variables and functions in the outer scope, while callbacks are used to execute a function after an operation has completed.

    What is the difference between let and var in JavaScript?

    The main difference between let and var in JavaScript is in their scoping. Variables declared with let are block-scoped, meaning they are only accessible within the block in which they are declared. Variables declared with var, on the other hand, are function-scoped, meaning they are accessible throughout the entire function in which they are declared. Additionally, variables declared with let cannot be redeclared in the same block, while var allows for redeclaration.

    What is the prototype in JavaScript?

    In JavaScript, every object has a prototype property, which is a reference to another object. This prototype object contains methods and properties that are inherited by the object.
    When a property or method is accessed on an object, JavaScript first looks for that property or method on the object itself. If the property or method is not found on the object, JavaScript then looks for it on the object's prototype. If the property or method is still not found, JavaScript continues the search up the prototype chain until it reaches the top level, which is typically the Object.prototype object.
    In other words, the prototype is a way to implement inheritance in JavaScript, allowing objects to inherit properties and methods from other objects. This can help simplify code and make it more efficient, by allowing objects to share common functionality without having to recreate it for each object. To create a new object with a specific prototype, you can use the Object.create() method, passing in the desired prototype object as an argument.

    What is event bubbling in JavaScript?

    Event bubbling is a mechanism in JavaScript where events propagate from the innermost to the outermost elements in the HTML DOM. When an event is triggered on an element, it is first handled by that element's event listener. If the event listener does not stop the event from propagating, the event then bubbles up to the element's parent, and so on until it reaches the top-level element.

    Event bubbling can be useful for handling events on multiple elements with a common ancestor. However, it can also cause unintended consequences if not handled properly. To stop event bubbling, you can call the event.stopPropagation() method within the event listener.

    What is the difference between let and const in JavaScript?

    The main difference between let and const in JavaScript is in their mutability. Variables declared with let can be reassigned a new value, while variables declared with const cannot be reassigned. Additionally, variables declared with const must be initialized with a value at the time of declaration, while variables declared with let can be initialized later. Both let and const are block-scoped, meaning they are only accessible within the block in which they are declared.

    What is the difference between synchronous and asynchronous programming in JavaScript?

    Synchronous programming in JavaScript refers to a style of programming where each statement is executed in turn, and the program waits for each statement to complete before moving on to the next one. Asynchronous programming, on the other hand, refers to a style of programming where operations can run in the background while the program continues to execute. Asynchronous programming is often used for I/O operations, such as reading or writing to a file, or making a network request, where the operation can take a long time to complete.

    What is the difference between a for loop and a forEach loop in JavaScript?

    A for loop in JavaScript is a traditional loop structure that iterates over a set of values using a counter variable. A forEach loop, on the other hand, is a method on the Array object that allows you to iterate over each element in an array and perform an action on each element. The main difference between the two is that a for loop is more flexible and can be used for iterating over any set of values, while a forEach loop is specifically designed for iterating over arrays. Additionally, a forEach loop cannot be interrupted or stopped in the middle, while a for loop can be exited using a break statement.

    What is the difference between a regular function and an arrow function in JavaScript?

    The main difference between a regular function and an arrow function in JavaScript is in their syntax and the way they handle the this keyword. Arrow functions have a shorter syntax than regular functions, and they do not bind their own this keyword. Instead, the this keyword in an arrow function refers to the value of this in the context in which the arrow function was defined. This can be useful for avoiding the common "this" pitfalls that can arise with regular functions.

    What is the difference between a callback function and a promise in JavaScript?

    A callback function is a function that is passed as an argument to another function, and is typically used for handling asynchronous operations in JavaScript. A promise, on the other hand, is an object that represents the eventual completion of an asynchronous operation, and provides a more structured and flexible way of handling asynchronous code. While both callback functions and promises can be used for handling asynchronous operations in JavaScript, promises are generally considered to be more flexible and easier to reason about, especially when dealing with complex asynchronous workflows.

    What are the four principles of object-oriented programming?

    The four principles of object-oriented programming are inheritance, encapsulation, abstraction, and polymorphism. Inheritance allows objects to inherit properties and methods from other objects. Encapsulation is the practice of keeping an object's internal state and behavior hidden from the outside world. Abstraction is the practice of simplifying complex systems by breaking them down into smaller, more manageable parts. Polymorphism allows objects to take on multiple forms or behaviors depending on the context in which they are used.

    What is the difference between the innerHTML and textContent properties in JavaScript?

    The innerHTML property in JavaScript allows for the manipulation of the HTML content inside an element, including tags and attributes. The textContent property, on the other hand, only returns the text content of an element, without any HTML tags or attributes. It is generally recommended to use textContent when dealing with text-only content, and innerHTML when dealing with HTML content that may contain tags and attributes.

    What is the purpose of the "use strict" directive in JavaScript?

    The "use strict" directive in JavaScript enables strict mode, which is a set of rules that must be followed in order to write secure and efficient JavaScript code. In strict mode, certain JavaScript features that are considered error-prone or dangerous are disabled, and stricter rules are enforced for variable declaration, function invocation, and other aspects of the language. Using strict mode can help to prevent common coding mistakes and improve the overall quality of JavaScript code.

    What is the difference between the spread operator (...) and the rest operator (...) in JavaScript?

    The spread operator (...) in JavaScript is used to expand an iterable (such as an array or a string) into individual elements. It is often used to pass the contents of an array or an object as arguments to a function or to concatenate arrays. The rest operator (...), on the other hand, is used to capture a variable number of arguments passed to a function into an array. It is often used in function declarations to allow for a variable number of arguments to be passed to the function.

    What is the purpose of the "this" keyword in JavaScript?

    The "this" keyword refers to the current execution context, which is typically the object that the function is a method of. It is often used to access or manipulate properties of the current object within a method, or to bind a function to a specific object. The behavior of the "this" keyword can be affected by the way in which a function is called, such as with the "call" or "apply" methods, or by using arrow functions, which bind the "this" keyword to the lexical scope of the function.

    What is the purpose of the "use strict" directive in JavaScript?

    The "use strict" directive in JavaScript is a feature introduced in ECMAScript 5 that enables strict mode, which is a stricter version of JavaScript that eliminates some silent errors and enforces stricter coding standards. In strict mode, certain actions that were previously ignored or silently failed will now throw errors, making it easier to write more reliable and secure code. The "use strict" directive is typically placed at the beginning of a JavaScript file or function to enable strict mode for that scope.

    What is a generator function in JavaScript?

    A generator function in JavaScript is a special type of function that can be paused and resumed, allowing for the generation of a sequence of values on demand. Generator functions are declared using the "function*" syntax and use the "yield" keyword to produce a value and pause execution. They can also receive input values when resumed using the "next" method.

    How do you define a function in JavaScript?

    You can define a function in JavaScript using the function keyword, like this:

    
    function myFunction(parameter1, parameter2) {
      // Code to perform the task
      return result;
    }
    
    

    What is an event in JavaScript?

    An event in JavaScript is an action that occurs on a web page, such as a mouse click or a key press.

    What is the DOM in JavaScript?

    The DOM (Document Object Model) in JavaScript is a hierarchical representation of a web page's HTML structure, which can be manipulated using JavaScript.

    How do you access an element in the DOM using JavaScript?

    You can access an element in the DOM using JavaScript using methods such as document.getElementById(), document.querySelector(), or document.querySelectorAll().

    What is AJAX in JavaScript?

    AJAX (Asynchronous JavaScript and XML) in JavaScript is a technique used to update parts of a web page without reloading the entire page.

    What is a constructor function in JavaScript?

    A constructor function in JavaScript is a function that is used to create and initialize an object.