- With Modulator
- <?php
- $num = 14;
- if($num%2==0) {
- echo 'The number is even.';
- } else {
- echo 'The number is odd.';
- }
- ?>
2. With Bitwise Operator
- <?php
- $num = 14;
- if($num&1) {
- echo 'The number is odd.';
- } else {
- echo 'The number is even.';
- }
- ?>
- <?php
- $num = 14;
- if($num%2==0) {
- echo 'The number is even.';
- } else {
- echo 'The number is odd.';
- }
- ?>
2. With Bitwise Operator
- <?php
- $num = 14;
- if($num&1) {
- echo 'The number is odd.';
- } else {
- echo 'The number is even.';
- }
- ?>
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