Java Script

 

                              Java Script

 

Synchronous Java script :

In this java script programs run line by line sequentially.



 

Let :

 

var a=1;

var b=2;

console.log(a);

console.

 

Result:

1

2

 

Asynchronous :

Follows the non-sequential manner of the code execution and unexpected execution time of code.

 

var a = 1;

fetch(“/”,function({

console.log(“loaded page”)

})

Console.log(“a”);

 

Result :

1

Loaded

 

 

Ex:2

 

setTimeout Function

 

 

setTimeout(function(){

concole.log(“hello world”)

},1000)

 

 

 

 

 

 

 

Var a=1;

setTimeout(function(){

console.log(“helloi world”)

},1000)

Console.log(“a”);

 

Result :

1

Hello World

 

 

 

Here we don’t know how much time  setTimeout() will take and also don’t know how much time the fetch() will take , which is the example of asynchronous function.

 

 

Trick :

The handlers and asynchronous functions are put in a event queue and the normal functions are in execution stack.

 

Event queue waits till the execution stack is empty.Then the event queue is getting executed its content.

 

Handlers such as http request some functions like fetch , setTimeout are executed after the execution stack’s normal functions defined in the program.

 

 

 

Types and Javascript :

 

Dynamic Typing

``````````````

You donot tell the engine what type of data a variable holds, it figures it out while your code is running.

 

Variables can hold different types of value because it’s all figured out during execution.

 

 

Static typing :

 

Bool isNew =’hello’ ; //an error

 

Dynamic typing :

 

Var isNew=true; //no errors

isNew = ‘Yup !’ ;

isNew=1;

 

 

 

 

 

 

Primitive Types

 

6 primitive types.

 

Primitive type , A type of data that represents a single value. i.e. not an object.

 

1.Undefined :

Represents lack of existence.
(You shouldn’t set a variable to this)

 

2.Null :

Represents lack of existence.

(You can set a variuable for this)

 

3.Boolean :

True or false

4. Number :

Floating point number (There is always some decimals).Unlike other programing languages, there’s only one ‘number’ type…and it can make math weird.

 

5.String :

A sequence of characters both ‘’ and “” can be used.

 

6.Symbol :

Used in ES6 (the next version of javascript).

 

Conceptual Aside

Operator :

A special function that is syntactically (Written) differently.

 

Generally operators took two parameters and return one result.

 

Conceptual Aside Operator

Var a=3+4;

Concole.log(a);

 

Output :

7

 

 

Var a=3+4;

Function +(a,b){

Return //add the two #s

}

 

 

Var a=3+4;

+(3,4);

 

 

Var a=3+4;

+3 4;  //prefix notation

3 4+; //post fix notation

3 + 4; //Infix notation

 

Var a=4-3;

Console.log(a);

 

Var a=4>3;

Console.log(a); //return Boolean true or false

 

Output :

True

 

Operator precedence in java script

Which operator function is called first ?

Java script engine call the higher presedece operator function first.

 

Right associativity and left associativity :-

If the precedence is same , then we use the associativity rule.

 

Var a=3+4*5;

Console.log(a);

 

Multiplication has higer precedence.

So it will be 23.

 

 

Coercion :


Var a=’hello ‘+ ‘world’;

Console.log(a);


Output

Hello world //concartination

 

Var a=1+’2’;

Console.log(a);

 

Output :

12

 

Var a=’1’+’2’;

Console.log(a);

Output :

 

12

 

When java script find the + symbol between the string and number, it convert the number to string and concatenate both the string.

 

Java script is dynamically typed so it try to convert it to the value it wants. Because we are not explicitly telling what the value should be in this case.

 

Var a=1,b=’2’;

Console.log(a+b);

 

Output:

12

 

 

Comparison operator

Console.log(3<2<1);

(false<1)

(0<1)

 

But

In js prospective ans is true using presedency.

Console.log(true<3);

 

>Number(false)

0

>Number(“3”)

3

>Number(undefined)

NaN (Not a number)

>Number(null)

0

>3==3

True

>”3”==3

True

>false ==0

True

>var a=false;

Undefined

>a==0;

True

>null==0

False

>var a=0;

Var b=false;

If(a!==b)

{

       Console.log(‘They are not equal !’);

}

Else

{

Console.log(‘Equal. ‘);

}

 

//They are not equal !

 

a==b

a===b

 

 

Existence and Booleans :

 

>Boolean(undefined)

False

>Boolean(null)

False

>Boolean(“”)

False

 

Var a;

If(a)

{

Console.log(‘Something is there’);

}

 

***Whatever we write inside if parenthesis will convert into Boolean.

***If a is (undefined or null or empty (“”) or 0 == false), then if statement will fail.

A=0;

If(a ||a===0)

//a===0 à true

//a || true à false || true

//true

 

Default Values:

Function greet(name){

Console.log(‘Hello ‘+name);

}

Greet(‘sandeep’);

 

Op:

Hello sandeep

 

Function greet(name){

Console.log(name);

Console.log(‘Hello ‘+name);

}

Greet();

 

Op:

Undefined

 

Ø undefined || ‘hello’

“hello”

 

Ø “Hi” || “Hello”

Hi

 

Ø 0 ||1

0

 

Ø Null || “hello”

Hello

 

Framework Aside :

Library: jQuery

Framework : Angular JS

 

***A group of java script code that performs a task that intended to be reusable.

 

Objects and functions

Objects are collection of name value pairs.

 

 

Name

                              Name

                                        Name/value

                                        Name/value

                                        Name/value

Function “method”

|

Object  --  Object “Property” /another child object

|

Primitive “property”

 

***Object has property and methods.

Core object has some short of address in your computer’s memory and it has references to this properties and methods which also sit in computer’s memory.

 

How we access the property and function f object in memory let’s see…

 

 

Var person = new Object();

//this new object going to sit in memory

//Now I am going to create property and methods

 

person[“firstname”]=”Tony”;

//computed member access having precedence from left //to right and in top 3 in precedence table

//Operator take the object “person”

//and property “firstname”.And looks for the //property(“firstname”) on the object(“person”).

 

Person[“lastname]=”Mishra”;

 

Var firstNameProperty=”firstname”;

 

Console.log(person);

Console.log(person[firstNameProperty]);

 

Op:-

Ø Object

Tony

 

 

 

Another operator to access the object

 

Console.log(person.firstname);

//”.” Is the member access operator whose precedence is

//”left to right” and is on the second from the top

Op:

Tony

 

Console.log(person.lastname);

 

person.address=new Object();

//object sitting inside another object

person.address.street=”street 250”;

//member access operator “.” , left to right assc.

//person address called first and then street is accessed

person.address.city=”Kolkata”;

person.address.state=”wb”;

 

console.log(person.address.street);

console.log(person.address.city);

console.log(person[“address”][“street”]);

//again left to right associativity

 

//preferable always use the “.” Operator.

 

Object and Object Literals

var person=new Object();

var person= {};  //same as new object

//It’s a short hand not an operator

console.log(person);

 

 

Now I can initialize the object with property and all in one line inside curly braces.

 

Like :

------------------------------------------------------------------------

var person ={firstname: ‘Sandeep’,lastname: ‘Mishra’};

console.log(person);

//This is much faster actually

---------------------------------------------------------------

 

 

similar to

 

-----------------------------------------------------------

person=new Object();

person.firstname=”Sandeep”;

person.lastname=”Mishra”;

-------------------------------------------------------------

 

 

var person ={

firstname: ‘Sandeep’,

lastname: ‘Mishra’

};

console.log(person);

//This is much faster actually

 

 

Name and value pairs

var person ={

//name and value pairs

firstname: ‘Sandeep’,

lastname: ‘Mishra’,

address : {

                 //another object

                 street: ‘250 newtown’,

                 city: ‘Kolkata’,

                state: ‘wb’

      }

};

console.log(person);

//This is much faster actually

 

 

Using Function

 

var sandeep ={

//name and value pairs

firstname: ‘Sandeep’,

lastname: ‘Mishra’,

address : {

                 //another object

                 street: ‘250 newtown’,

                 city: ‘Kolkata’,

                state: ‘wb’

      }

};

 

Function greet(person)

{

 Console.log(‘Hi’ + person.firstname);

}

 

Greet(Sandeep);

 

Greet({

firstname: ‘Hary’,

lastname: ‘cool’

});

//creating an object instantly while calling greet function

//and passing it as parameter

 

 

//object literal syntax

Sandeep.address2={

Street: ‘333 secondst.”

}

 

op :

Hi sandeep

Hi Hary

 

//we learn a lot of syntax above.

//Its our choice what to use.

 

Faking Namespaces

 

Namespace :

Typically to keep variables and functions with the same name separate.

Js doesn’t have namespace.We don’t need even. We can fake it.

 

Var greet=’Hello!’;

Var greet=’Hola!’;

 

Console.log(greet);

 

Var English={};

Var Spanish={};

 

English.greet=’Hello!’;

English.greetings.greet=’Hello!’; //error

//left to right is the precedence

//starting from left greeting is undefined.So undefined is //passed to greet.So error.

//Solution is to first declare greeting object

//English.greetings={};

//English.greeting.greet=’Hello’;

//or

//var English={ greetings : {

                                          basic: ‘Hello!’

                          }};

 

Spanish.greet=’Hola!’;

//Here English and Spanish act as container.

//so as there will be no namespace confusion

Console.log(English);

 

 

Op

Hola!

 

 

 

JSON and Object Literals:

 

JSON : JavaScript Object Notation

Inspired by object literal syntax in java script. So called JSON.

 

Javascript object

 

Var objectliteral={

firstname: ‘Mary’,

isAProgrammer: true

}

Console.log(objectliteral);

 

***In previous years data was send through internet in various formats. And the format that was landed upon a while , that is XML.

 

 

<object>

                              <firstname>Sandeep</firstname>

                              <isAProgrammer>true</isAProgrammer>

</object>

 

Then the server will be have this information and will parse it out.That’s fine.

But when we are using download times , how much data we are using,this is a lot of extra unnecessary data.his is a huge amount of wastage of download bandwidth if we are dealing for lot of data.

 

So we go for json.

It’s just a string of data which looks like object literals.

 

{

“firstname”:”Sandeep”,

“isAProgrammer”:true

}

 

Pretty same like object literals.

 

JSON is a subset of a javascript object literal syntax.But the reverse is not true.

 

1.Converting js object literal to json string:

Var objectliteral={

firstname: ‘Mary’,

isAProgrammer: true

}

Console.log(JSON.stringify(objectliteral));

 

Converting JSON String to java script object literal

Var jsonValue=

JSON.parse(‘{“firstname”:”Sandeep”, isAProgrammer”:true}’);

 

Console.log(jsonValue);

 

 

Functions are object

First class functions:

Everything you can do with other types,you can do with functions.Assign them to variables,pass them around,create them on the fly.

 

Function Object:

Like any other objects in java script, it resides in memory.It is a special type of object though , because it has all the feature of normal object and has some other special properties.

 

You can attach properties and methods to a function. Why ?

This is just an object.So I can attach a primitive , a name value pair ,I could attach an object, could attach other function.

 

JS function object has some hidden special properties.Important ones are ,

 

NAME :

(optional and can be anonymus(if doesn’t have a name))

 

CODE:

“Invocable”()

 

 

Writing a function

Functions are actually objects in java script

 

Function()

{

Console.log(‘hi’);

}

 

Greet.language=’englisg’;

//added a property to object greet()

Console.log(greet)

Console.log(greet.language)  //English

 

 

Name :

Greet

Code:

Console.log(‘hi’); //invocable ()

 

 

Function Statements and function Expressions

 

Expression:

A unit of code that results in a value.

It doesn’t have to save to a variable.

 

Var a;

//A is sitting there in memory

 

Output console:

a=3;

>3

1+2; //valid expression

>3

A={greeting: ‘hi’};

>Object {greeting: ‘hi’};

 

 

 

 

2)

 

Var a;

If(a===3)

//if is a statement as no value is returned

// a===3 is an expression which results some value

{

}

 

3)

Function greet(){

Console.log(‘hi’);

}

 

Op:

//just a stamen .Not returning any vale

/its only on global execution context

 

 

 

4)

Greet();

 

//normal function run through execution phase

//not really do anything

Function greet(){

Console.log(‘hi’);

}

 

 

//its available in main memory now

 

//object will created

//its an expression which returns a value

//to store in anonymousGreet

Var anonymousGreet=function()

{

Console.log(‘hi’);

}

//function object is assigned to anonymousGreet

// anonymousGreet is a memory location

//which points to the function object

//here there is no name of function object

//so anonymous function

//we have reference it to variable name.

//code : Console.log(‘hi’);

anonymusGreed();

 

op:

hi

hi

5)

 

Greet();

 

//normal function run through execution phase

//not really do anything

Function greet(){

Console.log(‘hi’);

}

 

 

anonymusGreed();

 

 

//its available in main memory now

 

//object will created

//its an expression which returns a value

//to store in anonymousGreet

Var anonymousGreet=function()

{

Console.log(‘hi’);

}

//function object is assigned to anonymousGreet

// anonymousGreet is a memory location

//which points to the function object

//here there is no name of function object

//so anonymous function

//we have reference it to variable name.

//code : Console.log(‘hi’);

 

Op:

Hi

Uncaught error :undefined




Dot and bracket notation for object

-----------------------------------










The For Loop

-------------------------------------------

//for loop keeps running till the condition is true

for (let  rep = 1; rep <= 10; rep++) {

    console.log('text ${rep}');

}









Looping Array

-------------------------------------------------------------------------------------------

ex1 :

const testArray = [

    'India',

    'Kolkata',

    2019 - 2025,

    'Developer',

    ['Sandeep',  'Java', 'XYZ']

];


for(let I =0; I < 5; i++) {

console.log(testArray [i]);

}


using length

for(let I =0; I < testArray.length; i++) {

console.log(testArray [i]);

}


ex2 :

console.log(testArray[1], typeof testArray[1])


Assigning array vars to new array 

const types = [ ];

types.push(typeof testtArray[1])

types[1] = testArray[1]


Break and continue


break -- terminate whole loop


//only string is considered

//continues specify that particular iteration only will skip where cond not satishfied

for(let I =0; I < testArray.length; i++) {

  if(typeof testArray[I] !== 'string') continue;

console.log(testArray[i], typeof testArray[I])

}


//once number is found break the loop

for(let I =0; I < testArray.length; i++) {

  if(typeof testArray[I] !== 'number') break;

console.log(testArray[i], typeof testArray[I])

}



Looping backwards

--------------------



const test = [

    'India',

    'Kolkata',

    2019 - 2025,

    'Developer',

    ['Sandeep',  'Java', 'XYZ']

];


for(let I = (test.length - 1;I >=0; i--) {

    console.log(i, test[I]);

}



While loop

----------------------

var rep = 1

while (rep <= 10) {

console.log('test ${rep}');

rep ++;

}


let dice = Math.random()

let dice = Math.trunc(Math.random()*6)+1;

console.log(dice)

while(dice !=6) {

}







#JavaScript

#java script

#javascript

#frontEnd

#Front End

#frontend

Comments

Popular posts from this blog

Java Interview Preparation (conceptual)

Git Commands With Output Log

Java 8 Function Interface