Javascript

Javascript is a dynamic and lightweight programming language common used as part of web pages.

Javascript

Javascript is a dynamic and lightweight programming language common used as part of web pages. It is different from java

Development tools

  • Microsoft Front Page
  • Micromedia DreamWeaver MX
Javascript is case sensitive

Comments

Singleline: Any text after // and before end of line.
Multiline: Any text between /* and */

Placement

Javascript code can be placed anywhere in html document e.g body,head etc
	 <script type="text/javascript">
JavaScript code
</script>
Javascript from external source
	 <script type="text/javascript" src="http://www.example.com/file.js"></script>
	 

or

<script type="text/javascript" src="file:///sdcard/file.js"></script>

Statements

Javascript statements are separated by semi-colons
Javascript ignores whitespaces. Use them to format your code
	 var a = 5; //a statement
	 alert(a*a); // another statement
	 

Output

To provide visible data to user javascript uses:
  • alert(text/variable)
  • console.log(text/variable)
  • document.write(text/variable)
  • element.innerHTML=text/variable
  • element.value=text/valuable

Variables

They are used to temporarily store data
	 var a = 5; //Number
	 var b= "Titus";  //String
	 var c = true;  //Boolean
	 var d= ["Joy","James"];  //Array
	 var e ={firstName:"John",lastName:"Kamau"}; //Object
	 var f=new Function(params);  //Function
	 
Rules
Must begin with a letter,underscore or dollar sign
Case sensitive and unique
Scope
Global:- Outside Functions
Local:- Inside functions
without a var keyword the variable is a property of the global object.

Operators

Arithmetic

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus
  • ++ Increment
  • -- Decrement

Comparison

  • == Equal to
  • === Equal value
  • != Not equal
  • !== Not equal value and type
  • > Greater than
  • < Less than
  • >= Greater or equal to
  • <= Less or equal to
  • ? Ternary/Conditional operator

String

  • + Combine two strings
  • += Add more strings to a variable

Assignment

  • =
  • +=
  • -=
  • *=
  • /=
  • %=

Logical

  • && And
  • || Or
  • ! Not

Bitwise

  • & AND
  • | OR=
  • ~ NOT
  • ^ XOR
  • << Left Shift
  • >> Right Shift

Others

  • typeof(variable): returns the data type
  • delete: Deletes a property from object
  • in: Checks a property in object
  • instanceof:
  • void: No return

Data types

  • Strings: "Titus"
  • Numbers: 5
  • Arrays: []
  • Booleans: true or false
  • Objects: {}
  • Functions: function(){ }

Functions

Function is a block of code that perform a particular function. It is executed when invoked.A function is reusable and is accesible from any part of a program
    function multiply(p1,p2){
    return p1*p2;
    }
    

Coditional Statements

To write a code that thinks you have to put conditions
Condition is a statement that returns positive or negative data type
Examples of negative data types are
  1. "" (string)
  2. 0 (Number)
  3. false (boolean)
  4. null (Object)
  5. undefined
  6. NaN

if

    if(condition){
    code block executed if condition is pisitive
    }
    

if...else

    if(condition){
    code block executed if condition is positive
    }
    else{
    code block executed if condition is negative
    }
    

if...else if...else

    if(condition){
    code block executed if condition is positive
    }
    else if(condition2){
    code block executed if condition2 is positive
    }
    else{
    code block executed if condition is negative
    }
    

Switch

switch is a more simpler version of if..else if..else
    switch(data){
    case condition: code block executed if condition is equal to data; break;
    case condition2: code block executed if condition2 is equal to data; break;
    default: code block executed if all conditions are not met;
    }
    

Loops

Loop is piece of code is executed many times repeatedly
for
    for(initialization;condition;interation){
    code block
    }
    // initialization: initialise a variable e.g i=0
    //condition : set a condition e.g i<10
    //intelation : increment or decrement e.g i++,i--,i=i+2
    
for/in
It loops through properties in an object
    for(property in object){
    code block
    }
    //example
    for(x in window){
    document.write(x);
    }
    
while
You have to satisfy condition from within the code block.
    while(condition){
    code block
    }
    //example
    while(i<10){
    document.write(i);
    i++
    }
    
do.. .while
Checks condition after code execution
    do{
    code block;
    }
    while(condition)
    
break is used to jump out of loop
continue break one interation with a condition and continues to the next

Conversions

  • To String: String(variable)
  • To Number: Number(variable)
  • To Float: parseFloat( variable)
  • To Interger: parseInt(variable,base)
  • To Array: new Array(variables)
  • To Object: new Object(variables)
  • To new Function: new Function(variables)

Regular expressions

It is a sequence of characters that form a search pattern
    /pattern/modifiers
    
modifiers
  • i: case insensitive
  • g: global
String methods used
  • match()
  • search()
  • replace()

Handling errors

try...catch

    try{
    block of code expected to have error.
    }
    catch(error){
    block of code executed after an error occur.
    }
    finally{
    block of code executed whether there was error or not.
    }
    

onerror(DOM)

    onerror= function(error){ handle error}
    

Global methods

  • decodeURI()
  • decodeURI()Component
  • encodeURI()
  • encodeURIComponent()
  • escape()
  • unescape
  • eval(expression): evaluates an expession/block of code/function/string etc
  • isNaN: checks whether a variable is a number
  • isFinite(number): checks whether number has reached infinity
  • parseInt(number): converts to interger
  • parseFloat(number): converts to float

JSON

Javascript Object Notation
    {
    "action":"android.intent.action.VIEW",
    "type" : "message/rfc822",
     "data":"/sdcard/hd.jpg",
    "extras" : {name:"android.intent.extra.EMAIL", type:"list", value:"yourname@gmail.com"}
   }
   

JSON methods

JSON.stringify(object) Converts object to JSON
JSON.parse(JSON) Converts JSON to Object
Rules
  • data is in quotes
  • Array is inside []
  • Object is inside {}

Best Practices

  • Initialize your variables with var keyword
    • Slow code: for(i=0;i<array.length;i++){}
    • Fast code: var len = array.length; for(i=0;i<len;i++){}
  • End statements with a semi-colon. Not a must when each statement is on its own line
  • Dont use reserved words as variable names
Categories
External
Free Web Hosting