-3

I want to know how JavaScript deals with code, what happens in the browser
Code 1 (working code)

let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(function(item) {
    if (item === 'Item 2') {
        item = item.toUpperCase();
    } else {
        item = item.toLowerCase();
    }
    console.log(item);
});
// output item 1
//        ITEM 2
//        item 3 

Code 2 (not working)

let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(function(item) {
    if (item === 'Item 2') {
        item.toUpperCase();
    } else {
        item.toLowerCase();
    }
    console.log(item);
});
// output Item 1
//        Item 2
//        Item 3 
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

2 Answers2

2

item.toUpperCase(); returns the uppercased string that is why when you do item = item.toUpperCase(); the uppercased string is assigned to item and since item is a array element, the element is changed by its reference.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Here item = item.toUpperCase(); in bold is creating a local variable which is getting printed , but in the later case it is just the reference and the function argument which is printing

brk
  • 48,835
  • 10
  • 56
  • 78