Getting Started with Javascript

  • View
    1.138

  • Download
    0

Embed Size (px)

DESCRIPTION

This was prepared for delivering a session about Javascript to newbies.

Text of Getting Started with Javascript

Getting Started with JavaScript

Getting Started with

Akshay Mathur@akshaymathu

Ground Rules

Post on FB and Tweet nowDisturb Everyone during the sessionNot by phone ringsNot by local talksBy more information and questions

2

@akshaymathu

Lets Know Each Other

Do you code?OS?Programing Language?HTML?Javascript?JSON?Why are you attending?

@akshaymathu

3

After first session add lines

3

Akshay Mathur

Founding Team Member ofShopSocially (Enabling social for retailers)AirTight Neworks (Global leader of WIPS)15+ years in IT industryCurrently Principal Architect at ShopSociallyMostly worked with StartupsFrom Conceptualization to StabilizationAt different functions i.e. development, testing, releaseWith multiple technologies

@akshaymathu

4

JavaScript

Born in 1995 at NetscapeNot at all related to JavaSyntax influenced by CInterpreted ECMA scripting lanuageDynamically typedObject Oriented as well as FunctionalPrototype based

@akshaymathu

5

Typical Usage

Web programingClient sideWeb pagesBrowser pluginsServer sideSSJS (not in use)NodeJSPDF documentsDesktop WidgetsMongoDB

@akshaymathu

6

Language Reference

Comments

Single lineStarts with //Can also be used after a statementMulti lineStarts with /* and ends with */

@akshaymathu

8

Statements

Case sensitiveIgnore whitespaceSemicolon (;) is used as delimiter for statementsBlock of statements is delimited by curly braces ({})

@akshaymathu

9

Output

Visible to all using DOM functionsdocument.write(Hello);alert(How are you);

For developers in consoleconsole.log(This is working);

@akshaymathu

10

Variable

Explicitly defining is optionalJS runtime automatically defines as neededDefining all variables with var keyword is goodLoosely typedNo need to define the type (int, str etc.)Dynamically typedType changes at runtime as the value changes

var my_var = Hello;my_var = 6;

@akshaymathu

11

Data Types

String: 1, Hello! How are youNumber: 1, 2, 121.22Boolean: true, falseArray: [1, 1, false, {a: 10}]Object: {lang: JS, val: my_var}Null: nullUndefined: undefinedFunctions: function(){}Date: Mon, 23 Sep 2013 12:18:54 GMTtypeof 1 // String

@akshaymathu

12

Operators

Arithmetic+, -, *, /,%, ++, --Assignment=, +=, -=,*=, /=, %=Concatenation+Comparison==, ===, !=,!==, >, 18){ can_vote = true;} else { can_vote = false;}Orcan_vote = (age>18) ? true : false;

@akshaymathu

14

For Loop

Forfor (i=0; i

@akshaymathu

15

While Loop

Whilewhile (is_extra_water){ drain();}Do/whiledo { drain();} while (is_extra_water);

@akshaymathu

16

@akshaymathu

17

JS Functions

Function

Code block that executes on call//define the functionfunction say_hello(name){ alert(Hello! + name);}

//call the functionsay_hello(Akshay);

@akshaymathu

19

Function Arguments

Any number of arguments can be passed without declaringNamed arguments are not supported

say_hello(1); // Hello! 1say_hello(); // Hello! undefinedsay_hello(Akshay, Mathur); //Hello! Akshay

@akshaymathu

20

Naming a Function

function my_func(){}

A function may not have a name

function(){};

my_func = function(){};

@akshaymathu

21

Variable Scope

By default all variables are globalVariables defined with var keyword are local to the functionIt is assumed that all variables are defined in the first linefunction(){var my_var = Hello;console.log(msg);var2 = 6;}

@akshaymathu

22

Return Values

Anything can be returned from a function using return statementfunction sqr(x){var sq = x * x; return sq;}

var four_sq = sqr(4);

@akshaymathu

23

Other Facts

A function can be assigned to a variableA function can be defined within another functionA function can return a functionfunction sqr(){ sq = function (x){ return x * x * x; }; return sq;}My_sqr = sqr(); // functionMy_sqr(3); // 27

@akshaymathu

24

Global Functions

encodeURI(), encodeURIComponent() Encodes a URI decodeURI(), decodeURIComponent() Decodes a URI

escape() Encodes a string unescape() Decodes an encoded string

String() Converts an object's value to a string Number() Converts an object's value to a number

isFinite() Determines whether a value is a finite, legal number isNaN() Determines whether a value is an illegal number

parseInt() Parses a string and returns an integer parseFloat() Parses a string and returns a floating point number

eval() Evaluates a string and executes it as if it was script code

@akshaymathu

25

@akshaymathu

26

JS Objects

Objects

Everything in JS is an object (instance)string.length // 6str.length.toFixed(2) // 3.00[hell, o!].join() // hello!

Custom objects can also be defined

@akshaymathu

28

JSON

Javascript Object has a key and a valueKey is always stringValue can be of any typeIncluding another JSON object

A = {key1: value1, key2: value2};orA = new Object();A[key1] = value1;A.key2 = value2;

@akshaymathu

29

Object as Namespace

It is a good practice to group variables and functions together in an object rather than keeping them global

var user = {};user.name = Akshay;user.greet = function(){ alert(Hello!.concat(user.name);};

@akshaymathu

30

Object as Named Argument

Objects can be passed to a function as an argumentThey proxy for named arguments

Say_hello = function (options){ if (typeof options === Object){ options.msg = (options.msg)?options.msg : Hello!; } alert(options.msg + + options.name);}

Say_hello({name: Akshay});

@akshaymathu

31

@akshaymathu

32

Creating Single Page Web App

Series of 3 workshopsFull DayHands-on

presents

1. Simple Web Pages

Introduction to Web and its evolutionWeb page basics and HTML tagsStyling elementsJavaScript basicsIntroduction to DOMChanging style using JavaScriptSimple DOM manipulationResponding to user actions

@akshaymathu

34

2. Dynamic Web Pages

Jquery JavaScript FrameworkHandling DOM eventsGetting data asynchronously via AJAXClient side dynamism using JavaScript templatesSimplify JS coding via CoffeeScriptWriting JS classes (prototypes)

@akshaymathu

35

3. Single Page App

Understanding MVC conceptsIntroduction BackboneJS and UnderscoreJSUsing Backbone models, views and routerDealing with collectionsCustom events and their handlersAdjusting URLs for making browser buttons work

@akshaymathu

36

Document Object Model

Window ObjectRepresents the browser windowAll Javascript functions and variable are attached here by defaultDocument ObjectRepresents the page rendered inside the windowAll HTML elements are available hereIn the hierarchy they are attached

@akshaymathu

37

Manipulating the Web Page

Get programmatic handle of an HTML element via Document Object Model (DOM)var el = document.getElementByID(a_unique_id);Change desired property of the elementel.src = my_photo.png

@akshaymathu

38

JS Framework

Library for simplifying JS codingJquery is most popularProvides simple interface and syntactic sugar for common JS workSelecting DOM elementDOM traversal and manipulationEvent handlingTakes care of cross browser and cross version issues

@akshaymathu

39

Jquery

Takes care of cross browser and cross version issuesLibrary for simplifying JS codingEverything is via functionsSame function for get and setProvides simple interface and syntactic sugar for common JS workSelecting DOM elementDOM traversal and manipulationEvent handling

@akshaymathu

40

Javascript Templates

Dynamically creates HTML code in JSData driven HTMLAllows variable substitution, looping and conditional statementsGenerated HTML is inserted into the DOM for changing part of the page on-the-fly

@akshaymathu

41

Using Template

46

BackboneJS

Provides MVC structure for JavascriptThe model object holds dataThe view object handles visual elements and interactionsThe controller object glues everything together and provides communication amongst objectsCustom Events help writing good code and eliminates use of global variablesThe event object allows raising and handling custom events

@akshaymathu

47

BackboneJS code in Coffeescript

class LoginModel extends Backbone.Modelclass LoginView extends Backbone.Viewinitialize: =>@template = $(#login_template').template()@render()render: =>$(@el).html $.tmpl(@template, @model.toJSON())events:'click #login_btn' : login_handlerlogin_handler: (ev) =>window.mpq_track Login Clickclass LoginController extends Backbone.Routerinitialize: =>@l_model = new LoginModel window.app_info@l_view = new LoginView model: model, el: #login_div

@akshaymathu

48

Thanks

@akshaymathu

49

@akshaymathu

http://www.quora.com/Akshay-Mathur