What I am trying to do is set a variable specified in a function to something, see below if that doesn't really make sense.
function getRandomFromArray(arrayName,storeVariable)
{
storeVariable = arrayName[Math.floor(Math.random() * arrayName.length)]
}
var petTypeArray = ['Cat','Dog','Ferret','Spider','Companion Bot'];
getRandomFromArray(petTypeArray,petType)
For example, set petType to a random string in petTypeArray. Am I doing it right? Am I able to do it like this?
You could use the return value of the function:
function getRandomFromArray(arrayName) {
return Math.floor(Math.random() * arrayName.length);
}
var petTypeArray = ['Cat', 'Dog', 'Ferret', 'Spider', 'Companion Bot'];
var randomElement = getRandomFromArray(petTypeArray);
This makes the code more readable. Modifying parameter values inside the function is possible but it doesn't work with primitive types such as strings and integers. You can only modify the properties of some complex object.
No. You are not doing in correctly. The reason is, the variables are just references to data. They don't mean anything themselves. So, when you say
storeVariable = Math.floor(Math.random() * arrayName.length)
you are making storeVariable refer to a new value. Thats it. You are not making changes to storeVariable. That is why it will not work. Instead, you can return the value from the function like this
function getRandomFromArray(arrayName)
{
return arrayName[Math.floor(Math.random() * arrayName.length)];
}
and make some other variable refer the returned data, like this
var randomData = getRandomFromArray(myArray);
In JavaScript, all parameters are passed by value.
This means that storeVariable receives a COPY of the value that you call with. That local copy can change but it can't influence the original.
(Yes, ALL parameters are passed by value. For those about to downvote me, objects are passed by value. That value just happens to be a reference to the original object.)
Related
I'm following some canvas tutorial. The code below is a snippet of that.
In this snippet, why would they not choose for runAnimation to be a simple boolean? I would think the x = !x statement would work anyways, but when i tried changing the code to use booleans, the code didn't work.
So, what's the difference between a boolean as primitive and a boolean as property of an object?
/*
* define the runAnimation boolean as an object
* so that it can be modified by reference
*/
var runAnimation = {
value: false
};
// add click listener to canvas
document.getElementById('myCanvas').addEventListener('click', function() {
// flip flag
runAnimation.value = !runAnimation.value;
All arguments are passed by "value" in JavaScript. This means that when an argument is passed, a copy of what's stored in the variable is passed.
Primitives (like booleans) store the actual data they represent and so, when a primitive is passed, a copy of the data is sent, resulting in two copies of the data. Changes to one, won't affect the other.
But, when you assign an object to a variable, the variable stores the memory location for where that object can be found, not the object itself. Passing an object as an argument results in a copy of the memory address being passed. In these cases, you may wind up with two variables that store the same memory address, so no matter which variable you use, the same one underlying object is affected.
In your scenario, you could certainly make it work with just a boolean variable, but it appears that the tutorial wants to encapsulate that into an object so that copies of the boolean data won't be floating around and there will be less chances of accidentally changing one variable but not another.
Here's some basic examples:
// This function takes a single argument, which it calls "input"
// This argument will be scoped to the function.
function foo(input){
// The function is going to alter the parameter it received
input = input + 77;
console.log(input);
}
var input = 100; // Here's a higher scoped variable also called "input"
foo(input); // We'll pass the higher scoped variable to the function
// Now, has the higher level scoped "input" been changed by the function?
console.log(input); // 100 <-- No, it hasn't because primitives pass a copy of their data
// ************************************************
// Now, we'll do roughly the same thing, but with objects, not primitives
function foo2(obj){
obj.someProp = 100;
console.log(obj.someProp);
}
var obj = {
someProp : 50
};
foo2(obj);
// Here, we see that the original object has been changed by the funciton we passed it to
console.log(obj.someProp);
I'm still new to Javascript so please forgive me if this seems like a silly question.
I defined a function called randomNumberGenerator, and in it is just one line of code. Basically, the purpose of it is to return a number between 0 and 2.
function randomNumberGenerator() {
return Math.round(Math.random() * 2);
};
However, when I tried to log the result of this function in my console, it shows me the outline (is that what it's called) of that function instead of a random number. You can see it here:
ƒ randomQuestionSelector() {
return Math.round(Math.random() * 2);
}
I tried assigning 'Math.round(Math.random() * 2)' to a simple variable, and logging that variable to the console. It worked as expected (I got a random number), so I'm confused why doing the same with a function doesn't.
Hope someone can help me out with this. Thank you!
The reason why console.log(randomNumberGenerator) returned such a value is that you did not really invoke this function. You called the default .toString() method which exists on every object. And default implementation (which can be overriden) returns what you saw in the console. If you want to get the result of the function you need to use () operator which calls the function, like this:
randomNumberGenerator()
And to capture the returned value you can assign it to the variable, for example:
const random = randomNumberGenerator()
console.log(random);
That way you are calling the function and assigning the returned value to the new variable.
You need to call the method. What you are likely doing is calling console.log(randomNumberGenerator) rather than console.log(randomNumberGenerator())
I want to manipulate some attributes of my page elements in a java script function , take a look at this example and maybe you find a solution to do this.
function doubleup(attr){
attr*=2;
}
doubleup(myDIV.style.zIndex);
doubleup(myDIV.style.opacity);
In short, you don't. You can't pass primitive values by reference.
You can do that with non-primitive values, though, as they're always passed as reference. Example:
function doubleup(object, property) {
object[propety] *= 2;
}
doubleup(myDiv.style, "zIndex");
doubleup(myDiv.style, "opacity");
Primitive data types are strings, numbers, booleans and, recently, Symbols
You only pass the value of this attribute to the function, so you don't change the style element, you only change the value, can do it in this way:
function doubleup(attr){
return attr*=2;
}
myDIV.style.opacity = doubleup(myDIV.style.opacity);
myDIV.style.zIndex = doubleup(myDIV.style.zIndex);
By the way, you have to use zIndex instead of z-index to manipulate this value.
Another possible solution is:
function doubleup(el){
el.style.opacity*=2;
}
function doubleupZIndex(el){
el.style.zIndex*=2;
}
doubleupOpacity(myDIV);
doubleupZIndex(myDIV);
I was trying to understand some javascript and found some quite unexpected behavior. Not knowing much about this language I wanted to find out what this behavior is called so that I can read about it formally.
Here's an example of the behavior:
var test={'x':2};
var test2=test;
test2.sourceLinks = [];
console.log('test',test);
console.log('test2',test2);
To my amazement, I found that modifying the 2nd variable somehow modifies the first as well. The variable "test" will also have an attribute .sourceLinks = []. Do I understand what's happening correctly, and if so, what's the formal term for this behavior?
I found that the answer to this is covered in How do I correctly clone a JavaScript object? after I posted it, although that covered more than I was asking about.
Behavior is called creating a reference. When variable assigned is an object actually it is not copied, rather the result of assignment is a new reference (pointer) to the object.
This doesn't happen with primitive types:
number,
string,
boolean,
null,
undefined.
But happens with all object types:
object,
Array,
function.
This difference is significant in javascript. When some value should be passed to another scope and it might be modified there it should be passed be reference.
function main(){
var x = 1;
modify(x);
console.log(x);//x remains 1
}
function modify(arg){
arg = 10;
}
Whereas when it is passed as a field of an object, it can be modified via reference to an object:
function main(){
var o = {x : 1};
modifyObj(o);
console.log(o);//o.x now equals 10
}
function modifyObj(arg){
arg.x = 10;
}
It's holding the reference.
When you assign object/array/function to another object/array/function it'll assign reference instead of value.
To overcome this you have to clone it
When declaring a variable in Javascript you are creating an object in memory and the variable in the scope is a pointer to that memory object.
In your example both variables (test and test2) are pointing to the same object. Hence, when you modify the the either variable pointer, it is modifying the same object in memory.
I need to change array to a new array created inside a function.
function changeArr(a)
{
a=["hello"]; // don't work
//a.push("hello"); //works, but the real array pretty big (dont want copy)
}
var arr=[];
changeArr(arr);
console.log(arr); // should echo ["hello"]
It seems like all you really want to do is clear the array that is passed into the function, before appending to it:
function changeArr(a)
{
a.length = 0; // clear the array here if you don't care about the prev. contents
a.push("hello"); // this adds to the array that was passed in
}
Inside the function changeArr(), a is only a local variable referencing the array you passed as an argument when calling this function. a=["hello"] makes this local variable reference a newly created and different array. This changes does not affect the original array passed in. What you want to do is likely what Miky Dinescu suggested: use the local variable to modify the original array but don't assign/attach anything new to it.
If you are trying to completely replace the array, you can use a return value.
function changeArr()
{
return ["hello"];
}
arr = changeArr();
If there is a reason you aren't doing this, explain and I'll adjust my answer.
You can use the splice method as such:
a.splice(0,a.length,"hello")