1
let menu = {
    width: 200,
    height: 300,
    title: "My menu"
};

function multiplyNumeric(obj) {
    for (let key in obj) {
        if (typeof obj[key] == "number") {
            obj[key] *= 2;
        }
    }
}

multiplyNumeric(menu);

alert(menu);
console.log(menu)

I ran into this problem.

so at the end of the code when I do alert(menu); I get [object Object].

but when I do console.log(menu); I get { width: 400, height: 600, title: 'My menu' }. Which is what i wanted. So what's causing the difference?

ChrisF
  • 131,190
  • 30
  • 250
  • 321
ChromeBrowser
  • 189
  • 1
  • 5
  • 1
    Does this answer your question? [difference between console.log / document.write and alert](https://stackoverflow.com/questions/35682997/difference-between-console-log-document-write-and-alert) – PIG208 Dec 15 '20 at 08:46

2 Answers2

3

That is because menu itself is an Object.

When we use alert, a pop up box opens with a given message, which expects a String. When passed with an Object, you will instead get [object Object]

Try alert(JSON.stringify(menu)) instead to see the full stringified output

IcyBloom
  • 193
  • 10
1

If you read properly on w3schools. Alert takes string as parameter and your menu isn't a string it's object so instead of showing menu it shows the type of menu

you can do something like this :

alert(JSON.stringify(menu));
Ashish
  • 6,494
  • 3
  • 21
  • 42