This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 9 years ago.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
why can't i use addnums directly in the above Javascript ?
PS : I know other alternatives, the question is why the above specified method doesn't work.
You can.
var add = function addnums(a,b)
{
return a+b;
}
alert("sum is " + (function(a,b) { return a+b; })(10,20) );
Plus you may shorten the syntax:
var addnums = function(a,b) { ... }
or
function addnums(a,b) { ... }
You have an error writing the function write like the following:
var addnums = function(a,b)
{
return a+b;
}
alert("sum is " + addnums(10,20));
:)
var add; is a declaration. Here add is declared and assigned a function you need not name the function after keyword function, variable name will take the function name when you define a function in this way. I think you understand now.
Related
This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
I have searched the internet trying to find a good answer for this question. What I mainly found is suggestions to move the variable in the global scope, or using the functions as parameters for the function I want to use the variable in, but without explanation on how that works
To explain my dilema, lets say we have this piece of code:
function foo(){
var x = 2;
}
function bar(){
var z = 2;
}
function compare(foo,bar){
if ( z === x ) {
console.log("text");
}
}
This is the problem I'm facing. Is the code I've written above correct and if I call the compare() function it should console log "text" ?
declare with globel variable it's will easy to pass Another function
var x;
var y;
function foo(){
x = 2;
}
function bar(){
z = 2;
}
function compare(){
if ( z === x ) {
console.log("text");
}
}
foo()
bar()
compare();
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I am trying to call a function using a variable with it's name.
Here's the code:
var selectedFunc = 'func2';
var myModule = {
func1: function() {
//something here
},
func1: function() {
//something here
}
};
myModule.selectedFunc();
I would normally do this:
myModule.func1();
which will work but I'm trying to use the variable to define it's name, which is not working.
How can I fix this issue?
You can use bracket notation:
myModule[selectedFunc]();
You could call it using the following syntax
setTimeout("myModule."+selectedFunc + "()", 0);
Or even using eval to call it
eval("myModule." + selectedFunc).call();
Use eval.
var selectedFunc = 'func2';
var myModule = {
func1: function() {
return "hello";
},
func2: function() {
return "world";
}
};
window.alert(eval("myModule." + selectedFunc + "()"));
This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
I am new to javascript and I might have dove into the deep end first. I have came across the following definition while reading design patterns in js. I don't understand the syntax used here, why is the "log" function definition in "()",
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
Please point me in the right direction.
Without the parenthesis, the right hand side of your assignment is a function expression, and log is assigned a reference to that (anonymous) function expression, allowing to call log() later.
If you include the parenthesis, the wrapped function turns into a self-invoking function expression (and is immediately executed), so log is assigned whatever this function call returns.
As someone else already stated, your code shows an example of the so-called module pattern. Read much more about it here.
I don't understand the syntax used here, why is the "log" function
definition in "()"
Its basically self executing anonymous function. There are several ways of writing such functions.
(function() {
alert('hi there');
})();
! function() {
alert('hello');
}();
+ function() {
alert('plus');
}();
- function() {
alert('minus');
}();
Now such function can also return values:
var msg = (function() {
return 'hello';
})();
alert(msg);
var calc = (function() {
return {
add: function(a, b) {
return a + b;
},
sub: function(a, b) {
return a - b;
}
};
})();
alert(calc.add(4, 5));
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I was told that you can declare functions in JavaScript more than 1 way.
ex.
// One way
function sqrt(x){
return x * x;
}
// Second way
var sqrtAlt = function (x){
return x * x;
}
What is the difference between these two function declarations?
The output is same but must have a reason to have two ways?
I am also curious about how you would use them.
Lastly, are there any other ways?
Thanks.
When you are defining
function sqrt(x){
return x * x;
}
is that the function name appears in Firebug debugger.
Functions that are declared as
var sqrtAlt = function (x){
return x * x;
}
come up as anonymous.
Also check out this Thread
They are basically the same thing, but in the second example you additionally assign the function to a variable. This way of creating a function is very useful when overriding an existing function of some object, let's say:
window.alert = function(text)
{
// Do something ...
};
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
I am attempting to understand the "best practices" of javascript.
This code is from jqfundementals.com
// create a function that will greet a person,
// and assign the function to the `greet` variable
var greet = function( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
greet( 'Jory', 'Welcome to JavaScript' );
greet( 'Rebecca', 'Thanks for joining us' );
Why should I assign the function to the greet variable?
My first impulse would be to write it like this:
function greet ( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
What are the differences between these two implementations?
There aren't any differences between those snippets, except hoisting which allows you to call the former function in the lines before the definition. But this is just a simplistic example to get you warmed up. In reality, people don't assign these functions to variables but pass them directly to other functions. Or they otherwise use them in expression contexts. Or they dynamically decide which function to to store. Or anything else really.
There is no real difference but the var form enables you to declare-before-use incase you have recursive functions.
Simple example:
var func1, func2;
func1 = function (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
func2 = function (count) {
func1(count + 1);
}
func1(10);
Although
function func1 (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
function func2 (count) {
func1(count + 1);
}
func1(10);
is perfectly acceptable too. The interpreter will replace it with the former because of variable hoisting.