Eivind Says;

Weekly code tip

Javascript tips in general

(function(){
// alot of things get handled as strings
var a = parseFloat("7") // Turning a string into a digit
var b = parseInt("5", 10) // Another one
var c = 123123123123123123123123; 
  // too long number - is turned into 1.2312312312312312e+26
  // long numbers needs to be stored as strings


if( a == "7" ){ // difference
        // passes
        if( a === "7"){ // equality
                // does not pass
        }        
}

var obj = {
        key: 'value'
}
if("key" in obj){
        // safe check
}

var argu = false; // global variable

// inheritance for objects
var first = function(){
        var arg = arguments;        // local variable
        variable = true;        // global -> no var declaration
};
first.prototype.func = function(){
        return this.nodeName;
}

// Inheritance
var second = function(){        
}
second.prototype = new first; // inherits from first

// Calling in context
second.func() // undefined context
second.func.apply(document, [true, false, "haha"]); // document context
second.func.call(document.body, true, false, "haha"); // body context


// Optimizing
var arr = [1,2,3,4]
for (var i = 0, l = arr.length, paragraph; i

Objects in javascript

Working with objects in Javascript is a blast. The Object can contain any type of variable, strings, booleans, numbers, arrays and objects. It's easy to extend, manipulate & traverse, as complexity comes along. 

var data = {}; 
  // I prefer the string literal, but you could also: 
  var blah = new Object();

Now we have an object. Let's add some attributes to it.

data["articles"] = [];
  data.count = 0;

You can choose whether to use the dot annotation or array access. I do both depending on whether I'm adding keys with variables or have keys with spaces.

data["ev_" + i] = true;
 data["a space in here"] = 1000;

If you need to loop or check for a key in an objects, you could use the in statement.

if("localStorage" in window){
    if("articles" in window.localStorage){
      data.articles = eval(window.localStorage.articles);
      for(var key in data.articles){
        var article = data.articles[key];
      }
    }
  } 

 

Be aware of that you can never order an object, so if you need ordered lists you have to use an array for that. Well that's it for this weeks code tip. Tune in next week for more.

Filed under  //   javascript   quicktip