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
ifElsefunction which has a condition oftrueorfalsepassed into it, 2 functions and 1 argument to be used in those functions. - Notice that
funcOneandfuncTwoboth take an argument ofxwhich is console logged when they are called. - We call the
ifElsefunction and pass intrueas the condition, the two functions and a string ofmyArg. - The condition is
truesoisTrueis called and themyArgstring gets console logged as it was passed in via theargargument.
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");