Published:2016-04-10
Passing Arguments in Javascript
You can pass arguments into functions to be used within the function. These arguments can be any JavaScript data type including functions.
- We create an
ifElse
function which has a condition oftrue
orfalse
passed into it, 2 functions and 1 argument to be used in those functions. - Notice that
funcOne
andfuncTwo
both take an argument ofx
which is console logged when they are called. - We call the
ifElse
function and pass intrue
as the condition, the two functions and a string ofmyArg
. - The condition is
true
soisTrue
is called and themyArg
string gets console logged as it was passed in via thearg
argument.
var ifElse = function (condition, isTrue, isFalse, arg) {
if (condition) {
isTrue(arg); // this is called, passing in the myArg string
} else {
isFalse(arg);
}
};
var funcOne = function (x) {
console.log(x);
};
var funcTwo = function (x) {
console.log(x);
};
ifElse(true, funcOne, funcTwo, "myArg");