Table of Contents

    Operators in JavaScript: Types and Usage Explained

    Operators in JavaScript: Types and Usage Explained

    Following operators available in JavaScript:

    • Assignment operators
    • Arithmetic operators
    • Comparison operators
    • Logical operators
    • String operators
    • Conditional operators
    Assignment Operators
    • Like most programming languages, = is the assignment operator
    • Variables can be declared either by key var and value OR simply by assigning values directly. Ex – var x = 42; OR x = 42 ;
    • Explicit type declaration is not necessary.
    • Same variable can be assigned values of different data types. To know the type of a variable, use typeof operator. Ex –
    var x = "hello"; 
            var x = true;
            console.log(typeof x); //returns Boolean
    Comparison Operators
    • JavaScript has operators like <, >, !=, >=, <= to compare 2 operands.
    • What is unique about JavaScript is the == and === operators?
    • == compares the operands and returns true without considering their data type. Ex: var a = 10, b= “10”;
    • if(a==b) results in true due to the same value they carry, but ignores data types differentiation.
    • However, if(a===b) results in false as they are of different data types.
    Standard Arithmetic Operators
    • Addition + Ex: [5 + 8]
    • Subtraction - Ex: [49 – 38]
    • Division / Ex: [ 49 / 7]
    • Multiplication * Ex: [28 * 2]

     

    More on Arithmetic Operators
    • Modulus % to return the remainder of a division – Ex: 50 % 7 is 1
    • Increment ++ to increment the operand itself by 1 – Ex: If x=4, x++ evaluates to 5
    • Decrement -- to decrement the operand itself by 1 – Ex: if x= 10, x—- evaluates to 9 
    Logical Operators

    AND &&, OR ||, NOT ! are the logical operators often used during conditional statements to test logic between variables.

    • Expr1 && Expr2 returns true if both are true, else returns false.
    • Expr1 || Expr2 returns true if either is true.
    • !Expr1 operates on single operand to convert true to false and vice versa.
    String Operator

    Operator + is used to concatenate strings. x = "Hello"; y = " World "; x + y; /* Returns “Hello World” */

    While concatenating, JavaScript treats all data types as strings even if values are of different data types.

    x = "Hello";
    y = 100;
    z = 333;
    x + y + z;  /*  Returns “Hello100333” */