GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.

Exercise 9

What does the following program log to the console? Why?

let foo = {
  a: 'hello',
  b: 'world',
};

let qux = 'hello';

function bar(argument1, argument2) {
  argument1.a = 'hi';
  argument2 = 'hi';
}

bar(foo, qux);

console.log(foo.a);
console.log(qux);

Solution

This program logs 'hi' and 'hello' to the console. This is because objects are mutable and primitives are immutable.

When bar is invoked on line 13, argument1 is initialized to an object and argument2 is initialized to a string value.

Line 9 reassigns an object property (argument1.a), which will mutate the object. Line 10 reassigns a variable, which completely replaces the value of the local argument2 variable.

Thus, line 9 mutates foo by reassigning its a property to a new value ('hi'), and line 10's variable reassignment doesn't affect any variables outside of bar.

Because foo was mutated, the access to foo.a on line 15 logs 'hi'. On the other hand, the variable reassignment on line 10 does not mutate qux's value, so line 16 logs hello - the original value of the qux variable.

Video Walkthrough

Hi! I'm LSBot. I can help you think through the selected exercise by giving you hints and guidance without revealing the solution. Your code from the editor will be automatically detected. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...

Submit your solution for LSBot review.

Hi! I'm LSBot. Your code from the editor will be automatically detected. I'll review your solution and provide feedback to help you improve. Ask questions about your solution or request a comprehensive code review. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...