How to get the function arguments value? - javascript

I want to simplify my email validation by looping through all the function arguments value using arguments[i] but it returns "undefined".
function checkInputRequired(companyNameValue, contactNameValue, publisherEmailValue, publisherEmailConfirmValue)
{
// The arguments object is an Array-like object corresponding to the arguments passed to a function.
for (var i = 0; i < arguments.length; i++)
{
// print out 4 undefined
console.log(arguments[i]);
}
}

check this out
function checkInputRequired(companyNameValue, contactNameValue, publisherEmailValue, publisherEmailConfirmValue)
{
// The arguments object is an Array-like object corresponding to the arguments passed to a function.
for (var i = 0; i < arguments.length; i++)
{
// print out 4 undefined
console.log(arguments[i]);
}
}
checkInputRequired('ddd','bbbbb','sssss','dddddddddd');
when you call the function it will display the values otherwise it show the default value undefined.

Related

Why object.values(arguments) instead of directly slicing “arr”?

This is the question Prompt:
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
This is the model solution:
function destroyer(arr) {
let valsToRemove = Object.values(arguments).slice(1);
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < valsToRemove.length; j++) {
if (arr[i] === valsToRemove[j]) {
delete arr[i];
}
}
}
return arr.filter(item => item !== null);
}
My question is: why must we assign to “valToRemove” “Object.values(arguments).slice(1)” and not “arr.slice(1)”
Look at the definition again:
an initial array (the first argument in the destroyer function), followed by one or more arguments
So arr is "an initial array (the first argument in the destroyer function)"
Object.values(arguments).slice(1); is "followed by one or more arguments"
If you sliced arr then you might as well just say:
function destroyer(arr) {
return arr[0];
}
… which is very different.
That said, the modern approach to this would be to use rest parameter syntax:
function destroyer(arr, ...valsToRemove) {

For Loop inside Function, Array Enumeration

Having some difficulty with this code for my assignment.
I'm supposed to create two functions.
the first function is called calledInLoop that will accept one parameter and log the parameter.
calledInLoop = function (parameter) {
console.log(parameter);
}
the second function is called loopThrough that will accept an array, loop through each, and invoke the calledInLoop function. The result should be each element of the array is console logged.
loopThrough = function (array) {
for (var i = 0; i < array.length; i++){
calledInLoop(array[i]);
};
}
myArray = ['dog', 'bird', 'cat', 'gopher'];
console.log(loopThrough(myArray)); returns each element on its own console.log line but then returns undefined. Why is this?
The call to console.log in console.log(loopThrough(myArray)); is only printing out undefined. It does this because loopThrough does not return anything, so it defaults to undefined.
The elements in the array are printed by a call to calledInLoop in loopThrough, which in turn calls console.log.
Your loopThrough function does not return any value when called. Hence it's return value is undefined.
loopThrough = function (array) {
for (var i = 0; i < array.length; i++)
calledInLoop(array[i])
return 1
}
Now this will return you 1.
Similarly you can return any other values.

How does a function gets passed in to another function?

I have a forEach function defined to do "something" with all the items in an array:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
var numbers = [1, 2, 3, 4, 5], sum = 0;
So I could do:
forEach(numbers, console.log);
And it would print out all the numbers because 'console.log(array[i])' prints the number to the console.
I get that part.
Here's where I'm stuck: If I pass the function below into the place of the action parameter, instead of 'console.log' then at what point does the function know about every element?
forEach(numbers, function(number) {
sum += number;
});
console.log(sum);
// 15
How does it get evaluated? If I pass console.log into the last problem and it still has to be evaluated as 'console.log(array[i])' with the '(array[i])' code next to whatever parameter is being passed in, then doesn't that get applied to the entire function too since that function is the parameter? Such as below:
function(number) { sum += number; }(array[i])
at what point does the function know about every element
At no point (just like when you pass in console.log).
The forEach function calls it on this line:
action(array[i]);
At which point, it only knows about a single value from the array because that is all that is passed into it.
(It also knows about the sum variable because that is defined in a wider scope than the function).
How does it get evaluated?
It creates a new scope (with array, action and i variables) and assigns the function to the action variable - that's a function invocation.
Your
var sum = 0;
forEach([1, 2, 3, 4, 5], function(number) {
sum += number;
});
is just the same as
var sum = 0;
{ // let's assume block scope here
var array = [1, 2, 3, 4, 5],
action = function(number) {
sum += number;
},
i;
for (i = 0; i < array.length; i++)
action(array[i]);
}
If I pass console.log into the last problem and it still has to be evaluated, then doesn't that apply to the entire function too since that function is the parameter?
Yes, exactly. You are passing a function object - and whether get that by referencing the console.log variable or by creating it on the fly (with the function expression) doesn't matter to forEach. It only will get executed with action(…) - where the array[i] value is passed for the number parameter of your function.
In JavaScript, functions are first-class citizens. That means they can be treated as variables, just like strings, numbers, etc.
When you do:
forEach(numbers, function(number) {
sum += number;
});
You are passing forEach an anonymous function. Instead of the function being in a variable, it's created on-the-fly. Inside your forEach function, action will contain your anonymous function.
In for for loop, the action function is called for each element.
Heres the solution to your problems:
function forEach(array, action) {
for (var i = 0; i < array.length; i++){
if(typeof action == 'function'){
action(array[i]);
}else{
var slices = action.match(/(.+)\.([a-zA-Z0-9]+)/);
var object = eval(slices[1]);
var action = slices[2];
object[action](array[i]);
}
}
}
I've tested it with both scenarios and it works like magic

Passing Variable Number of arguments in javascript function argument-list

Can I pass a variable number of arguments into a Javascript function? I have little knowledge in JS. I want to implement something like the following:
function CalculateAB3(data, val1, val2, ...)
{
...
}
You can pass multiple parameters in your function and access them via arguments variable. Here is an example of function which returns the sum of all parameters you passed in it
var sum = function () {
var res = 0;
for (var i = 0; i < arguments.length; i++) {
res += parseInt(arguments[i]);
}
return res;
}
You can call it as follows:
sum(1, 2, 3); // returns 6
Simple answer to your question, surely you can
But personally I would like to pass a object rather than n numbers of parameters
Example:
function CalculateAB3(obj)
{
var var1= obj.var1 || 0; //if obj.var1 is null, 0 will be set to var1
//rest of parameters
}
Here || is logical operator for more info visit http://codepb.com/null-coalescing-operator-in-javascript/
A Is there a "null coalescing" operator in JavaScript? is a good read
Yes, you can make it. Use variable arguments like there:
function test() {
for(var i=0; i<arguments.length; i++) {
console.log(arguments[i])
}
}

How String.concat() implements in javascript?

In function .concat(), I can pass an arbitrary number of arguments to it.
I understand function overloading in C++, but I don't know how implement a function with unknown number of arguments in JavaScript.
How do I implement an arbitrary number of arguments to a function?
In javascript, you would use the built in parameter called "arguments" which is an array of all the arguments passed to the function. You can obtain it's length with arguments.length and each value from the array arguments[0], arguments[1], etc... Every function has this built in variable that you can use.
For example, a function to concatenate all strings passed to it.
function concatAll() {
var str;
for (var i = 0 ; i < arguments.length; i++) {
str += arguments[i];
}
return(str);
}
var f = concatAll("abc", "def", "ghi"); // "abcdefghi"
You can do this using the arguments object. See the examples and documentation here: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments
Like this -
function f()
{
var i;
for(i=0; i<arguments.length; i++)
{
alert( (i+1) + "th argument: " + arguments[i]);
}
}
All the functions in javascript has a built-in parameter called arguments which is an array containing all the function arguments passed to the function. Just iterate over this array and you will be able to access all the arguments of a function.
As an example, once I've written a function which is used to enable/disable certain button if some specific fields were not empty. I wrote this function this way -
function toggleButton() // I used jquery inside this function
{
var i;
var last = arguments.length-1;
for(i=0; i<last; i++)
{
if( $.trim($(arguments[i]).val()) === "" )
return false;
}
$(arguments[last]).toggle();
return true;
}
and called this function like this -
toggleButton("#idOfFirstField", "#idOfSecondField", "#idOfButtonToToggle");
or like this -
toggleButton("#idOfFirstField", "#idOfSecondField", "#idOfThirdField", "#idOfButtonToToggle");
so in both the cases, I was passing variable number of field ids to the function and it checked that if these fields were empty. If all of them contained some value, then it toggled the visibility of the button.
Like this - use the arguments object all functions have available :
function someFunction() {
for (var i=0,n=arguments.length;i<n;i++) {
// do something with arguments[i];
}
}
You can use the arguments array to access parameters that are not formally declared inside the function:
function printArguments() {
for (i = 0; i < printArguments.arguments.length; i++)
document.writeln(printArguments.arguments[i] + '<br />');
}
printArguments(1, 2, 3, 'etc');
Source: http://www.irt.org/articles/js008/
Any javascript function can have an arbitrary number of arguments. If function execution depends on the number or specific qualities of it's arguments, you'll have to check the arguments object, which can be iterated like an 'Arraylike' object, as others have shown.
In some cases it may be handy to convert the arguments to a real array, using something like
var args = Array.prototoype.slice(arguments).
Here's a blog entry from John Resigs page on method overloading that may interest you.

Categories

Resources