Author: admin

  • JavaScript – Bitwise Operators

    JavaScript Bitwise Operators

    The bitwise operators in JavaScript perform operations on the integer values at the binary level. They are used to manipulate each bit of the integer values. Bitwise operators are similar to logical operators but they work on individual bits.

    JavaScript bitwise operators works on 32-bits operands. In JavaScript, numbers are stored as 64-bit floating point number. JavaScript converts the numbers to 32-bit signed integer before performing the operation. After bitwise operation, it converts the result to 64-bits number.

    There are seven bitwise operators in JavaScript. Following is the list of bitwise operators with description.

    OperatorNameDescription
    &Bitwise ANDReturns 1 if both bits are 1, otherwise 0.
    |Bitwise ORReturns 1 if either bit is 1, otherwise 0.
    ^Bitwise XORReturns 1 if both bits are different, otherwise 0.
    !Bitwise NOTReturns 1 if bit is 0, otherwise 0.
    <<Left ShiftShifts the bits left by pushing zeros in from right and discarding leftmost bits.
    >>Right ShiftShifts the bits right by pushing copies of leftmost bit in from left and discarding rightmost bits.
    >>>Right Shift with ZeroShifts the bits right by pushing zeros in from left and discarding rightmost bits.

    JavaScript Bitwise AND (&) Operator

    The bitwise AND (&) operator performs AND operation on each pair of bits of its integer operands. After the operation, it returns a new integer value with the updated bits.

    When bitwise AND operator is applied on a pair of bits, it returns 1 if both bits are 1, otherwise returns 0.

    Following is the truth table for bitwise AND operation −

    ABA & B
    000
    010
    100
    111

    Let’s understand bitwise AND operation taking an example of 4-bit operands.

    ABA & B
    111100010001
    111100100010
    111101000100
    111110001000

    Example

    Let’s perform bitwise AND (&) operation on 5 and 7. These numbers are represented as 32-bits integer.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 & 700000000000000000000000000000101 (= 5)

    The resultant value of the OR operation of each bit of the 101 and 111 binary numbers is the same as below.

    • 1 & 1 = 1
    • 1 & 0 = 0
    • 1 & 1 = 1

    So, the resultant binary number is 111, which is equal to 7 in the decimal representation.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a & b = "+(a & b);</script></body></html>

    It will produce the following result −

    a & b = 5
    

    JavaScript Bitwise OR (|) Operator

    The bitwise OR (|) operator performs OR operation on each pair of bits of its integer operands. After the operation, it returns an integer value with the updated bits.

    When bitwise OR operator is applied on a pair of bits, it returns 1 if either of bits is 1, otherwise returns 0.

    Following is the truth table for bitwise OR operation.

    ABA | B
    000
    011
    101
    111

    Let’s understand bitwise OR operation taking an example of 4-bit operands.

    ABA | B
    111100011111
    111100101111
    111101001111
    111110001111

    Example

    Let’s perform bitwise OR (|) operation on 5 and 7. These numbers are represented as 32-bits integer.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 | 700000000000000000000000000000111 (= 7)

    The resultant value of the OR operation of each bit of the 101 and 111 binary numbers is the same as below.

    • 1 | 1 = 1
    • 1 | 0 = 1
    • 1 | 1 = 1

    So, the resultant binary number is 111, which is equal to 7 in the decimal representation.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a | b = "+(a | b);</script></body></html>

    It will produce the following result −

    a | b = 7
    

    JavaScript Bitwise XOR (^) Operator

    The bitwise XOR (^) operator performs exclusive OR operation on each pair of bits of its integer operands. After the operation, it returns an integer value with the updated bits.

    When bitwise XOR operator is applied on a pair of bits, it returns 1 if both bits are different, otherwise returns 0.

    Following is the truth table for Bitwise XOR operation −

    ABA ^ B
    000
    011
    101
    110

    Example

    Let’s perform bitwise XOR (^) operation on 5 and 7.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 ^ 700000000000000000000000000000010 (= 2)

    After performing the bitwise XOR operation of 101 and 111, the resultant binary number is given below.

    • 1 ^ 1 = 0
    • 1 ^ 0 = 1
    • 1 ^ 1 = 0

    So, the resultant binary number is 010, which is equal to 2.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a ^ b = "+(a ^ b);</script></body></html>

    It will produce the following output −

    a ^ b = 2
    

    JavaScript Bitwise NOT (~) Operator

    The bitwise NOT (~) operator performs the NOT operation on each bit of the binary number. It is a unary operator that inverts each bit of the binary number and returns the 2s complement to the binary number.

    Following is the truth table for the Bitwise XOR operation.

    Input (A)Output (~A)
    01
    10

    Example

    Let’s perform bitwise NOT (~) operation.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    ~511111111111111111111111111111010 (= -6)
    ~711111111111111111111111111111000 (= -8)

    Try to execute the below code −

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="~a = "+(~a)+"<br>"+"~b = "+(~b)</script></body></html>

    It will produce the following output −

    ~a = -6
    ~b = -8
    

    Bitwise Left Shift (<<) Operator

    The JavaScript bitwise left shift (<<) operator moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros from the right and left most bits are discarded.

    Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on.

    Example

    When you left shift 5 (101) by 1, a value becomes 10 (1010). When you perform the left shift operation by 2 places, the resultant value is 20 (10100).

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    500000000000000000000000000001010 (= 10)
    500000000000000000000000000010100 (= 20)

    The following JavaScript program demonstrates the bitwise left shift operation −

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a << 1 = "+(a <<1)+"<br>"+"a << 2 = "+(a <<2);</script></body></html>

    It will produce the following output −

    a << 1 = 10
    a << 2 = 20
    

    Bitwise Right Shift (>>) Operator

    The bitwise right shift (>>) operator moves all the bits in its first operand to the right by the number of places specified in the second operand. It inserts copies of leftmost bit in from left and discard rightmost bits. In this way it preserves the sign of the number.

    In short, it removes the N last bits from the number. Here, N is a second operand. Right-shifting the binary number is equivalent to dividing the decimal number by 2.

    Example

    In the below example, when we perform the right shift operation on 101 for the first time, the value of a becomes equal to 010. After performing the right-shift operation for the second time, the resultant value is 001, equal to 1 in the decimal representation.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    5 >> 100000000000000000000000000000010 (= 2)
    ~511111111111111111111111111111010 (= -6)
    ~5 >>111111111111111111111111111111101 (= -3)

    Try to execute the following program −

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a >> 1 = "+(a >>1)+"<br>"+"~a >> 1 = "+(~a >>1);</script></body></html>

    It will produce the following output −

    a >> 1 = 2
    ~a >> 1 = -3
    

    Bitwise Right Shift with Zero (>>>) Operator

    The Right Shift with Zero (>>>) operator is very similar to the right shift operator. It always fills the left bits with zero without worrying about the sign of the bit.

    Example

    Here, the binary representation of 10 is 1010. When we perform the right shift with zero operation, it moves all bits 2 times in the right direction and inserts two 0 at the start. So, the resultant value will be 0010, equal to 1.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    5 >>> 100000000000000000000000000000010 (= 2)

    The following JavaScript program demonstrate the use of >>> operator.

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a >>> 1 = "+(a >>>1);</script></body></html>

    It will produce the following result −

    a >>> 1 = 2
    

    You may try to use the different inputs with each operator and observe the output for more practices.

  • JavaScript – Logical Operators

    JavaScript Logical Operators

    The logical operators in JavaScript are generally used with Boolean operands and return a boolean value. There are mainly three types on logical operators in JavaScript – && (AND), || (OR), and ! (NOT). These operators are used to control the flow the program.

    Although the logical operators are typically used with Boolean values, they can be used with any type. For each non-boolean value, the operator converts to a boolean. The falsy values are converted to false and truthy values to true.

    There are six falsy values in JavaScript: false, null, undefined, 0 (zero), “” (empty string), NaN. The value other than falsy values are treated as truthy values. So non zero numbers, non-empty strings, etc., are truthy values.

    The && and || operators return the value of one of the operands based on condition. So if the operands are non-boolean, they return a non-boolean value. The ! operator always returns a Boolean value.

    The operands may be literals, variables or expressions. These are first evaluated to boolean equivalent before performing the logical operation.

    In the below table, we have given the logical operators with its description and example. Lets assume: x = true, y = false.

    OperatorDescriptionExample
    &&Logical AND(x && y) is false.
    ||Logical OR(x || y) is true.
    !Logical NOT!(x) is false.

    JavaScript Logical AND (&&) Operator

    The logical AND (&&) operator evaluates the operands from left to right. If the first operand can be converted to false, it will return the value of first operand, otherwise it will return the value of the second operand.

    x && y
    

    In the above expression if x is a falsy value then it will return the value of x otherwise it will return the value of y.

    The above rule is followed for all types of operands, whether they are Boolean values, numbers or strings, etc.

    Let’s first discuss with Boolean operands. In general, for a set of Boolean operands, it will return true if both operands are true else it returns false.

    true&&true;// returns truetrue&&false;// returns falsefalse&&true;// returns falsefalse&&false;// returns false

    For number operands, the && operator will return the first operand if it is flasy values (0, -0, and 0n), otherwise second operand.

    0&&10;// returns 010&&20;// returns 20 20&&0;// returns 0

    For string values, empty string is converted to false and non-empty string to true. Look at the below example.

    let str1 ='';let str2 ='Hello';let str3 ='World';  
    console.log(str1 && str2);// returns '' empty string
    console.log(str2 && str3);// returns World

    Let’s look how && operator works for null and undefined −

    null&&true// return nullundefined&&true// returns undefined

    For all above examples, you have noticed that if the first operand can be converted to false then it returns the value of first operand otherwise the value of second operand.

    Example

    Now let’s look at an example of a logical expression.

    <html><body><div id="output"></div><script>const x =3;const y =-2;
      document.getElementById("output").innerHTML = x >0&& y >2;</script></body></html>

    Here x > 0 is evaluated to true and y > 2 is evaluated to false. And the final expression becomes true && false which is evaluated as false.

    Multiple && Operators

    If we have multiple && operators in an expression, the && operator evaluates the expression from left to right and it converts each operand to a boolean value. If the result is false, then it returns the value of that operand and terminates the execution. If all the operands are truthy then it returns the value of the last operand.

    10&&null&&false;// returns nulltrue&&10&&20;// returns 20

    JavaScript Logical OR (||) Operator

    The logical OR (||) operator also evaluates the operands from left to right. If the first operand can be converted to true, it will return the value of first operand, otherwise it will return the value of the second operand.

    x || y
    

    In the above expression if x is a truthy value then it will return the value of x otherwise it will return the value of y.

    As || is a logical operator but it can be applied to any type of operand not only boolean.

    Let’s first discuss with Boolean operands. In general, for a set of Boolean operands, it will return flase if both operands are false else it returns true.

    true||true;// returns truetrue||false;// returns truefalse||true;// returns truefalse||false;// returns false

    For number operands, the || operator will return the first operand if it is truthy values (other than 0, -0, and 0n), otherwise second operand.

    0||10;// returns 1010||20;// returns 1020||0;// returns 20

    For string values, empty string is converted to false and non-empty string to true. Look at the below example.

    Example

    <html><body><div id="output"></div><script>let str1 ='';let str2 ='Hello';let str3 ='World';  
      document.getElementById("output").innerHTML = 
      str1 || str2 +"<br>"+
      str2 || str3;</script></body></html>

    Let’s look how && operator works for null and undefined −

    null||true;// returns trueundefined||true;// returns true

    For all above examples, you have noticed that if the first operand can be converted to true then it returns the value of first operand otherwise the value of second operand.

    Example

    Now let’s look at an example with expression −

    <html><body><div id="output"></div><script>const x =3;const y =-2;
      document.getElementById("output").innerHTML = x >0|| y >2;</script></body></html>

    Multiple || Operators

    We may have multiple || operators in an expression. The || operator evaluates the expression from left to right and it converts each operand to a boolean value. If the result is true, then it returns the value of that operand and terminates the execution. If all the operands are falsy then it returns the value of the last operand.

    null||10||false// returns 10false||null||undefined// returns undefined

    JavaScript Logical NOT (!) Operator

    The logical NOT (!) Operator is a unary operator. It returns false if the operand can be converted to true, otherwise it returns true.

    !x
    

    If x is truthy, the NOT (!) operator returns false. If the x is falsy then it returns true.

    Same as Logical AND, and OR operators, this logical NOT operator can also be used with non-boolean operands. But it will always return a Boolean value.

    Example

    <html><body><div id="output"></div><script>
      document.getElementById("output").innerHTML =!true+"<br>"+!false+"<br>"+!0+"<br>"+!20+"<br>"+!('Hello World')</script></body></html>

    Logical Operators Precedence

    An expression may have more than one logical operators in JavaScript. In such situation, the operators are evaluated on the basis of their precedence. The NOT (!) operator has the highest precedence. Then AND (&&) operator has the higher precedence than OR (||) operator.

    • Logical NOT (!)
    • Logical AND (&&)
    • Logical OR (||)

    Example

    Let’s check the following example −

    <html><body><div id="output"></div><script>
      document.getElementById("output").innerHTML =(false||true&&!false)// returns true</script></body></html>

    The logical NOT (!) operator has the highest precedence so !false is evaluated to true. Hence the expression now looks like “false || true && true”. The && has higher precedence than || so next “true && true” will be evaluated. Now the expression looks like “false || true”. Finally “false || true” will be evaluated to true.

    Short Circuit Evaluation

    Logical expressions are evaluated from left to right. These are tested for short-circuit evaluation. Following is the rule of short circuit evaluation −

    • false && any_value returns false
    • true || any_value retuns true

    The any_value part is not evaluated so it doesn’t have any effect on final result.

  • JavaScript – Comparison Operators

    JavaScript Comparison Operators

    The comparison operators in JavaScript compare two variables or values and return a boolean value, either true or false based on comparison result. For example, we can use the comparison operators to check whether two operands are equal or not.

    The comparison operators are used in logical expressions. A logical expression is evaluated to either true or false.

    The comparison operators are binary operators as they perform operations on two operands. The operands can be numerical, string, logical, or object values.

    There are eight comparison operators in JavaScript to perform different types of comparison. Here, we have given a table explaining each comparison operator with the example.

    OperatorDescriptionExample
    ==Equalx == y
    !=Not Equalx != y
    ===Strict equality (equal value and equal type)x === y
    !==Strict inequality (not equal value or not equal type)x !== y
    >Greater thanx > y
    <Less thanx < y<
    >=Greater than or Equal tox >= y
    <=Less than or Equal tox <= y

    How comparison is done?

    If both operands are of same type, the comparison operators compare the values. However, if the operands are of different types, JavaScript perform appropriate type conversion for the comparison. This is known as type coercion.

    The comparison is done by checking the numerical values of the operands if both the operands are numbers. The strings are compared based on lexicographical ordering, using Unicode values. The following type coercion is done when a string is compared with a number.

    • If the string contains only numeric value, it is converted to number type.
    • If the string contains non-numeric values as well, it will be converted to NaN.
    • If string is empty, it is converted to zero.

    The strict equality (===) and strict inequality (!==) operators perform strict comparison. These operators don’t perform type conversion before performing comparison operation.

    Dealing with falsy values

    There are some falsy values in JavaScript. JavaScript deals with these falsy values differently while performing the comparison. Followings are the flasy values −

    • 0 (zero)
    • false
    • ‘ ‘ or ” ” (Empty String)
    • null
    • undefined
    • NaN

    All comparison operators (excepts === and !==) converts false and empty string to zero before performing comparison.

    In addition to above, the less and, greater than operators (, >=) convert null to zero and undefined to NaN.

    JavaScript Equality (==) Operator

    The “equality” operator checks if the value of two operands are equal or not. It returns true if the operands are equal, otherwise it returns false. If the operands are of different types, it performs type conversion and then compare the operands.

    Lets look at some examples of comparison with no type conversion. The both operands are of same type.

    const a =10;const b =20;
    a ==10;//true
    a == b;// false "Hello"=="Hello";// true

    Now lets check some example of comparison with type conversion. Here the operands are of different types.

    5=='5';// true0==false;// true0=='';// true

    In the first example above, ‘5’ is converted to 5 (string to number conversion). The false and empty string (‘ ‘), are converted to zero (0) before comparison.

    Example

    The following code shows how to use equality operator in JavaScript −

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a == b);
      document.getElementById("output").innerHTML ="(a == b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    JavaScript Inequality (!=) Operator

    The “inequality” operator checks if the values of two operands are not equal. It returns true if the operands are not equal, otherwise it returns false. Same as the equality operator, type conversion is performed if the operands are not of same type.

    In the example below two values of same type are compared for inequality check. If the values are not equal, the inequality operator will return true.

    10!=10;// false10!=20;// true"Hello"!="Hello";// false

    Lets check for inequality when the operands are of different types.

    10!='10';// false0!=false;// false

    Here in first example, ’10’ is type casted to 10. Here string is converted to number type. In second example, false (Boolean value) is converted to zero (number).

    Example

    The following code shows how to use inequality operator in JavaScript.

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a != b);
      document.getElementById("output").innerHTML ="(a != b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    JavaScript Strict Equality (===) Operator

    The “strict equality” operator checks whether the values and data types of the two operands are equal or not. It returns true if both operands are equal and of same type.

    In other words, it checks the equality of the operands without the type conversion. If the operands are of different types, it returns false without further checking the value.

    10===10;// true10===20;// false'Hello'==='Hello';// true10==='10';// false0===false;// false

    Example

    The following code shows how to use strict equality operator in JavaScript.

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a === b);
      document.getElementById("output").innerHTML ="(a === b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    Strict Inequality (!==) Operator

    The “strict inequality” operator checks whether the two operands are not equal in value or type. It returns true if the operands are of same type but not equal or are of different types.

    Same as strict equality operator, it also first checks the inequality of operands without type conversion. If the operands are of different type, it will return true without further checking the value.

    10!==10;//returns false10!==20;// returns true'Hello'!=='Hello';// returns false10!=='10';//return true0!==false;//returns true

    Example

    The following code shows how to use strict inequality operator in JavaScript.

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a !== b);
      document.getElementById("output").innerHTML ="(a !== b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    JavaScript Greater Than (>) Operator

    The “greater than” operator checks if the value of the left operand is greater than the value of the right operand. If yes, it returns true otherwise it returns false.

    20>10;// true10>10;// false"ab">"aa";// true10>'5';// true

    Example

    The following code shows how to use greater than operator in JavaScript −

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a > b);
      document.getElementById("output").innerHTML ="(a > b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    Greater Than or Equal (>=) Operator

    The “greater than or equal” operator checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, it returns true otherwise false.

    10>=5;// true5>=5;// true"ab">="aa";// true10>='5';// true

    Example

    The following code shows how to use greater than or equal to operator in JavaScript.

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a >= b);
      document.getElementById("output").innerHTML ="(a >= b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    JavaScript Less Than (<) Operator

    The “less than operator” returns true if the value of the left operand is less than the value of the right operand, otherwise it returns false.

    10<20;// true5<5;// false"ab"<"aa";// true10<'5';// false

    Example

    The following code shows how to use less than operator in JavaScript −

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a < b);
      document.getElementById("output").innerHTML ="(a < b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    JavaScript Less Than or Equal (<=) Operator

    The less than or equal operator checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition becomes true.

    10<=20;// true5<=5;// true"ab"<="aa";// false10<='5';// false

    Example

    The following code shows how to use less than or equal operator in JavaScript −

    <html><body><div id="output"></div><script>const a =10;const b =20;let result =(a <= b);
      document.getElementById("output").innerHTML ="(a <= b) => "+ result;</script><p> Set the variables to different values and then try...</p></body></html>

    Comparing null, undefined and NaN

    In JavaScript, null, undefined and NaN are the falsy values that are not converted to zero (0) for the comparison.

    0==null;// returns false0==undefined;// returns false0==NaN;// returns false

    null and undefined are weekly equal.

    null==undefined;// returns truenull===undefined;// returns false

    The type of NaN is number but it is not equal to zero. Interestingly NaN is not equal to NaN itself.

    NaN==NaN;// returns false
  • JavaScript – Arithmetic Operators

    JavaScript Arithmetic Operators

    Arithmetic operators in JavaScript perform mathematical calculations on numeric values (operands). Most of the arithmetic operators are binary operators as they perform calculations on two operands. Some arithmetic operators are unary operators. The unary operators perform computation on a single operand.

    JavaScript supports many arithmetic operators such as addition, subtraction, multiplication, division operators, etc. It uses the common symbols for arithmetic operators such as “+” for addition, “” for subtraction, “*” for multiplication, “/ ” for division etc.

    The operands can be literals, variables or the expression.

    var z =3+5;// 3 and 5 are literal values.const x =3; y =5;var z = x + y ;// x and y are variables. var z =3+2*x  // expression

    In general, arithmetic operators are used to perform mathematical operations but they can be used for other operations as well. For example, the addition operator (+) can be used for string concatenation.

    Here, we have given a table containing the mathematical operators and explaining the functionality of each operator.

    OperatorNameDescription
    +AdditionAdds two operands
    SubtractionSubtracts the second operand from the first
    *MultiplicationMultiply both operands
    /DivisionDivide the numerator by the denominator
    %ModulusOutputs the remainder of an integer division
    ++IncrementIncreases an integer value by one
    DecrementDecreases an integer value by one

    Let’s discuss the different operators with the help of examples.

    JavaScript Addition (+) Operator

    The JavaScript addition (+) operator adds two numeric operands. It is denoted by the plus (+) symbol.

    var x =5, y =10;var sum = x + y;

    This operator can also be used to concatenate strings and/or numbers.

    var z ='10'+3// returns 103var z ='10'+'3'// returns 103
    • If one operand is string, the addition operator converts the other operand to string and concatenate it with first operand.
    • If both the operands are string, it just concatenates the second operand to the first operand.
    • If both operands are numeric values, it will return the numeric value.

    Example

    In the below example, we demonstrate adding two decimal numbers and concatenating the strings and numbers.

    <html><body><script>const x =3; y =5;var z = x + y ;
          document.write(z +"</br>");var z ='10'+3 
          document.write(z +"</br>");var z ='10'+'3';
          document.write(z +"</br>");</script></body></html>

    JavaScript Subtraction (-) Operator

    JavaScript subtraction (-) operator subtracts the right operand from the left operand and produces their difference. It is denoted by the minus (-) symbol.

    20-10;// returns 10'20'-10;// returns 10'20'-'10';// returns 10'20ee'-10;// returns NaNNaN-10// return NaNsInfinity-10// returns infinity
    • The subtraction operator uses numeric operands but can also be used for non-numeric operands such as strings.
    • If both operands are numbers, then resultant is number.
    • If any or both operands are strings (containing only numbers), it first converts the strings to number and then performs subtraction operations.
    • If string contains non numeric value, it will return NaN.
    • If any operand is NaN or Infinity, the result will be NaN or Infinity respectively.

    Example

    In the below example, we demonstrate the subtraction two decimal numbers and of other datatypes.

    <html><body><script>var x =20; y =10;var z = x - y ;
          document.write(z +"</br>");
          x ="20"; y ="10"
          z = x - y ;
          document.write(z +"</br>");
          x ="20ee"; 
          z = x - y ;
          document.write(z +"</br>");</script><p>Change the values of the variables and test the resultant values</p></body></html>

    JavaScript Multiplication (*) Operator

    The JavaScript multiplication operator multiplies two numbers (operands). It gives the product of two operands. It is denoted by the asterisk (*) symbol. If two operands are of same sign, the product is positive. If the two operands are of different sign, the product is negative.

    If any or both operands are string, it converts the string to number and then returns their product.

    Example

    In the example below, we demonstrate the use of multiplication operator on different types of operands.

    <html><body><script>var x =20; y =10;var z = x * y ;
          document.write(z +"</br>");
          x ="20"; y ="10"
          z = x * y ;
          document.write(z +"</br>");
          x ="20ee"; 
          z = x * y ;
          document.write(z +"</br>");</script><p>Change the values of the variables and test the resultant values</p></body></html>

    JavaScript Division (/) Operator

    The JavaScript division (/) operator divides the left operand (dividend) by the right operand (divisor) and returns the quotient. It is represented by the slash (/) symbol.

    20/10// returns 220/-10// return -2100/0// returns Infinity0/0// returns NaN

    Example

    Let’s demonstrate the use of division operator.

    <html><body><script>var x =20; y =10;var z = x / y ;
          document.write(z +"</br>");
          x ="20"; y ="10"
          z = x / y ;
          document.write(z +"</br>");
          z = x /0;
          document.write(z +"</br>");
          z =0/0;
          document.write(z +"</br>");</script><p>Change the values of the variables and test the resultant values</p></body></html>

    JavaScript Modulus (%) Operator

    The JavaScript modulus (%) operator returns the remainder when first operand is divided by the second operand. It is also known as remainder operator. It is denoted by the percent (%) symbol. It takes the sign of dividend. Lets take an example 5%3 gives 2 because when 5 is divided by 3, it gives remainder as 2.

    Example

    Let’s understand the modulus operator with the help of an example program.

    <html><body><script>var x =20%9;var y =-20%9;var z =20.43%9;var a =20%-9;var b =20%10;
          document.write(x +"</br>");
          document.write(y +"</br>");
          document.write(z +"</br>");
          document.write(a +"</br>");
          document.write(b +"</br>");</script></body></html>

    JavaScript Increment (++) Operator

    The JavaScript increment (++) operator increases the value of operand by one. It is an unary operator. It takes only one operand. It is denoted by double plus (++) sign.

    There are two types of increment operator in JavaScript −

    Prefix Increment Operator

    The prefix increment operator increments the value of the variable before its current value is used. For example,

    var x =10;var y =++x;// x is now 11 and y is also 11.

    Postfix Increment Operator

    The postfix increment operator increments the value of the variable after its current value is used. For example,

    var a =10;var b = a++;// a is now 11 but b is 10.

    Here, in the second line of the above code, first the current value of a is assigned to b, then it is incremented.

    Lets look at the following example −

    <html><body><script>var x =10;var y =--x;//prefix decrementvar a =10;var b = a--;// postfix decrement
    	  document.write("x = "+ x);
          document.write(" y = "+ y +"<br>");
          document.write("a = "+ a);
          document.write(" b = "+ b +"<br>");</script><p>Change the values of the variables and check the results</p></body></html>

    JavaScript Decrement (–) Operator

    The JavaScript decrement (–) operator decreases the value of operand by one. It is also an unary operator, i.e., it takes only one operand. It is denoted by double minus (–) sign.

    There are two types of decrement operator in JavaScript −

    Prefix Decrement Operator

    The prefix decrement operator decrements the value of the variable before its current value is used. For example,

    var x =10;var y =--x;// x is now 9 and y is also 9.

    Postfix Decrement Operator

    The postfix decrement operator decrements the value of the variable after its current value is used. For example,

    var a =10;var b = a--;// a is now 9 but b is 10.

    Here, in the second line of the above code, first the current value of a is assigned to b, then it is decremented.

    Lets look at the following example −

    <html><body><script>var x =10;var y =--x;//prefix decrementvar a =10;var b = a--;// postfix decrement
    	  document.write("x = "+ x);
          document.write(" y = "+ y +"<br>");
          document.write("a = "+ a);
          document.write(" b = "+ b +"<br>");</script><p>Change the values of the variables and check the results</p></body></html>

  • JavaScript – Operators

    What is an Operator?

    In JavaScript, an operator is a symbol that performs an operation on one or more operands, such as variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and + is called the operator.

    JavaScript supports the following types of operators.

    • Arithmetic Operators
    • Comparison Operators
    • Logical (or Relational) Operators
    • Bitwise Operators
    • Assignment Operators
    • Miscellaneous Operators

    Lets have a look on all operators one by one.

    JavaScript Arithmetic Operators

    The JavaScript arithmetic operators are used to perform mathematical calculations such as addition, multiplication, subtraction, division, etc. on numbers. JavaScript supports the following arithmetic operators −

    Assume variable x holds 10 and variable y holds 20, then −

    OperatorDescriptionExample
    + (Addition)Adds two operands.x + y will give 30.
    – (Subtraction)Subtracts the second operand from the first.x – y will give -10.
    * (Multiplication)Multiplies both operands.x * y will give 200.
    / (Division)Divides the numerator by the denominator.y / x will give 2.
    % (Modulus)Outputs the remainder of an integer division.y % x will give 0
    ++ (Increment)Increases an integer value by one.x++ will give 11.
    — (Decrement)Decreases an integer value by one.x– will give 9.

    Addition operator (+) works for Numeric as well as Strings. e.g. “a” + 10 will give “a10”.

    JavaScript Comparison Operators

    The JavaScript comparison operators compare two values and returns a boolean result (true or false). JavaScript supports the following comparison operators −

    Assume variable x holds 10 and variable y holds 20, then −

    OperatorDescriptionExample
    == (Equal)Checks if the value of two operands is equal or not. If yes, then the condition becomes true.(x == y) is not true.
    != (Not Equal)Checks if the value of two operands is equal or not. If the values are not equal, then the condition becomes true.(x != y) is true.
    === (Strict equality)It checks whether the value and data type of the variable is equal or not. If yes, then the condition becomes true.(x === y) is not true.
    !== (Strict inequality)It checks whether the value and data type of the variable is equal or not. If the values are not equal, then the condition becomes true.(x !== y) is true.
    > (Greater than)Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition becomes true.(x > y) is not true.
    < (Less than)Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition becomes true.(x < y) is true.
    >= (Greater than or Equal to)Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition becomes true.(x >= y) is not true.
    <= (Less than or Equal to)Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition becomes true.(x <= y) is true.

    JavaScript Logical Operators

    The logical operators are generally used to perform logical operations on boolean values. But logical operators can be applied to values of any types not only boolean.

    JavaScript supports the following logical operators −

    Assume that the value of x is 10 and y is 0.

    OperatorDescriptionExample
    && (Logical AND)If both the operands are non-zero, then the condition becomes true.(x && y) is false
    || (Logical OR)If any of the two operands are non-zero, then the condition becomes true.(x || y) is true.
    ! (Logical NOT)Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.!x is false.

    JavaScript Bitwise Operators

    The JavaScript bitwise operators are used to perform bit-level operations on integers. JavaScript supports the following seven types of bitwise operators −

    Assume variable x holds 2 and variable y holds 3, then −

    OperatorDescriptionExample
    & (Bitwise AND)It performs a Boolean AND operation on each bit of its integer arguments.(x & y) is 2.
    | (Bitwise OR)It performs a Boolean OR operation on each bit of its integer arguments.(x | y) is 3.
    ^ (Bitwise XOR)It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.(x ^ y) is 1.
    ~ (Bitwise Not)It is a unary operator and operates by reversing all the bits in the operand.(~y) is -4.
    << (Left Shift)It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on.(x << 1) is 4.
    >> (Right Shift)Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.(x >> 1) is 1.
    >>> (Right shift with Zero)This operator is just like the >> operator, except that the bits shifted in on the left are always zero.(x >>> 1) is 1.

    JavaScript Assignment Operators

    In JavaScript, an assignment operator is used to assign a value to a variable. JavaScript supports the following assignment operators −

    OperatorDescriptionExample
    = (Simple Assignment)Assigns values from the right side operand to the left side operandz = x &plus; y will assign the value of x &plus; y into z
    &plus;= (Add and Assignment)It adds the right operand to the left operand and assigns the result to the left operand.z &plus;= x is equivalent to z = z &plus; x
    = (Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the left operand.z -= x is equivalent to z = z – x
    &ast;=(Multiply and Assignment)It multiplies the right operand with the left operand and assigns the result to the left operand.z &ast;= x is equivalent to z = z &ast; x
    /= (Divide and Assignment)It divides the left operand with the right operand and assigns the result to the left operand.z /= x is equivalent to z = z / x
    %= (Modules and Assignment)It takes modulus using two operands and assigns the result to the left operand.z %= x is equivalent to z = z % x

    Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

    JavaScript Miscellaneous Operators

    There are few other operators supported by JavaScript. These operators are conditional operator (? :), typeof operator, delete operator, etc.

    In the below table, we have given the JavaScript miscellaneous operators with its explanation.

    OperatorDescription
    ? : (Conditional )If Condition is true? Then value X : Otherwise value Y
    typeofIt returns the data type of the operand.
    ?? (Nullish Coalescing Operator)It returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
    deleteIt removes a property from an object.
    , (Comma)It evaluates its operands (from left to right) and returns the value of the last operand.
    () (Grouping)It allows to change the operator precedence.
    yieldIt is used to pause and resume a generator function.
    (Spread)It is used to expand the iterables such as array or string.
    ** (Exponentiation)Raises the left operand to the power of the right operand

  • JavaScript – Reserved Keywords

    Reserved Keywords in JavaScript

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

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

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

    varfunction="Hello";

    Reserved Keywords

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

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

    Reserved Keywords added in ES5 and ES6

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

    awaitclassenumexport
    extendsimportletSuper

    Removed Reserved Keywords

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

    abstractbooleanbytechar
    doublefinalfloatgoto
    intlongnativeshort
    synchronizedthrowstransientvolatile

    JavaScript Objects, Properties, and Methods

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

    JavaScript Built-in Objects

    ArrayArrayBufferBooleanDataView
    DateErrorevalFloat32Array
    Float64ArrayFunctionGeneratorGeneratorFunction
    Int8ArrayInt16ArrayInt32ArrayIntl
    JSONMapMathNumber
    ObjectPromiseProxyRangeError
    ReferenceErrorReflectRegExpSet
    StringSymbolSyntaxErrorTypeError
    Uint8ArrayUint8ClampedArrayUint16ArrayUint32Array
    URIErrorWeakMapWeakSet

    JavaScript Built-in Properties

    lengthconstructorprototype__proto__callercallee

    JavaScript Methods

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

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

    Other Reserved Keywords

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

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

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

    HTML Event Handlers

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

    Here, we have listed some of the event handlers.

    onclickondblclickonmouseoveronmouseout
    onmousemoveonkeydownonkeyuponkeypress
    onfocusonbluronchangeonsubmit
    onresetonloadonunloadonresize
    onscroll

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

  • JavaScript – Strict Mode

    Strict Mode in JavaScript

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

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

    Enabling Strict Mode

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

    'use strict';

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

    Why Use the Strict Mode?

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

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

    Strict Mode in the Global Scope

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

    Example

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

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

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

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

    Strict Mode in the Local Scope

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

    Example

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

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

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

    Mistakes that you should’t make in the strict mode

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    8. You can’t use escape characters.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    JavaScript Type Conversions

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

    There are two types of type conversion in JavaScript −

    • Implicit type conversion
    • Explicit type conversion

    The implicit type conversion is also known as coercion.

    Implicit Type Conversion

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

    Here are some examples of the implicit type conversion.

    Converting to String (Implicit conversion)

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

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

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

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

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

    Converting to Number (Implicit conversion)

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

    Boolean values are also gets converted to a number.

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

    Try the example below and check the output −

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

    Converting to Boolean (Implicit conversion)

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

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

    Null to Number (Implicit conversion)

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

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

    Undefined with Number and Boolean (Implicit conversion)

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

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

    Explicit Type Conversion

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

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

    Converting to String (Explicit conversion)

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

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

    Example

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

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

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

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

    Converting to Number (Explicit conversion)

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

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

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

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

    Example

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

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

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

    Converting to Boolean (Explicit conversion)

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

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

    Example

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

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

    Converting Date to String/Number

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

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

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

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

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

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

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

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

    Conversion Table in JavaScript

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

    ValueString conversionNumber conversionBoolean conversion
    0“0”0false
    1“1”1true
    “1”“1”1true
    “0”“0”0true
    “”“”0false
    “Hello”“Hello”NaNtrue
    true“true”1true
    false“false”0false
    null“null”0false
    undefined“undefined”NaNfalse
    [50]“50”50true
    [50, 100]“[50, 100]”NaNtrue
  • JavaScript – Data Types

    JavaScript Data Types

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

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

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

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

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

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

    • Object
    • Array
    • Date

    Why are data types important?

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

    For example, the below code generates the 1010 output.

    let sum ="10"+10;

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

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

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

    JavaScript String

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

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

    Example

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

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

    JavaScript Number

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

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

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

    Example

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

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

    Example (Exponential notation of numbers)

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

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

    JavaScript Boolean

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

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

    JavaScript Undefined

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

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

    JavaScript Null

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

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

    JavaScript Bigint

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

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

    JavaScript Symbol

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

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

    Example

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

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

    JavaScript Object

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

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

    Example

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

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

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

    JavaScript Array

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

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

    JavaScript Date

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

    Example

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

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

    Dynamic Types

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

    Example

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

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

    Checking Data Types Using the typeof Operator

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

    Example

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

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

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

    JavaScript const Keyword

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

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

    Declaring JavaScript Constants

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

    const x =10;// Correct Way

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

    const y;// Incorrect way
    y =20;

    Can’t be Reassigned

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

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

    Block Scope

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

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

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

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

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

    Constant Arrays and Objects in JavaScript

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

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

    Example (Constant Arrays)

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

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

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

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

    gate,window,roof,wall,fence
    

    Example (Constant Objects)

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

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

    It will produce the following result −

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

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

    No Const Hoisting

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

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

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

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

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

    Difference between var, let and const

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

    Comparison basisvarletconst
    ScopeFunctionBlockBlock
    HoistedYesNoNo
    ReassignYesYesNo
    Re-declareYesNoNo
    Bind ThisYesNoNo

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

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