Sunday, January 17, 2010

Basic Javascript for programmer

Variable definition

There are two way to define variable 1. define in local scope 2. define in global scope. So you can define global variable even in function.
var a = 0;

// Function definition
function define_c() {
    c = 1;      // if c is defined it will be overided
    var b = 0;  // define a in local scope
    
}

define_c();

alert(a);
alert(c);       // You can access c in global scope
alert(b);       // b is undefined in global scope


// Array definition
var array1 = [1, 2, 3];
var array2 = new Array(1, 2, 3);

// String definition
var text = "hello";         // type of "text" is "string"
var text2 = new String("hello");    // type of "text2" is "object"

special operator

There are many operators exist in javascript. Most of them come from C/C++ and Java but there are something different.
var text = "hello";
var text2 = new String("hello");

// typeof

typeof text         // "string"

typeof text2        // "object"

typeof text3        // "undefined"

if(typeof text == "string") {
    alert("text is string");
}

if(typeof text2 == "object") {
    alert("text2 is object");
}

/*
There are several type in javascript
* number
* string
* boolean
* object
* function
* undefined
*/



// instanceof

text instanceof String      // false
text2 instanceof String     // true


// comparison

text === text2      // false, because they are different type
text !== text2      // true

text == text2       // true, because they have same value
text != text2       // false

Function definition

// Define f1 as function
function f1(){
    
}


// Define f2 as function
var f2 = function() {
    
}

// There are something different

typeof f1.name      // string
f1.name == "f1"     // true

typeof f2.name      // string
f2.name == ""       // true, Oh name of f2 is empty

var f3 = function myfunction() {

}

typeof f3.name      // string
f3.name == "myfunction"       // true


To be continued...

No comments:

Post a Comment