Skip to main content

Javascript - Some Useful Tips & Tricks

Use window.name for simple session handling

window object has its own property 'name'. The name of the window is used primarily for setting targets for hyperlinks and forms. Windows do not need to have names. With this property we can achieve simple session storage. Browser preserves the property value (window.name) until the window/tab is closed. 


Labels

You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i === 1 && j === 1) {
         continue loop1;
      }
      console.log('i = ' + i + ', j = ' + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"

Know more about typeof, instanceof and constructor:

typeof: An operator – returns a string indicating the type of the unevaluated operand.

Note: typeof null will return "object", and for most of the object types (Array, Date, Number, Function, String …) will return "object". On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example: typeof alert === 'object'


Type
Result
Undefined
"undefined"
Null
"object"
Boolean
"boolean"
Number
"number"
String
"string"
Host object (provided by the JS environment)
Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)
"function"
Any other object
"object"

 Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

constructor: A reference to the function that created an object. All objects inherit a constructor property from their prototype and it can be changed programmatically 

instanceof: An operator -  which tests presence of constructor.prototype in object prototype chain. 
//EXAMPLE
var obj = {},
arr= [],
d = new Date(),
f1 = new Function(),
f2 = function(){},
s1 ="a string",
s2 = new String(),
n1 = new Number(5),
n2 = 5,
n3 = 3.14;
typeof obj //return "object"
typeof arr //return "object"
typeof d //return "object"
typeof f1 //return "function"
typeof f2 //return "function"
typeof s1 //return "string"
typeof s2 //return "object"
typeof n1 //return "object"
typeof n2 //return "number"
typeof n3 //return "number"
obj instanceof Object //return true
arr instanceof Array //return true
arr instanceof Object //return true
d instanceof Object //return true
d instanceof Date //return true
f1 instanceof Object //return true
f1 instanceof Function //return true
f2 instanceof Function //return true
f2 instanceof Object //return true
s1 instanceof Object //return false
s1 instanceof String //return false
s2 instanceof Object //return true
s2 instanceof String //return true
n1 instanceof Object //return true
n1 instanceof Number //return true
n2 instanceof Object //return false
n2 instanceof Number //return false
n3 instanceof Object //return false
n3 instanceof Number //return false
obj.constructor()//return Object {}
arr.constructor()//return []
d.constructor()//return "(current date)"
f1.constructor()//return function anonymous() { }
f2.constructor()//return function anonymous() { }

s1.constructor()//return ""
s2.constructor()//return ""

n1.constructor()//return 0
n2.constructor()//return 0
n3.constructor()//return 0


Shuffle an array

var arr = [“a”, “b”, 1, 100, 5, 10, 200, 458, 98];
arr = arr.sort(function(){ return Math.random() - 0.5});


Get a random item from an array

var arr = [1,5,6,7,4,3,9,”a”,”xyz”];
var  randomItem = arr[Math.floor(Math.random() * arr.length)];

Max and Min values in an array of numbers

var arr = [1, 100, 5, 10, 200, 458, 98];
var max = Math.max.apply(Math, arr); 
var min = Math.min.apply(Math, arr); 

Variable conversion shortcuts

var x = "1.592",
//to string
str = ""+ x,

//to integer
int = ~~x,  

//to float
float = 1*x,

//to boolean
bool = !!x,

//to array
array = [x]; 

‘yield’ Keyword:

JavaScript 1.7+ supports yield keyword, which is used to suspend execution of a function. Only firefox supports this option for now.

function currentLoop(){
  var i = 0;
  while(true){
    i++;
    yield i;
  }
}

var g= currentLoop();

g.next(); //return 1
g.next(); //return 2
g.next(); //return 3
g.next(); //return 4 

Comments

Popular posts from this blog

Random Bouncing Ball Animation

Simple animation of random balls that bounces within the screen Source: #include<stdio.h> #include<graphics.h> #include<conio.h> #include<dos.h> #include<math.h> void drawBall(struct ball *b, int color); struct ball{ int x, y; int dx, dy; int radius; }; void main() { int gd=0, gm=VGAHI; int i; struct ball b[10]; initgraph(&gd, &gm, ""); for(i=1;i<=15;i++){ b[i].radius = rand()%20; b[i].x=rand()%getmaxx(); b[i].y=rand()%getmaxy(); b[i].dx=2; b[i].dy=4; } while(!kbhit()) { delay(5); cleardevice(); for(i=1;i<=15;i++) drawBall(&b[i],i); } closegraph(); } void drawBall(struct ball *b, int color){ setfillstyle(1,color); setcolor(color); fillellipse(b->x, b->y, b->radius, b->radius); if(b->x+b->radius > getmaxx() || b->x-b->radius<0) b->dx = -b->dx; if(b->y+b->radius > getmaxy() || b->y-b->radius<0) b->dy = -b->dy; b->x+=b-...

Simple Animation Using C

Here i have used fillpoly function to draw the object body and used fillellipse function to draw tier. animation is done by looping through the objects x & y position until user hits a key. Keypress event is achived  by using kbhit function. Smoothness of animation is controlled by delay function. Change the delay values to change the animation speed Source: #include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> void main() { int gd=DETECT,gm,i=-300,j; int poly[16]={100,100,250,100,250,50,300,50,325,90,325,140,100,140,100,100}; int tpoly[16]={100,100,250,100,250,50,300,50,325,90,325,140,100,140,100,100}; initgraph(&gd,&gm,""); getch(); while(!kbhit()) { for(j=0;j<16;j+=2) { poly[j]=tpoly[j]+i; } fillpoly(8,poly); setfillstyle(5,7); bar(275+i,60,295+i,85); setfillstyle(5,8); fillellipse(140+i,140,20,20); fillellipse(280+i,140,20,20); setfillstyle(1,0); fillellipse(140+i,140,10,10); fillellipse(280+i,140,10...

RGB in C

Default palette size for normal graphics driver is 16 i.e) the color number rages from 0 to 15 To use rgb color modes we have to choose VGA or IBM 8514 as a graphics driver For VGA, Palette size is 16 i.e) color number ranges from 0-16 For IBM 8514, Palette size is 256 i.e) color number ranges from 0-255, we can also say it as VGA with 256 palette size By using setrgbpalette function we can generate RGB colors, we can generate colors with respect to Palette size. This function replaces the default palette colors with the generated Palette colors. Syntax: void setrgbpalette(int colornum, int red, int green, int blue); /* colornum - color number in palette (0-15 or 0-255 depens on graphics driver) red - color value for red (0-255) green - color value for green (0-255) blue - color value for blue (0-255) */ Example: #include<graphics.h> #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<time.h> void main(){ in...