I want to run code if another code snippet has run.
IF this code runs
(function() {
// Code runs here
})();
THEN run this code also
//This code
Example
if (condition) {
block of code to be executed if the condition is true
}
http://www.w3schools.com/js/js_if_else.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/if...else
This won't seem to work?
if ((function() {// Code runs here})();)
{
//This code
}
You should use return statement otherwise the IIFE would return undefined and thus it would be equivalent to false statement.
if (
(function() {
// Code runs here
return true;
})();
){
//This code
}
Use this
var functionName = (function() {
var didRun = false;
// This function will be executed only once, no matter how many times
// it is called.
function functionName() {
// Your code goes here
}
return function() {
if (didRun) {
return;
}
didRun = true;
return foo.apply(this, arguments);
}
})();
and check, when the function didRun, then execute your core
The IIFE seems superfluous to me here - just use a named function the simple way and keep it straightforward. If anyone can give me a use for the IIFE as the conditional expression in an If ... else, please comment - I would love to understand what I might be missing:
function odd(num) {
return num % 2;
}
// Use Dev Tools Console (F12) to see output
function logOddEven(num) {
if (odd(num)) {
console.log(num + ' is odd');
} else {
console.log(num + ' is even');
}
}
logOddEven(0);
logOddEven(1);
logOddEven(2);
Related
Please see this example code:
(function() {
if (1 + 1 === 2) {
return;
}
console.log(`This Line Won't Compile`);
})()
The code above simply breaks when the condition is true.
However, I would like to extract the whole logic outside of this IIFE.
function checkNumber() {
if (1 + 1 === 2) {
return;
}
}
(function() {
checkNumber(); // How do I achieve this?
console.log(`This Line Now Compile, but I don't want this line compile.`);
})()
How do I achieve this?
Is it possible to achieve this?
You need a flag if the function take short circuit. In this case you need another check and return early.
function checkNumber() {
if (1 + 1 === 2) {
return true; // supply a flag
}
}
void function() {
console.log('IIFE');
if (checkNumber()) return; // use this flag
console.log(`This Line Now Compile, but I don't want this line compile.`);
}();
There are many options, a simple one would be to set a global variable which you can then use in the IIFE
var iAmAGlobalVariableKnowingWhatToDo = false;
var checkNumber = function () {
if (1 + 1 === 2) {
iAmAGlobalVariableKnowingWhatToDo = true;
return;
}
iAmAGlobalVariableKnowingWhatToDo = false;
};
// note everything until this line of code is in the global scope!
// that's why you can use the checkNumber() and the variable inside the IIFE
(function() {
checkNumber();
if(iAmAGlobalVariableKnowingWhatToDo) {
return;
}
console.log(`This Line Now Compile, but I don't want this line compile.`);
})()
I have an if-else statement in a function. I want to test both cases. When the instance is initiated, self.count is set to 1. When I run my test, it goes to the false statement. How can I make self.count = 2 to go into the else statement?
Test:
it('verify change', function () {
spyOn(this.instance, 'change').and.callThrough();
this.instance.change('messageBoard');
expect(this.instance.change).toHaveBeenCalled();
});
Javascript:
self.count = 1;
self.change = function change() {
if(self.count <= 1) {
// do stuff
} else {
// do stuff
}
};
I know I can use this.object.method.and.returnValue() to make a method return a value, but I don't know how to do it with variables.
So it seems i do not need to mock the variables. I can just assign it within the test like:
it('verify change', function () {
this.instance.count = 2; // this would nake it go to the else block
spyOn(this.instance, 'change').and.callThrough();
this.instance.change('messageBoard');
expect(this.instance.change).toHaveBeenCalled();
});
I was cleaning up my code and ran into a little trouble with callbacks, specifically getting the correct values to output when a callback is called. Could some explain to me why the following code spits out something that I'm not expecting and a possible solution without having to put in another parameter of i to the run() function, or is passing in i to know my index upon calling the callback the only way to do this?
for (var i in dls) {
run(dls[i][0], dls[i][1], function(isTrue){
if (isTrue) {
// Do true stuff here
} else {
console.log("Value is: " + dls[i][3])
}
});
}
Calling run() actually has the correct inputs inside, but upon that function calling the callback and going into the else statement, dls[i][3] spits out the same value i times.
I've tried putting different scopes around (run()) and such but to no avail and can't seem to wrap my head around this.
Thanks
EDIT:
If I wanted to split it up into a separate function, how would I do it?
var run = function(cb){
setTimeout(function() {
cb(false)
}, 3000);
}
for (var i in dls) {
run(dls[i][0], dls[i][1], (function(index) {
return extraction
})(i));
}
function extraction(isTrue){
if (isTrue) {
// stuff
} else {
console.log("Nothing changed in " + dls[i][3])
}
}
Here dls[i][3] is still incorrect and prints the same value 3 times.
You have fallen into the traditional "loop trap"
When it comes time for your callback to run i is now a different value.
What you can do is cache that value in another wrapper function:
for (var i in dls) {
run(dls[i][0], dls[i][1], (function (currentIndex) {
return function(isTrue){
if (isTrue) {
// Do true stuff here
} else {
console.log("Value is: " + dls[currentIndex][3])
}
};
})(i));
}
In regards to the edit / second question, assuming this is what you wanted to do:
// note that I changed the function signature of `run`
var run = function(val1, val2, cb) {
setTimeout(function() {
cb(false);
}, 3000);
};
// note the `wrapper` here
for (var i in dls) {
run(dls[i][0], dls[i][1], wrapper(i));
}
// this is the same as what the IIFE is doing,
// just with an external function instead
function wrapper(scopedIndex) {
// return a function to be used as the callback for `run`
return function extraction(isTrue) {
if (isTrue) {
// stuff
}
else {
// use the scoped index here
console.log("Nothing changed in " + dls[scopedIndex][3]);
}
}
}
Take a look at function makeExitCallback(i) in the other linked question, as well. It directly relates to what's going on here.
You should post what's in dls as well, just to make it easier to run your snippets locally.
I am trying to understand how this code works. I finally figured out it is a loop. It is not a "while" or "for" loop, but it is a loop nonetheless by virtue of calling itself I think (please correct me if I am wrong).
I understand it's main function: to pass JQuery when it is loaded to my 'foo' function, when ever jQuery has loaded. To do that it checks for jQuery in Window and if not there it resets the timer(). That is the loop. I get that.
Let me explain what I do not understand:
the call: CheckDependency.Deferred.execute(foo);
why the "Deferred" keyword?
execute baffles me: I expect that if I call CheckDependency.Deferred.execute that it would only execute that method. Why does it obviously run the timer function. why could it not simply have that code after the timer() since it keeps looping there and then return jquery?
Speaking of return. Why is there a method in there? CheckDependency.Deferred.execute(foo); is as crazy to me as CheckDependency.Deferred.RETURN.execute(foo); (or some similar crazy statement)
I am fairly new to JavaScript (from PHP). Here the code:
function foo(){ console.log('jQuery found!');
}
var CheckDependency = CheckDependency || { };
CheckDependency.Deferred = function ()
{
var functions = [];
var timer = function() {
if (window.jQuery) {/* && window.jQuery.ui*/
while (functions.length) {
functions.shift()(window.jQuery);
}
} else {
window.setTimeout(timer, 250);
}
};
timer();
return {
execute: function(onJQueryReady)
{
if (window.jQuery) { // && window.jQuery.ui
onJQueryReady(window.jQuery);
} else {
functions.push(onJQueryReady);
}
}
};
}();
CheckDependency.Deferred.execute(foo);
Let me start by saying I'm not a javascript expert, but I dabble :) I'll take a stab at describing what is going on here.
First, This creates a new object called "CheckDependency".
var CheckDependency = CheckDependency || { };
Next, it runs an anonymous function, and stores the result in CheckDependency.Deferred.
CheckDependency.Deferred = function ()
{
.
.
.
.
}()
The anonymous function runs the following code:
var functions = [];
var timer = function() {
if (window.jQuery) {/* && window.jQuery.ui*/
while (functions.length) {
functions.shift()(window.jQuery);
}
} else {
window.setTimeout(timer, 250);
}
};
timer();
The last part of the function code returns a new function execute, which gives CheckDependency.Deferred a function execute.
return {
execute: function(onJQueryReady)
{
if (window.jQuery) { // && window.jQuery.ui
onJQueryReady(window.jQuery);
} else {
functions.push(onJQueryReady);
}
}
};
Finally, this new function is called
CheckDependency.Deferred.execute(foo);
The final result of this is that the code starts a background timer that calls itself until window.jQuery is true - which means jQuery is loaded. Then, the function passed to execute is passed into this loop and so will once jQuery is available, the original function passed to "execute" will be called with the instance of window.jQuery.
I hope I did this justice, and I hope my answer helps! Please let me know if you have any question.
I would like to have a function that checks if a condition is true run before a specific function is called. My goal is to have one line of code (the function being called) in another function. This function should run before any other code is executed. Here is some pseudocode to demonstrate what I mean:
function checkFunction(){
//checks if a condition is true if so end function, else continue function
}
function aFunction(){
checkFunction();
//some code
}
I know I can make a conditional statement that contains a return, but I would like to keep it this short if possible.
Thank you guys for your time.
There's nothing designed specifically for what you want, and its verging on bad practice anyway. But you could get it pretty succinct by just writing something like:
function aFunction()
{
if (!checkFunction()) return;
//some code
}
You might want an assert-like function, but then the other way round:
function stopIfTrue(x) {
if(x === true) throw "stop function"; // can be any string
}
and then:
function aFunction(){
stopIfTrue(something); // if 'something' is true an error will be thrown; function will exit
//some code
}
I would simply do this:
function checkFunction(){
return (condition);
}
function aFunction(){
if(!checkFunction()) return;
//some code
}
If what you're trying to do is this:
function aFunction()
{
if(checkFunction())
{
return;
}
//somecode
}
without using a return in aFunction(), you could do this:
function aFunction()
{
if(!checkFunction())
{
//somecode
}
}
A trick you can do is dynamically change the other function. So
function make_wrapped(before, after){
return function(){
if(before()) return;
after.apply(this, arguments);
}
}
//set aFunction to be the new function
aFunction = make_wrapped(checkFunction, aFunction);
edit: I misread the question. This is probably way more complicated than you need.