why this code returns undefined when I first run

I want to get a base64 string from an uploaded image. First time when i run the code, it returns undefined. When i run after it works fine. How can i fix this?

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <input type="file" id="file">
    <button id="button" onclick="upload()">Upload</button>
    <script type="text/javascript">
      var result;

      function getBase64(file) {
         var reader = new FileReader();
         reader.onload = function () {
           result = reader.result;
         reader.onerror = function (error) {
           console.log('Error: ', error);
         return result;

      function upload() {
        var file = document.querySelector('input').files[0];

Source: JavaSript – Stack Overflow

November 18, 2021
Category : News
Tags: base64 | html | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.