How come this function isn't reassigning the variable? - javascript

I am doing a simple javascript problem where I have to pass an array through a function and have the array reassigned a different value. How come when I pass through an array (or even any variable) I have to specifically reassign the array in order for it to change? Can't I just use the code in the function to use the parameter to do that for me? Here's my code:
<script>
var str = 'this is my sentence';
//Write a function called reverse that takes is given str as it's only argument and returns that string after it's been reversed
function reverse(x) {
x = x.split('').reverse().join('');
return x;
}
//returns with the text reversed, but str is still 'this is my sentence' and not the reversed version
</script>

You have to actually call the reverse function. Your code works once you add str = reverse(str);
<script>
var str = 'this is my sentence';
//Write a function called reverse that takes is given str as it's only argument and returns that string after it's been reversed
function reverse(x) {
x = x.split('').reverse().join('');
return x;
}
str = reverse(str); //Call the function
window.alert(str); //show an alert box to view reversed string
</script>
EDIT
It seems the brunt of his question is [Why do] I have to specifically reassign the array in order for it to change?.
The argument is a primitive and with primitives, javascript passes by value. Meaning that the called functions' parameter will be a copy of the callers' passed argument. It is not the same item.
The alternative would be pass by reference in which case the called functions' parameter will be the same object as the caller's passed argument. In this case, changes occurring inside the function on the object passed as a parameter will be 'available' outside the function - because it's the same object. This is how Javascript passes objects.
In Javascript, a string can be either an object or a primitive depending on how you create it:
var str = "I'm a String primitive"; //This is a primitive
var str = new String("I'm a String object"); //this is an object

Related

Confused on how to approach this (writing a function, returning a string)

So I have to write a function plusLettuce that accepts one parameter as an argument and the function has to return a string that has my argument and the phrase "plus lettuce". So I'm guessing if I type in plusLettuce("Onions"); into my console I should get "Onions plus lettuce" as my output.
This is what I have so far .. so I wrote my function with a parameter and I'm confused what to do next. (I'm a total noon sorry) Do I make a variable word? I'm just stuck on what my next step has to be. Please help.
var plusLettuce = function(word) {
var word =
}
You can use the addition operator + to concatenate strings, and the return statement to return the result of the function call:
var plusLettuce = function(word) {
return word + " plus lettuce";
};
plusLettuce("Onions"); // "Onions plus lettuce"
JS uses + for string concatenation.
You're also overwriting your word (which is already there, in your function), when you declare a new var word.
So
function plusLettuce (phrase) {
// I don't say `var phrase`, because it already exists
var phrasePlusLettuce = phrase + " plus lettuce"; // note the space at the start
return phrasePlusLettuce;
}
When you give a function a parameter, it automatically becomes a local variable for that function. Meaning that you can immediately use it as a variable too.
var plusLettuce = function(word) { // I take the var word from here...
return word + ' plus lettuce'; // ...and then use it here.
};
console.log(plusLettuce('Onions')); // This is where I assign the var word.
So what's happening here is that I'm telling the plusLettuce function to return whatever the user gave as a parameter plus ' plus lettuce'. Then call it in the console.log();
In programming this is called string concatenation, what your been asked to do is make a static string concatenate with a dynamic one.
function plusLettuce (phrase){
var staticWord = ' plus lettuce';
return phrase + staticWord
}
console.log(plusLettuce('Onions'))
Remember that a parameter/argument is a variable accessible by the function only, the static part meaning it will always be the same can be a assign to a variable to keep the code clean. and the dynamic part which is the parameter will be different every time according to what is passed on to the function each time is called.

syntax for javascript reverse function

hey guys I understand that the following will work for reversing a string passed to the function:
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString("hello");
however can someone help me understand why the following won't work?
function reverseString(str) {
str.split(' ');
str.reverse();
str.join(' ');
return str;
}
Those functions don't modify the string; strings are immutable. The functions return new values.
So, a statement like
str.split('');
is a valid statement, but it has no net effect because the returned array is ignored. In the first example you quoted, the returned values are used as object contexts from which the subsequent functions are accessed and called. The return statement there returns the result of the last function call in the chain (the .join() call).
Try using var , if expected result is to re-define str , set using str = /*new value */
function reverseString(str) {
var copy = str.split("");
copy.reverse();
str = copy.join("");
return str;
}
console.log(reverseString("hello"))
Firstly, strings are immutable, you can create new required string, using methods like the first one to return value by operating/invoking methods.
The first function calls methods in chain. Meaning, the return value of one function (object/reference types only) to invoke its method to compute new result.
str.split('').reverse().join('');
Here, split returns array and array's reverse method reverses contents in array (index) and finally join method joins the array elements with ' ' as separator.
whereas in second function its just a sequential call of statements. I guess in str.join(' '); there is no function called join in string prototype.
The method calls are chained so that each method uses the return value from the previous. You can do the same in separate statements if you keep the return value so that you can use it in the next statement:
function reverseString(str) {
var arr = str.split('');
arr = arr.reverse();
var result = arr.join('');
return result;
}
console.log(reverseString("hello"));
Note also that there is a difference between split('') and split(' '). The first one splits between each character while the second one splits at space characters.

How to make variable as callable function?

I have two variable and one function.
<script>
function myfunction(a1,a2,a3)
{
alert(a1+a2+a3)
}
var fname="myfunction";
var fdata="data1,data2,data3";
</script>
I want to call function from variable values. like this
myfunction('data1','data2','data3')
I know how to call function from variable value.
window[fname](); //this call myfunction()
But don't know how to call function with multiple arguments from variable values?
Give me a solution if you can!
First, you don't have to use the name of a function to keep a reference to it. Just use the function directly:
var fname = myfunction;
Then you can call it:
fname('whatever');
To pass parameters from that string, you'll have to get them out of the string, a process that will depend on how you've combined the values into a string in the first place. In your example, you could split the string on commas to create an array, and then use .apply()
fname.apply(null, fdata.split(','));
The .apply() method accepts an array as the second parameter (the first is a value to be used for this), and then calls the function such that the values of the arguments are the elements of the array.
Just add the arguments between the parentheses
window[fname]('data1', 'data2', 'data3');
To pass dynamically the arguments by using the fdata value, you should use apply (like #Pointy suggests).
window[fname].apply(null, fdata.split(','));
you can modify your code to be something like this maybe:
<script type="text/javascript">
function myfunction(a123) {
// remove the coma if you don't want it.
var completeData = a123.replace(/,/g, "");
alert(completeData);
}
var fname = "myfunction";
var fdata = "data1,data2,data3";
window[fname](fdata);
</script>
I hope it helps.

How to use pass by reference in javascript

I am wondering if I can modify the parameter in the function?
Objects and arrays are passed by reference and changes to the argument you pass to a function will affect the original. All other types behave like they are passed by value and you cannot change the original.
Javascript does this automatically - you cannot specify that something be passed by value or by reference like you can in some other languages. If you want something passed by reference, put it in an array or object and pass the array/object.
Example 1 (passing an object):
function myFunc(myObject) {
// this changes the original object
myObject.ready = true;
}
var obj = {ready: false;};
myFunc(obj);
// obj.ready == true - value is changed
Example 2 (passing a string):
function hello(str) {
str = str + " and goodbye";
alert(str);
}
var greeting = "Hello";
hello(greeting);
// greeting == "Hello" - value is unchanged
Example 3 (passing a string in an object):
function hello(obj) {
obj.str = obj.str + " and goodbye";
alert(obj.str);
}
var o = {greeting: "Hello"};
hello(o);
// o.greeting == "Hello and goodbye" - value is changed
Example 4 (passing a number):
function hello(num) {
num++;
alert(num);
}
var mynum = 5;
hello(mynum);
// mynum == 5 - value is unchanged
Note: One thing that is sometimes confusing is that strings are actually passed by reference (without making a copy), but strings in javascript are immutable (you can't change a string in place in javascript) so if you attempt to modify the string passed as an argument, the changed value ends up in a new string, thus the original string is not changed.
I think you are meaning to ask "Is it possible to change a value passed parameter to a referenced one?"
Javascript is, by nature, a pass by reference language for objects. Primitives like numbers, booleans, and strings are passed by value. If your thinking about how PhP (or a few others) can change the pass by reference or value modifier (IE function passByRef( &refVar ) ) this is not possible with javascript. There is a good post here about how sometimes javascript can be a little more indifferent while passing certain objects and what you might expect, vs what actually happens if it helps.
Is JavaScript a pass-by-reference or pass-by-value language?

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories