Javascript variables, types and operators

 JavaScript follows single line and multiline comment similar to C/C++/Java.

Java is dynamic typed language where variable types are determined during runtime. 

var a = 5 ;// variable can be declared using var keyword. Function scope variable
let b = 10 ;
const c = 20;
d = 8 ;// Global variable // not recommended as global variable are preserved throughout the program.

Example

function test()
{
    var a = 10; // local variable
    b = 20;// global variables
    {
        let c = 30; // block scoped variable
    }
    console.log(a); // prints 10
    console.log(b); // prints 20
    console.log(c); // error not accessible outside block.
}
test();
console.log(a);// error a not defined
console.log(b);// prints value of b  


const is also similar to let with only exception that is cannot be changed.
If we create variable using let or const, we cannot redeclare it.

While declaration it should be initialized compulsorily. 

 b = 20;// global variables
function test()
{
   
var a = 10; // local variable
    {
       
const c = 25;
    }  
   
console.log(a);
   
console.log(b);
   
console.log(c); /// Reference Error: c is not defined.
}


test();
//console.log(a);// error a not defined
console.log(b);// prints value of b 


/** Data Types
 * Integer
 * String - s1 = 'Jaro';
 * BigInt - 125n;
 * Boolean - true/ false
 * undefined
 * null
 * Symbol
 * Object
 *      - Instance Object
 *      - Array Object
 *      - Function Object
 * typeof - returns type of data/variable
 */
x = 35n; // BigInt
console.log(typeof x );
x = 'abc'; // String
console.log(typeof x );
x = undefined; // Undefined
console.log(typeof x );
x = Symbol('Something');
console.log(typeof x );// symbol


Objects in JavaScript: Examples

b = 20;// global variables
function test()
{
    var a = 10; // local variable
    {
        const c = 25;
    }  
    console.log(a);
    console.log(b);
    console.log(c); /// Reference Error: c is not defined.
}

// function Object
console.log(test)
console.log(test instanceof Object)
// Instance Object

let O1 = {

    name: 'Hari',
    age:35,
    rollNo: 101
}

console.log(O1); // { name: 'Hari', age: 35, rollNo: 101 }
console.log(typeof O1);// object
console.log(O1['name']);// Hari
console.log(O1.age);// accessed using . operator

// Array Object

let O2 = [1,2,3,4];
console.log(O2);
console.log(typeof O2);

console.log(Array.isArray (O2));

 Operators in JavaScript

// Operators

/**
 * 1) Arithimetic Operator - +, -, * , **, %, ++, --
 * 2) Assignment Operator = , +=, -= *=, /=, %=
 * 3) Comparision Operator ==, ===, !== , !=, >=,<=
 * 4) Logical Operator && ||
 * 5) Bitwise Operator & | ~ ^
 * 6) String Operator - toString() operator
 * 7) typeof Operator
 * 8) Other Operator
 */

let x = 1234
console.log(x/10); // provide 123.4 as in Maths
console.log(Math.floor(x/10)); // 123 removes quotient
console.log(1234%10);// modulus operator same as C
console.log(10.5%3) ; // 1.5 , it would be error in C
console.log(-10%2); //  -0 ; takes numerator sign
let k = 5;
let y = undefined;
y = k++;
console.log(k,y); // prints 6 and 5

Comparision Operator

/*comparision operator

    ==, !=, ===, !===, <, > , >= , <=

    New Opeators in Javascript
    === => strictly equal to
    !== => strictly not equal to
*/











== operator doesn't check type so here it returns true, as JavaScript change type of both the values. Hence, it is evaluated to true.

let x = 5 == '5';
console.log(x)

If we want to evaluate this strictly, then use strict === operator. In strict equal, there is no type conversion
let x = 5 === '5';
console.log(x)

PS C:\Users\hsapkota\OneDrive - Capgemini\Documents\Ineuron\JS> node "c:\Users\hsapkota\OneDrive - Capgemini\Documents\Ineuron\JS\Sample.js"
false

/*  NaN is a special value which signifies not
* a number, so it is not equal to any number
 *  even two Nan are not equal  
 */

 */
let x = NaN === 0;
console.log(x)

Returns false for any number. 

/*  null  is a special value which signifies null reference,  it is not 0 or false
 *  But if both are null then returns True. So it is different from NaN in that respect
 */
let x = null === null;
console.log(x)

However null and undefined are equal.

let x = undefined == null;
console.log(x)

Returns: True

With === it returns False.

/** null is of null type, but when we do typeof it
gives Object */

null is special address to show reference object
doesn't point any address.

Zero is a valid value.

It is highly recommended to use strict equal to in programming while comparison. 

In JavaScript empty string ( '') is treated as false.

/**
 * Logical Operators
 * !, &&, ||
 */

Follows the same rule as C.
x = !5

console.log(x)

It returns false for non-zero value. 
x = !false

console.log(x)

return True.

x = !NaN

console.log(x)

x = !undefined

console.log(x)

returns True in all case. 

undefined - can be represented as garbage value in C. 

/**
 * Interesting use case of !
 * We can convert any values into the boolean equivalent using ! operator
 */

x = !!undefined
console.log(x)

return false.
x = !!5
console.log(x)

return true.

Logical And

Important property 

In case of logical and (&&) Operator result depends upon all the expression if subsequent expression are true. 

Here ,
a = 5;
b = 6;
x = a > 0 && ++b;
console.log(x,a,b)

a is 5 so it is greater than 0, so condition evaluate to true and now it depends upon value of b which is 6. 

Since we are pre-incrementing b so it value becomes 7. So result is dependent on b. 

so, x will contain 7 and a and b will be 5 and 7. Output is 

7 5 7

For below, post increment case. 

a = 5;
b = 6;
x = a > 0 && b++;
console.log(x,a,b)

result will be 6 5 7 

Here, result is dependent on b which is 6 prior increment and updated to 7 which expression is evaluated, hence x becomes 6 and a and b evaluates to 5 and 7 respectively.

Let us take one more example. 

x = 4 > 0 && 3;
console.log(x)

Here, result depends on 3 as first condition is true. So, x will have value 3 in this case.  In C, it would return 1. 

as Logical operators always yield 1 and 0, this is different from JavaScript. This is same as Python.

More example, 
x = "seeta"  && "geeta";
console.log(x)

Output: geeta

Result is dependent on second expression so answer is geeta.

x = null  && "geeta";
console.log(x)

Here, output is null as it is interpreted as false. so, rest expression would be discarded.

Similarly, for || operator it would return geeta as result is dependent on next expression. 

for null and undefined case:
x = null  || undefined;
console.log(x)

It would return undefined as first expression is false and result depends on second expression. 

In case of NaN:

x = null  || NaN;
console.log(x)

Here output would be dependent on second expression, so x will have value Nan

 Bitwise Operators

For low level operation, bitwise operators are extremely useful as these are faster in execution time.
 
/**
 * Bitwise Operators
 *  & , | , ~ , ^
 *
 */
/**Incase of bitwise operators number is converted
into 32-bit binary equivalent */

x = 12 & 35
/**
 * 12 = 00000000 00000000 00000000 00001100
 * 35 = 00000000 00000000 00000000 00100011
 *
 * --------------------------------------------
 * 0    00000000 00000000 00000000 00000000
 */

console.log(x);

x = 12 | 35

/**
 * 12 = 00000000 00000000 00000000 00001100
 * 35 = 00000000 00000000 00000000 00100011
 *
 * --------------------------------------------
 * 47   00000000 00000000 00000000 00101111
 */

console.log(x);


/*bitwise not operator behavior*/

x = ~ 5;

/**Representation
 *x   00000000 00000000 00000000 00000101
     answer would be 2's complement of x

 *~x  11111111 11111111 11111111 11111010
 * --------------------------------------
 * difficult to find value ?
 * find 1s complement and add +1 to it.
* Actually ~ of a number and number are 2's complements
* so, -5 and 5 are 2's complement of each other
 * i.e 2's complement of 5 will be -5 and vice-versa
* ~x  11111111 11111111 11111111 11111010

x   00000000 00000000 00000000 00000101 - 1's complement
   +1
--------------------------------------------
     00000000 00000000 00000000 00000110     
 * 1's complement is inversion of ~x so would be x value
 * so ~x is negative of 5 lets say -x
 * + 1 means - (x + 1) this would be -6
 */
console.log(x)

Output = - 6

Left shift and right shift Operator:

x = 10
console.log(x<<1);
/**
 * x =      00000000 0000000 00000000 00001010
 * x << 1   00000000 0000000 00000000 00010100     -< insert 1 zero from left
 * -------------------------------------------
 * result = 20
 *
 * *x       00000000 0000000 00000000 00001010 -< insert 1 zero from right
 *  x >> 1  00000000 0000000 00000000 00000101
 * ----------------------------------------------
 *  result = 5
 * */
 console.log(x>>1)
 
Properties to remember.

Left shift will multiply the number with power of number of bits shifted
Right shift will divide the number with power of number of bits shifted

>>> - Unsigned value would be provided so it would be some unpredictable value.

Conversion to other number format

let x = 25;
console.log(x.toString(2)) # Binary
console.log(x.toString(8)) # Octal
console.log(x.toString(16))# Hexadecimal





Comments