I apologize if this is a noob question, I'm still kind of new to JS, Why doesn't overwriting a variable work inside a function?
var o = {x: 1};
function foo(){
// Overwrite var `o` with a string
arguments[0] = "string";
}
foo(o);
console.log(o); // Why is `o` still an object and not the string `string`?
-- Update based on responses ---
But why does this then work?
// Define an array literal
var a = ["a", "b"];
// Execute whatever function is passed to manipulate the array
a.execFunc = function(func){
func(this) // Pass this array (object) to it
}
// Invoke `execFunc` function passing another function
a.execFunc(function(thisArray){
thisArray[0] = "c"; // Change first element to "c"
})
console.log(a); // => ["c", "b", execFunc: function]: IT WORKED! a → c
--- Update #2 ----
Sorry just trying to wrap my mind around what is being said - why then DOESN'T this work? Isn't it basically the same as above? I'm modifying the original array just like above, not an arguments
object, aren't I?
// Define an array literal
var a = ["a", "b"];
// Execute whatever function is passed to manipulate the array
a.execFunc = function(func){
func(this[0]) // Pass the first element (object property) to it
}
// Invoke `execFunc` function passing another function
a.execFunc(function(firstElement){
console.log(firstElement = "c"); // Change first element to "c"
})
console.log(a); // => ["a", "b", execFunc: function]: first element is still `a`