Function to save script ? JAVASCRIPT

Asked

Viewed 31 times

0

I have a script and would like just to put you inside a Function because it is not good practice to let "loose" scripts, so I would like a function that does not modify at all my script, just serve "deposit" and that my script continues working and being recognized perfectly by HTML.

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },    
    options: {}
});
<html>
<head>
<title></title>
</head>
<body>

<canvas id="myChart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>
</html>

1 answer

0


You can define functions in various ways within Avascript and make the call after, first using the function statement, which is loaded before executing

function soma(a, b){
    return a + b
}

You can also use a Function Expression that only runs after the declaration

const sub = function(x,y){
    return x - y
}

We also have Arrow functions

let dobro = (a) => {
    return 2*a;
}

We can even assign functions to variables, we usually use const, so that they are not changed. You can leave your code in something equivalent to:

function myChart(){
 var ctx = document.getElementById('myChart').getContext('2d');
 var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },    
    options: {}
 });
}

myChart(); //chamada de função dentro do script
  • 1

    Thank you, that’s what I was looking for!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.