Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Function argument-output issue

Okay so I was experimenting with function arguments and I ran into an issue. Wanted to write a function that simply takes a boolean as an argument then switches it true to false or false to true.

Except after calling the function it doesn't work as intended. So how shall I modify the code below to make it work?

var boolean = true;

var changeBoolVal = function(param){
    param = !param;
    console.log(param); /*this returns false as intended*/
}

changeBoolVal(boolean);

console.log(boolean); /*this still returns true*/

1 Answer

Your function works fine! The problem is you're simply logging/printing the value of the boolean variable on line 1. you can see what I mean by removing the code in-between.

var boolean = true;

console.log(boolean);
// => ture

To fix this, redefine your boolean variable by storing the function call to it.

var boolean = true;

var changeBoolVal = function(param){
    param = !param;
    console.log(param);
}

boolean = changeBoolVal(boolean);

console.log(boolean);
// => false

Alternatively, you could just throw the function call inside the console.log function.

console.log(changeBoolVal(boolean);
// => false

I see. But the point would have been to write a function that takes any boolean variable as an argument and changes the value of that variable. (Sorry if the original question wasn't clear)

With this method I am still stuck at writing an extra line outside the function where I assign the output of the function to the variable. So if I have one hundred variables I have to write one hundred extra piece of line.