You guys several times will have seen the function in two syntax.
1)Function Declaration
- function func_name(arg_1, arg_2,..., arg_n){
- .............
- ...........
- }
2)Function Expression
- var func_name;
- func_name=function(){
- ....................
- .............
- };
-
Here are the differences
- Function expression can’t be called before its definition vs Function declaration can.
- function char_in_string($string){
- for($i=0;$i<sizeof($char_array);$i++){
- $no_of_char[$char_array[$i]]=0;
- for($j=0;$j<sizeof($char_array);$j++){
- if($char_array[$i]==$char_array[$j])
- {
- $no_of_char[$char_array[$i]]++;
- }
- }
- }
- return $no_of_char;
- }
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
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.
- for(i=0;i<3;i++)
- {
- console.log(i);
- }
-
My answer was
- 0
- 1
- 2
-
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:
- for (var i = 0; i < 3; i++) {
- (function (x) {
- setTimeout(function () { alert(x); }, 100);
- })(i);
- }
You might also check this Q/A on stackoverflow