Having only recently started the full-time online software engineering course at Flatiron I am by no means an expert in my desired field... yet. However I learned very quickly that you can chain methods together almost endlessly in vanilla JavaScript. That can lead to some atrocious code:
document.createElement('button').innerText = document.querySelector('#input').e.target.value
Is one example of getting carried away chaining, that while effective, is not efficient. If you were to do the same code with variables, it looks much cleaner:
const myButton = document.createElement('button')
const buttonText = document.querySelector('#input')
myButton.innerText = buttonText.e.target.value
Once I got the hang of breaking up my method chaining with variables I developed a new bad habit; making massive functions that did far to much. Typically I would write one function to do almost everything I wanted to accomplish in a feature. That frequently manifested in functions with no parameters, no callbacks, and endless nesting:
function doTheThing() {
let myButton = document.createElement('button')
let buttonText = document.querySelector('#input')
myButton.innerText = buttonText.e.target.value
document.appendChild('myButton')
myButton.addEventListener('mouseover' () => {
myButton.innerText = "ready to click"
myButton.addEventListener('click' () => {
myButton.innerText = "clicked"
})
})
}
That is an absolute mess but could easily be replaced using callbacks:
function doTheThing(theThing) {
let myButton = document.createElement('button')
let buttonText = document.querySelector('#input')
myButton.innerText = buttonText.e.target.value
document.appendChild('myButton')
myButton.addEventListener('mouseover', onMouseOver(theThing))
}
function onMouseOver(theThing) {
myButton.innerText = "ready to click"
myButton.addEventListener('click', onClick(onMouseOver))
}
function onClick(onMouseOver) {
myButton.innerText = "clicked"
}
Much better!
Top comments (0)