var obj = {
y: 4,
};
var nonMutatingFn = function (obj) {
var newObj = {
x: obj.y,
};
newObj.x += newObj.x + 1;
return newObj;
};
nonMutatingFn();
//Can someone help out with what’s causing the error in this pls?
var obj = {
y: 4,
};
var nonMutatingFn = function (obj) {
var newObj = {
x: obj.y,
};
newObj.x += newObj.x + 1;
return newObj;
};
nonMutatingFn();
//Can someone help out with what’s causing the error in this pls?
Well, for one thing, nonMutatingFn takes an obj as an argument but you are calling it without passing in an object.
So how do I call it? I’m not getting any output when I pass an object while calling the nonMutatingFn. @bbsmooth
var password = [1,2,3,4,5,6]
That is in the global scope i.e can be referenced anywhere.
Functions are exactly like maths’ functions. If you write an argument, that’s only a placeholder. Code:
let x = 5
var fn = function(){
return x
}
fn()
What will that return? Now…
let x = 5
var fn = function(x){
return x
}
fn()
What would that return?
When an argument has the same than a global variable, it overwrittes it. So function (x){//}
is much like saying function (let x){//}
And yet x
here is undefined, not assigned.
Now if you pass obj
(or x
) you’re redefining obj like this let obj;
so it’s undefined inside the function.
I just wanted to remaind you of that…in case it helps…
Edits
Sorry I’ve tried to shorten the text as much as possible
Now if I understand the exercise, you want to return a new object with an updated value.
So I’d go about more or less like this:
let game = {score:20}
var updater= function(){
var newScore = {score: game.score}
newScore.score += newScore.score + 1
return newScore
}
let newObject = updater()
I would probably not use a function that depends on a global variable like that.
Well I kept it as close to the post as I could…I guess you can build on the top. I don’t mind…
You pass in the object to the function just like you would pass in any other value to a function. You defined nonMutatingFn as:
var nonMutatingFn = function (obj) { ... }
The anonymous function you are using to define nonMutatingFn takes one argument (obj
). So when you call nonMutatingFn you must also pass in one argument.