Javascript training sample

Uploaded on

"Corporate training on Javascript" India, Srilanka, Bangladesh, middle east and ASEA. Contact for more information at

"Corporate training on Javascript" India, Srilanka, Bangladesh, middle east and ASEA. Contact for more information at

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide
  • Very age old language People assume it is similar to Java but it is not we will explain more in detail about this. Var that compiled time checked variables. So dynamic scripting. Number ,String , Object, null,undefined, boolean No int float double and other complex just 5 of them. Functions are Objects they can be passed. So delayed operation and state change. Passing function helps in creating DSL will talk later in depth. Object oriented with out creating classes, there is some unlearning that is needed which we will provide in our slides below. Annonymous Classes, JavaSwing are full of them but here in javascript programming it is back bone for good programming.
  • V8 scripting engine moved the javascript running environment out of browsers. Node js is like apache seerver which can render server scripts with Reflection in java – can be run through for-in loop.
  • function func() { varglobal_greet // same as -> var global_greet = undefined; alert( global_greet ); // "undefined" global_greet = "local"; alert( global_greet ); // "local" } //known as hoisting of variables, so it is a good practice to declare before than declaring any where when needed.


  • 2. Copyright of 2 JavaScript Basics ● Very Popular Language. ● Misunderstood programming language. ● Dynamic Scripting Language. ● Very few Language construct. ● OOPs and Functional programming support ** ● Doesnt have Classes and Function are first class Objects. * ● This is an advantage not deficiency ● Closure Support in Javascript for ages.
  • 3. Copyright of 3 Reasons for Popularity ● V8 Engine run out side browser ● Node.js as server component ● Out of box functional programming. ● Very cool open source software available. ● Popularity of Single screen applications. ● Rhino jav8 support for java. ● Mobile platforms based on basic javascript.
  • 4. Copyright of 4 JavaScript Objects ● Just 5 inbuilt objects ● null, undefined, String , number. ● Very few in built objects ( But not a drawback) ● Array , Date , etc. ● User defined objects can be defined. ● User defined objects can be persisted as JSON ● var variable_x = {}; // Basic Object. ● Add attributes to a black object. ● Gang of 4: perfect object composition 2 inheritance.
  • 5. Copyright of 5 Console output ● View in Chrome – ctrl-shift-J ● console.log(“prahalad, Lord's Bhakt”); ● Takes variable argument ● console.log(“prahalad”,1{}, {“lastName”:“das”,“firstName”:“prahalad”}); ● This will print all of them in one line. ● Console.dir( object ); this prints the whole object neatly in seperate lines.
  • 6. Copyright of 6 Prototype Step 1 ● Inheritance in JS exists using Prototype. ● Every Function you create has a prototype property. ● This protype is an empty. ● Convention OOPS ● First create class then create objects. ● Protype is Copy Object. ● Because of prototype there is less number of code. ● Need more 2 discuss on this later slides.
  • 7. Copyright of 7 eval is Evil ● Dynamic Instantiation have helped Languages ● Create framework. ● Extend and call classes that you dont know. ● THINK HOW TOMCAT instantiated your class without even knowing about the class. – By Class.forName in java ● But Eval does some thing similar. ● But javascript scope defination creates pain. ● Security concerns as the scope object could be compromised.
  • 8. Copyright of 8 Bug free Vs Speed ● Bugs are set back. ● Relook older code. ● Revist the requirement. ● Code changes have potential of breaking existing functionality of the application. ● We will spend more time reading than writing. ● So create code by patterns that are understood by the team. ● Unit testing is essential, it also helps in reading code.
  • 9. Copyright of 9 Minimize ● In Java code starts from main method. ● JS code starts the first line, as we keep including the js file it starts getting executed or recorded** ● Because of first pt, the application starts generating global variables. ● Weird gobal variable names by framework. ● $ - is the global variable created by jquery ● _ - is the global variable created by underscore.js ● So there are good posibility that we would be over writting the global variables.
  • 10. Copyright of 10 Minimize global contd. ● Global object accessed by this **outside function. ● Global variables becomes attribute to top object. For JS in browser it is “window” _global_var = “prahalad”; //note var not used console.log(window._global_var); console.log(this._global_var);//logic reused outside windows. ● Pattern use var to declare. function sumNumbers(x, y) { result = x + y;//result is global can conflict, with third party or your own script. return result;//BIG PROBLEM } var a1 = a2 = 0;//a1 is local a2 is global; instead use var a1,a2;
  • 11. Copyright of 11 Global contd.. ● Implied vs explicitly. ● Declared with “var” outside function explicit global variable. ● Delete Object – Only applied to Implied object only not for explicit objects. ● “delete” operator in javascript. delete a1;//deletes only implied objects not explicit objects. ● JUST NOTE: Strict mode can throw exception var global = (function () {return this;}());//*declare+exec Now “global” can now be used in browser and phonegap or serverscripts application.
  • 12. Copyright of 12 Global Contd.. ● Two slides before we discussed how JS is different from java(it starts from Main function) ● Here is an example. global_greet = "HELLO"; // global variable function func() { alert(global_greet); // "undefined" as in this scope global_var was in local scope var global_greet="Namaste"; //NOTE :Scope is pushed forward at start of function alert(global_greet); // local scoped kicked in } Func( );//creates own scope Javascript execution happens sequentially unlike Java.***
  • 13. Copyright of 13 Basic Language Constructs ● For Loop While loop remains same as other languages. ● “for-in” - prefered to iterate on Object. var house = {toilet: 2,bedRoom: 2,kitchen: 1,balcony=1,livingRoom=1,tvRoom=2}; for(var room in house){ console.log( room );} ● We can add function and variable on fly in javascript.*** ● So assume we added will it show original object or the prototype object. ● Interesting thing about JS vs Java & C++ ● In java you cant change behaviour of object while it is running. ● So transformer(movie) type CARS are never possible in java. – Very much possible in JS. – Possible in java to some degree by SPRING or Dynamic-PROXY. ● house.hasOwnProperty( room ) can check if it was manipulated.
  • 14. Copyright of 14 Basic Language Constructs ● Appending functionality across all objects. Refer & Explain Example – basic_prototype_all_objects.html ● Now you can append all the objects in the memory specific function. ● For example we want to add specific aspect or functionality across all Objects. ● For example : Clone, persistance etc cross object functionality. ● Inheritance in Java & C++ ● In java & C++ world we create class human and then create instance. ● Then common functionality of human becomes static variable. ● Inheritance in javascript. ● It is a true copy of single object. ● It is something like we all copied from Adam Or Eve. ● This basic difference between how JAVA/C++/.net world differ from JS world.
  • 15. Copyright of 15 Prototype can be dangerous ● We have seen that it effects all objects. ● Can potentially change all inbuilt object. if (typeof Object.prototype.overideFunction!== "function") { //checking if we are overriding existing functionality Object.protoype.overideFunction = function () { // implementation... }; } ● Now the above change we have a potential that we dont know which all object have changed.
  • 16. Copyright of 16 Change an Object at fly ● Blacket change is bad how @ specific change. function employee(eName,title,dob){ this.eName=eName; this.title=title; this.dob=dob; } var nmurthy=new employee("N.Murthy","Mentor",1750); employee.prototype.salary=null;//no hoisting for this. nmurthy.salary=1; var prince =new employee("Rajkumar","CEO in Making",1973); console.dir(nmurthy);console.dir(price);
  • 17. Copyright of 17 Ctnd... ● Change objects at fly. ● How we added salary variable to the employee class. ● We can remove the salary function. ● No hoisting happens for this, as scope happens.( price_ceo.html *** ) ● We can add function to an object. ● Now when compared this to more statically typed language it is a great advantange.
  • 18. Copyright of 18 Hoisting ● Hoisting becomes complex function firstFunction() {alert('global firstFunction');}; function secondFunction() {alert('global secondFunction2');}; function hoistingIssue() { console.log(typeof secondFunction); console.log(typeof firstFunction); secondFunction(); //firstFunction(); //will fail function secondFunction() {alert('local secondFunction');}//function hoisting var firstFunction = function () { alert('local firstFunction'); };//variable hoisting blank FirstFunction();//now it works, variable is posted with function type } hoistingIssue();//hoisting of local variable begins.
  • 19. Copyright of 19 Implied Type Casting ● false==0 -- true ● “XYZ”==true -- true ● false===0 --false ● Checks data type. ● Then compared value. ● Not check reference. ● Do you know you can return undefined ● Very useful most of the language dont have this feature function canReturnUndefined(){return undefined;// keyword }
  • 20. Copyright of 20 Tools & Convention ● Function called with new acts as constructor. ● Class starts with first letter CAPITAL. ● Private variable and private function starts with underscore. ● Note all these are not mandatory but a convension of this industry. ● Jsdoc most used to create js documentation of the API. ● Comment annotation used to create jsdoc. ● Google closurer tool to mimify
  • 21. Copyright of 21 Dynamic Language ● Most of the dynamic languages supports simplified object constructor. ● They hold attribute and function as attributes of hashmap. ● You can add attributes after the object is constructed. var pet = {};// add one property = "Pottu";// now add a method pet.getName = function () {return;}; We added attribute to my pet after it was created. delete;
  • 22. Copyright of 22 JavaScript Literals ● Above example literal object “json” var pet = { name: "Pottu", //literal seperator is, getName: function () { return; } }; ● Above object can be passed to any other languages could also be converted to respective languages Object. ● For example – gson for java. ● Few built-in constructor number(),Date(),String(),Object()
  • 23. Copyright of 23 JSon ● Literal presentation of object. ● Persisted and passed around network and database (mangoDB/clob rows). var data = JSON.parse(jstr);//objects get created ● So network application can pass object state in string format. var jsonstr = JSON.stringify(dog); ● We can get string persistable state of an Object.
  • 24. Copyright of 24 Similar to classes ● Pay attention to RED color keyword in code. var Person = function (name) { //implicit call var this={} = name; this.say = function () {//why implicit this was not created here and effected this? return "I am " +; }; //return this;//implicits }; ● Note “this” outside a function scope refers to global object like window or phonegap objects.
  • 25. Copyright of 25 JavaScript Constructor ● A function can be called with or with out new ● When called with new returns Object “this”. ● When called without new it executes function. ● This is very important concept to grab.CONSTRUCTOR.html*** ● When created with new it creates __proto__ attribute to understand if it was a function or an object from console. function human(name){//this={}; implicit = name; this.introduceHuman=function (){return "HI i am ";}}//return this; var nonNewPrahalad = human("Prahalad"); var newPrahalad = new human("Prahalad");console.dir( newPrahalad );console.dir( nonNewPrahala d );//returns undefined. human.prototype.sayBye = function () {return "Bye Bye" ;};//add attr&Function
  • 26. Copyright of 26 Constructors and Convention ● Constructor if not used with convention can be disaster, if not use properly you will spend days debugging it SO PLEASE PAY ATTENTION. ● Project success has hundred fathers, for failed javascript project have a single father “Developer who dont understand this slide” ( JOKE ). Assume we have a global variable name in the above example. name = "God";//global variable function Human(name){//check the function with capital letter(so Class) = name;//change global variable this.introduceHuman=function (){ return "HI i am ";} } Human(“prahalad”);//this will change global variable.(note: new operator not used) console.log("Told u to use new operator, so god is now : "+ name);
  • 27. Copyright of 27 Avoid Problem with that function Human(name) { var that = {}; = name; that.introduce= function(){ return “Hey my name”; } return that; }//GOOD PATTERN MUST FOLLOW THIS ● That helped me a lot as what ever i write i would not cpawanPutrahange the global variable. ● So my code remains safe. ● “that” is not a key word – name convention
  • 28. Copyright of 28 Force Function call 2 Constructor ● We can force function call to constructor call. ● “instanceof” operator does work to check if they used constructor. function Human(name){ if ( !(this instanceof Human) ) { return new Human(); // trick is here }//another better way is = new arguments.callee( ) ** bit advance concept. not completed } var instance = Human(“prahalad”); ● You always create object inspite of not using new operator. Good for API developers.
  • 29. Copyright of 29 Call Backs!! ● All major framework use this concept. ● You dont call me I will you, when time and scenario arrive. ● Servlet Container call your Servlet in JAVA. ● So how call back in java function i_will_call_you_Back(registered_callback) { // can do something... registered_callback();//can check if it is a “function” before you fire it. // post call back operation like reply object handling }
  • 30. Copyright of 30 Paid Training ● Contact ● Note this is a paid Training. ● This slide is just to show case our depth of understanding in this subject. ● It is a complete 3 days training. ● Training includes training handout(hardcopy), worksheet & practice examples also.
  • 31. Copyright of 31