0

innerHTML (Javascript)

When using innerHTML, one can use the keywords as variables: var let or const, they all have their differences. And all 3 keywords seem to work correctly with innerHTML. But in most or all tutorials, innerHTML is being used only with "const" and not with var or let. Why?

4th Feb 2022, 1:21 PM
CodeX
CodeX - avatar
4 Réponses
+ 3
Perhaps they preferred to use const there to ensure that reassignment of the reference (object) should not be allowed. And it's probably considered safer, since any reassignment attempt to a const will trigger error. An accidental problem prevention, as learners tend to modify things as they play with the code. Use of const helps learners to understand that const objects/values are not to play around with, mindlessly ...
4th Feb 2022, 2:25 PM
Ipang
+ 2
Use of keyword as identifier is not recommended. innerHTML can be used to obtain or modify content of any element capable of displaying text or HTML elements within. These are generally the paired elements, ones having an opening and closing tags https://sonalsart.com/what-is-an-unpaired-tag-in-html/ The use of `const` specifies that the identifier cannot be reassigned another reference, or value. An attempt to assign another reference or value to an identifier specified as `const` will trigger error. Members of a const object or array can still be modified. It's just that the identifier representing it cannot be reassigned another reference or value. let n1 = 5; n1 += 35; // okay console.log( n1 ); const n2 = 32; n2 += 10; // error, Assignment to constant console.log( n2 ) var arr1 = [ 1, 2, 3, 4, 5 ]; arr1 = [ 6, 7, 8, 9, 10 ]; // okay console.log( arr1 ); const arr2 = [ 1, 2, 3, 4, 5 ]; arr2 = [ 6, 7, 8, 9, 10 ]; // error, Assignment to constant console.log( arr2 );
4th Feb 2022, 2:00 PM
Ipang
+ 1
Example of changing text content: const myDiv = document.getElementById('my-div'); myDiv.innerHTML = ' New'; It also works when using let myDiv = document.getElementById('my-div'); Or var myDiv = document.getElementById('my-div'); All 3 variants changing the text. I see the differences between var let const, but why does anyone is using only const with that document.getElemenById , I mean, as long as it works too...?
4th Feb 2022, 2:10 PM
CodeX
CodeX - avatar
+ 1
Makes sense, good explained!
4th Feb 2022, 4:08 PM
CodeX
CodeX - avatar