Skip to content

Latest commit

 

History

History
117 lines (85 loc) · 2.63 KB

File metadata and controls

117 lines (85 loc) · 2.63 KB

Know if an object has a property

if(typeof obj.prop == 'undefined'){
    // do something...
}

This way it returns true either if the property doesn't exist or is set to 'undefined'

resource

Create variables within a scope and avoid collisions

I encountered this issue while programming

(function printWidget(){
    $triggerButton = $("#fistDiv .btn");
    text = "this is the first div";

    $triggerButton.click(function(e){
        e.preventDefault();
        console.log($widget);
    });
})();

(function printWidget(){
    $triggerButton = $("#secondDiv .btn");
    text = "this is the second div";

    $triggerButton.click(function(e){
        e.preventDefault();
        console.log($widget);
    });
})();

$("#firstDiv .btn").trigger("click"); // this is the second div
$("#secondDiv .btn").trigger("click"); // this is the second div

The solution: define and assign instead of just assign

(function printWidget(){
    var $triggerButton = $("#fistDiv .btn");
    var text = "this is the first div";

    $triggerButton.click(function(e){
        e.preventDefault();
        console.log($widget);
    });
})();

(function printWidget(){
    var $triggerButton = $("#secondDiv .btn");
    var text = "this is the second div";

    $triggerButton.click(function(e){
        e.preventDefault();
        console.log($widget);
    });
})();

$("#firstDiv .btn").trigger("click"); // this is the first div
$("#secondDiv .btn").trigger("click"); // this is the second div

Reason: As I didn't define the variables, they were being assigned to the global scope, hence, they were being overwritten in the second IIFE

More information in YDKJS

Console methods

  • console.log
  • console.info
  • console.warn
  • console.error
  • console.assert
  • console.dir
  • console.group (console.groupEnd)
  • console.table
  • console.time (console.timeEnd)

For know more about those methods check this blog post

Use a setTimeout for exitin a while-loop

The following 2 code snippets crash:

var count = 1;

while(count > 0){
	setTimeout(function(){count--};, 1000);
}
var count = 1;

setTimeout(function(){count--};, 1000);
while(count > 0){
}

I was trying to set a while loop that will last 1 second (is not a real implementation just as a concept test) however it seems that the while-loop iterates so fast that doesn't allows the setTimeout to be executed.

Useful Libraries

  • fullPage.js -> Library for smooth scroll to section web page