Function Declaration vs Function Expression

You guys several times will have seen the function in two syntax.

 

    1)Function Declaration

  1. function func_name(arg_1, arg_2,..., arg_n){
  2.     .............
  3.     ...........
  4. }

    2)Function Expression

  1. var func_name;
  2. func_name=function(){
  3.     ....................
  4.     .............
  5. };
  6.  

 

Here are the differences

  • Function expression can’t be called before its definition vs Function declaration can.

 

 

 

Find no of time a character used in string using PHP

  1. function char_in_string($string){
  2. $char_array=str_split($string);
  3. for($i=0;$i<sizeof($char_array);$i++){
  4. $no_of_char[$char_array[$i]]=0;
  5. for($j=0;$j<sizeof($char_array);$j++){
  6. if($char_array[$i]==$char_array[$j])
  7. {
  8. $no_of_char[$char_array[$i]]++;
  9. }
  10. }
  11. }
  12. return $no_of_char;
  13. }

 

Now show its structure using var_dump()

var_dump(char_in_string("Hello Ahmad Asjad"));

Its result will look something like this.

array (size=12)
  'H' => int 1
  'e' => int 1
  'l' => int 2
  'o' => int 1
  ' ' => int 2
  'A' => int 2
  'h' => int 1
  'm' => int 1
  'a' => int 2
  'd' => int 2
  's' => int 1
  'j' => int 1

 

 

JQuery setTimeout inside for loop

Today I was amazed with a question asked by one of my IT friends. 

What’ll be the output of setTimeout function if I declare it inside the for loop like this.

 

  1. for(i=0;i<3;i++)
  2. {
  3.     console.log(i);
  4. }
  5.  

 

My answer was 

 

  1. 0
  2. 1
  3. 2
  4.  

 

But the answer was not correct as he challenged and I checked it too. The answer was ‘2’ only.

 

I tried to know why the output is so. I thought that this is because of threading it’ll be skipping the setTimeout function some time due to thread concept. But when I changed the condition to i<10000, but the output was same. Finally I’s not able to know the situation and problem.

 

At last I searched on forems, and I got my answer which is as follows:

The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 4.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

 

  1. for (var i = 0; i < 3; i++) {
  2. (function (x) {
  3. setTimeout(function () { alert(x); }, 100);
  4. })(i);
  5. }

 

You might also check this Q/A on stackoverflow