-1

function switchBooks(book) {
  book = "the book name";
}

var myBook = "new book";
myBook = switchBooks(myBook);

console.log(myBook)

I'm new to JS and want to understand why this is happening?

DecPK
  • 24,537
  • 6
  • 26
  • 42
Stevieezi
  • 3
  • 2

2 Answers2

1

To further UnholySheep's comment. You need to return the result of the function in order to access it later in your code.

From MDN Web Docs

The return statement ends function execution and specifies a value to be returned to the function caller.

In your case, the function caller is switchBooks(myBook);

   function switchBooks(book) {
       var book = "the book name";
       return book; //This is the addition
   }

   var myBook = "new book";
   myBook = switchBooks(myBook);

   console.log(myBook)
SRR
  • 1,608
  • 1
  • 21
  • 51
0

You need to add return inside the function.

function switchBooks(book) {
 return book = "the book name";
}

var myBook = "new book";
myBook = switchBooks(myBook);

console.log(myBook)