Set an array as parameter in javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to parse an array from one function ton another.
I have seen in other posts that ".apply" can be used as in this example:
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
But in my code I want to parse to other function not just one array, I want to parse the array and two strings more. So mi code looks more like:
var array = [1, 2, 3];
var string = "something":
var string1 = "something":
ShowM(array, string, string2);
function ShowM(array, string1, string2) {
alert(array[1] + string1 + string2);
}
Is there any way to do that without changing the original location of the elements of the arrays for not getting undefined?. Thnks

If the question is purely about how do you set an array as a parameter in Javascript as your topic question states, you just do like any other variable.
var array = [a,b,c];
var str = "hello";
var str2 = "something";
function foo(x,y,z) {
// do stuff...
}
foo(array, str, str2); //executes function with the 3 parameters

If you just want to pass the array into a function, you can pass it as you would any other variable:
function showM(a, b, c) {
// empty function definition
}
var x = [ 'p0', 'p1', 'p2' ];
showM(x, "some string", "another string");
All arrays are passed by reference in javascript, so when you alter a passed array's contents within the function, the contents will change across all scopes. And duck-typing means that you can use any variable type as an argument.
The apply function, on the other hand, calls a function with a given content and an array of arguments (which it expands, like with the ES6 spread operator):
// equivalent to the other call, except "this" is bound to null
showM.apply(null, [x, "some string", "another string"]);

Related

Javascript is it bad practice to return an object that is passed by reference [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();

What to think about before defining function as Object.prototype extension or just function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
For example I have to add 'foo' to string.
So I have at least two ways to go.
First, I can implement String.prototype.foo:
String.prototype.foo = function() {
return this + 'foo';
};
var s = 'str';
var data = s.foo(); // "strfoo"
Another way:
function foo(str) {
return str + 'foo';
}
var s = 'str';
var data = foo(s); // "strfoo"
Both look pretty. But should I think about any "underwater rocks" before choosing first or second implementation? Are there any significant reasons, such as efficiency and performance?
The first extend the functionalities of String.
Use this solution if you have a class of objects and you like to add new behaviours to it.
The second is more an utility function.
Note also that you can apply the second foo also to a variable that is not a String, so you should also test the type of the argument if you like to limit the use to a String argument.
Modifying the globals in JavaScript is always a bad decision. Don't do that, except if it's not about making a polyfill.
The implications are multiple from your code being not portable to probability of breaking someone else's code.
I would always use the second method. Or if things are really that complicated maybe implement my own class of String.
function MyString(str) {
this.str = str;
}
MyString.prototype.foo = function() { return this.str + "foo" };
var s = new MyString("str");
var data = s.foo(); // "strfoo"
Here is further reading about modifying global objects and the downsides :
https://softwareengineering.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea

What does the "{}" mean in Javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In javascript, we can initialise a variable with {}. What does the "{}" mean?
var o = {};
o.getMessage = function ()
{
return 'This is an example';
};
return o;
This means you create an object with a variable
Its known as object with literal notation.which seems like below .
var o = {}
here your object has no property or it can be say as empty literal block .But in the below code
var o = {
o .first= 20;
o .second= 10;
o.result =function(){
return this . first- this .second;
}
} ;
now you have your object with property and function
** though there are several ways of creating object But Literal notation is the easiest and popular way to create objects
Basically the different cases are:
Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Basically, it is an empty object. When you add the getMessage() function at the bottom of the variable, you actually added it to the empty object, resulting to your empty object now to look like this:
var o = {
getMessage: function() {
return 'This is an example';
}
};
You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope.

How might the syntax `foo(a)(b)` be useful? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Today I have found a strange way of adding 2 numbers in javascript:
Basically the call of the method looks this way: add(5)(6) and the declaration of the method is:
function add(x) {
return function(y) { return x + y; };
}
Ok, I got it. The add function does not return a number, but returns the anonymous function which adds the first number with the second. But what is the point (how it can be helpful)?
Where exactly can it be useful apart from puzzling other people or writing some sort of obfuscated malware?
Obviously, the call add(5)(6) is not too useful - you'd rather write 5 + 6, or, if it's really a function, add(5, 6).
The great benefit is in functional programming where you are supposed to pass a function around (callback!) - most prominent in the array utils. For example:
[1, 2, 3].map(add(5)) // [6, 7, 8]
You can also use this for the composition of quite complex functions, without having to deal with function expressions. If we didn't have this curried add function, in the above example we would have needed to write
[1, 2, 3].map(function(y) {
return 5 + y;
}) // [6, 7, 8]
…and that every time for each different x.
Lets have a look at a function which is bit more common in the wild, pluck:
function pluck(prop) {
return function(obj) {
return obj[prop];
}
}
This function accepts a property name and returns a new function which, given an object, returns the property of that object.
This is useful for mapping an array of objects to an array of a specific property of those objects:
var names = people.map(pluck('name'));
Now, if you just have to do this a single time, there is no need to create a dedicated pluck function. However, if you do this multiple times, it avoids code repetition.
You wouldn't necessarily use it as you've described, but perhaps if you want to pass around a function that "adds 5 to the result", you could do
var addsFive = add(5);
// some other code, perhaps passing this var to another function
var result = addsFive(6); // returns 11
This technique of "partial" function invocation is called currying - this other SO question goes into some details on how/where it can be useful, as well as provides several links to help explain the concept.

Does this code add class attributes to the foo array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Below is a piece of working code. The "= true" part is confusing to me. This is what I think is happening.
1- create empty array.
2- take the selected list items (targets) and loop.
3- if the class attributes for the target list item is not in the array then enter if block.
4- add the class attributes for the target list item and add them
to the array.
My understanding is that javascript uses "push" and jquery uses "add" to
insert items into an array. The code below does not use push or add.
var foo = [];
$($targets).each(function(i) {
if (!foo[$(this).attr('class')]) {
foo[$(this).attr('class')] = true;
}
});
The code is flawed, you'd use an object instead of an array if you want to use strings as keys:
var foo = {};
Then it checks if the key is falsy in the object, although you may want to check for strict existence with the in operator:
$targets.each(function() {
var klass = this.className; // cache, no need for jQuery
// if `foo` doesn't have the key `klass` then add it
if (! (klass in foo)) foo[klass] = true;
});
Unless the class names are numbers like "1" or "2", you can't access items inside the array that way. That said, arrays are built from objects. So for example you can do things like this:
var foo = ['a', 'b', 'c'];
foo.bar = 'hello';
foo;
//=> ['a', 'b', 'c']
foo[0];
//=> 'a';
foo['bar'];
//=> 'hello';
So what's happening is that your script is not adding those items into the actual array. Instead, it's assigning them to the array as if it was a regular JavaScript object.

Categories

Resources