1

Here, is the simple code where i'm trying to change the background color once I clicked on the button

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];

colorBtn.addEventListener('click', changeColor);

    // const changeColor = () => {
    //     let random = Math.floor(Math.random() * colors.length);
    //     bodyBcg.style.background = colors[random];
    // };

function changeColor() {
    console.log('color change event');
    let random = Math.floor(Math.random() * colors.length);
    bodyBcg.style.background = colors[random];
}
body {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
}

.colorBtn {
    padding: 0.25rem 0.5rem;
    border: 10px;
    background-color: gray;
    color: white;
    outline: none;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hex Colors</title>
    <link rel="stylesheet" href="./main.css">
</head>
<body>
    <button type="button" class="colorBtn">Click here to change color</button>
    <script type="text/javascript" src="./script.js"></script>
</body>
</html>

But when we try with the Arrow Function named changeColor, it's not working: Not able to understand the concept behind this.

const changeColor = () => {
let random = Math.floor(Math.random() * colors.length);
bodyBcg.style.background = colors[random];
};

As well, It works fine in the chrome browser, but when I tried to put debug point on the working changeColor function, It throws error:

const colorBtn = document.querySelector('.colorBtn');
ReferenceError: document is not defined
3
  • 3
    Uh, if you have the exact same code but just replace function changeColor with const changeColor, you are running into a temporal deadzone problem. Is that your issue or something else? Commented Jun 4, 2019 at 7:52
  • 3
    What error do you get when using an arrow function? Probably the issue is that you're trying to use the function before you define it, whereas a function declaration is hoisted…? Commented Jun 4, 2019 at 7:52
  • Great! Learned new concept of "hoisted" With using of ArrowFunction I should take care of this! :) Commented Jun 4, 2019 at 7:55

2 Answers 2

2

It is not working because your changeColor variable is undefined when you want to link its function to the event listener.

Just define it before attaching your event listener.

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];

const changeColor = () => {
  let random = Math.floor(Math.random() * colors.length);
  bodyBcg.style.background = colors[random];
};

colorBtn.addEventListener('click', changeColor);
body {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
}

.colorBtn {
    padding: 0.25rem 0.5rem;
    border: 10px;
    background-color: gray;
    color: white;
    outline: none;
    cursor: pointer;
}
<button type="button" class="colorBtn">Click here to change color</button>


As a side note: in this case, changeColor is a variable containing an anonymous function.

Please, look at @Duc Hong's answer for an explanation about hoisting.

Sign up to request clarification or add additional context in comments.

Comments

1

what you're running into is called hoisting. JavaScript uses two main methods for defining a function: Function declarations (sometimes referred to as function statements) and function expressions.

Function Declaration:

function fncName() {}

Function Expression:

const x = function fncName(){}

The main functional difference between these two methods is that function declarations are hoisted, meaning you can invoke the function even before it has been defined. Function expressions are not hoisted.

In your case, the arrow function is Function Expression, so:

const x = () => {}

is identical to:

const x = function fncName(){}

As much as I understand, arrow functions is used for 2 reasons: minimal syntax and lexical this .

Please take notice of this from Arrow functions on Mozzila site

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.