Javascript - Why does a function work on the last call only? - javascript

Just started learning how to code. The first lesson taught how functions are used. For the below add function, whenever I call the function more than once, the output is displayed only for the last one. Does a function have to be written separately for each time I call?
function add(first, second) {
return first + second;
}
add(1,2);
add(7,9);
add(3,5);
Output: 8
How can I get an output to all three?

Your add function returns the computation, it does not print anything. So once you call it, all the work will be done and returned, and if you want to see what is returned, all you need is to console them in order to appear in the developer panel
function add(first, second) {
return first + second;
}
console.log(add(1,2)); // <- HERE
console.log(add(7,9);
console.log(add(3,5));

i think you are trying this on developer console. if you run this code as a file, you even doesn't get any output.
The developer console typically logs out the output from the codeblock. once the execution is done.
use console.log() in order to see all outputs.
console.log(add(1,2));
console.log(add(7,9));
console.log(add(3,5));

Related

Higher Order Function invocation behavior is very confusing

I am trying to invoke a function within a function which is not a big deal but for some reason i don't understand why i can't invoke a function through this logic:
function func1(futurefunc){
futurefunc();
}
function func2(){
return 3+3;
}
func(func2);
Now the result of the code above is undefined. However when I put: func(alert), the alert argument is invoked. I don't understand why is the second case running and the first part is not printing the returned value which in this case would be 6.
However when I try the following:
function func1(futurefunc){
return futurefunc();
}
the code seems to serve the proper value, which is 6 in this case. Any clear explanation. I hope I am not missing anything.
The first case, func1 just invoke futurefunc() and doesn't return anything so undefined is printed.
When you passed, alert, alert is invoked then you see the dialog.
The second case, func1 invoke futurefunc and return its result, so 6 is printed.
There is nothing hard to understand here.

Modify Function Output - Inspect Source - Javascript- HTML - Google Chrome

I want to modify the output of the functions (just say RANDOM examples, apologies for any code mistakes):
ng-if=!pfile.isgame
ng-if=! pfile.examplefile
-from false to true before it even has the page has any chance to drop any code on the page. How can I make it so I can append code to the page to the very beginning of the page to force every output of these particular functions to go true, on a live page?
This is definitely possible, I'm not sure where the function would be however the elements you can actually see the arguments on the page and it doesn't not look server sided at all, its just how its done. I read many articles but it many of them have not really helped me.
I am aware of Event Listener Breakpoints, its just the problem if I'm choosing the right one.
Thank you and I really appreciate it just if you can please dum down the explanation for me as even though I do understand HTML and JavaScript to an OK standard, I am still a massive beginner. This is something I always wanted to try out.
Hopefully I have understood your question correctly. There are a couple of options and the answer will depend on whether the functions are declarations or expressions.
If they are declarations, they get hoisted to the top on first pass, so that by the time your code begins execution, the function already exists and you can overwrite it early on.
If it's a function expression, you have to wait until the function expression has been created.
Example 1 (Function Declaration):
I have a function declaration on my page, which returns true if there is a remainder in the calculation, otherwise false. I execute it on page load. The output is false here:
function hasRemainder(first, second) {
return (first % second != 0);
}
console.log(hasRemainder(10, 5));
false
I have now added the Script First Statement breakpoint in DevTools, so that the debugger breaks before any script is run:
I re-open the page and the execution pauses. I now run the following code in the Console tab to override the hasRemainder function so that it always returns true:
hasRemainder = function() {
return true;
}
Finally, I click Play to continue execution. You can long click to select Long Resume, which skips breakpoints for 500ms so that you don't get caught for very single breakpoint thereafter.
true
The output this time is true as you would expect.
Example 2 (Function Expression):
We can't rely on the early breakpoint this time because the function won't exist yet. We need to add the breakpoint just after the function expression has been created.
Search for the functions using Cmd+Opt+F (Mac) or Ctrl+Shift+F (Windows).
When you are in the file with the function expression, put a breakpoint at the end of the function. When the debugger pauses, run the overriding function into the Console, and then press play to continue execution.

How does setTimeout(console.log.bind(console, "something")) work?

After reading How to hide source of Log messages in Console? , I'm confused about how this command works.
I try to not use setTimeout to wrap it, but the console log always show the source of log messages. Even I try to see the stack trace, it just shows nothing like the second line:
What does the setTimeout(console.log.bind(console, "something")) do?
And it seems cannnot remove setTimeout?
is there any other way to do the same thing?
Let's take it piece-by-piece:
What is console.log.bind(console, "something")?
The Function#bind function creates a new function that, when called, will call the original function using the first argument as this for the call and passing along any further arguments. So console.log.bind(console, "something") creates (but doesn't call) a function that, when it is called, will call console.log with this set to console and passing along "something" as the first argument.
What is setTimeout(x, y)?
It schedules the function x to be called after y milliseconds by the browser; if you don't supply y, it defaults to 0 (call back immediately, as soon as the current code completes).
So taken together, setTimeout(console.log.bind(console, "something")) schedules a call to console.log after a brief delay.
Using the delay means that the call to console.log doesn't happen directly from the code where you do that; the browser calls console.log directly, not within your code. Consequently, the stack trace doesn't show that it happened in your code, because it didn't.

Replicating/overriding javascript's console.log function

OK, so here's what I'm trying to do:
I'm building a Javascript->Cocoa/Objective-C bridge (a tiny test actually), which means that I'm able to call an Objective-C function from my JavaScript code.
One of the issues faced is that messages/errors/logs/etc from console.log are not visible, so they are to be forwarded to the corresponding Cocoa function (i created one like - (void)log:(NSString*)msg which simply takes a parameter as string and prints it out in the Xcode's console window.
Now, the thing is how do I replicate 100% what console.log does + forward the message to my own log function?
This is what I've done so far:
Javascript
console.log = function(text) {
API.log_(text);
}
Objective-C
- (void)log:(NSString*)msg
{
NSLog(#"Logging from JS : %#", msg);
}
If "text" is a simple text string when calling console.log("something"), then it works fine. If I pass the console.log function an object, then it's not working as expected (e.g. in Chrome's Javascript console window).
How would you go about it?
Is it possible to get the string output of what console.log would normally print out?
P.S. I tried playing with JSON.stringify(obj, null, 4) a bit, but it still doesn't seem right. Any ideas?
It sounds like you want the original functionality to persist whilst also capturing the input and passing it to your API. That could be achieved by something like (JSFiddle):
var original = console.log,
API = {
log_: function() {
// Your API functionality
}
};
console.log = function() {
original.apply(console, arguments);
API.log_(arguments);
};
A couple of things to point out. Firstly, the native console.log can receive any number of parameters, so we use arguments to handle this. We have to use .apply() to call the original method in the context of console and it also allows us to pass the arguments exactly as they were on the original call.

Is it possible to flush the console (make it print immediately)?

I use Firefox + Firebug for some Javascripting. The text I'm trying to log with console.log does not immediately appear in Firebug's console. It seems like it piles up in a buffer somewhere, and then gets flushed to console in chunks. I have a function that makes a few log calls. Sometimes I get just the first line, sometimes - nothing. I do, however, see the whole bunch of lines when I refresh the page.
Can I flush the console log manually?
The short answer is no. There is no flush. You could clear the console
console.clear();
But I don't think that's what you want. This is most likely from the code. If we can see it, I can revise my answer with better feedback.
If you want to see all the available methods under console, execute this in the command line:
for(var i in console) {
console.log(i);
}
or have a look at the wiki page of the console API.
It's not a Firefox problem, It's a JavaScript problem because execution is delayed and variables are updated so you can see only the last value.
To see immediately the output you need to convert your object in string so it will not change also if object will be updated.
I wrote this easy function :
function printLog(s) {
if (typeof(s) === 'object') {
console.log( JSON.stringify(s) );
} else {
console.log(s);
}
}
The printed output is a string (so you can't interact with it) but it contains the real dynamic object that you want to see at the print time instant.

Categories