0

Following the question here:

JavaScript getting filename without extension located in different folder

I would like to concatenate this function with my string.

When I apply this code

"use strict";
window.addEventListener('load', onLoad, false);

function onLoad(evt) {
  let scripts = document.querySelectorAll('script');
  scripts.forEach(scr => {
    if (scr.src != '') {
      let slashPos = scr.src.lastIndexOf('/');
      let filename = scr.src.slice(slashPos + 1);
      filename = filename.replace('.js', '');
      //console.log(filename);
      return filename
    }
  });
}

var string = 'Date = ' + onLoad;

console.log(string)My console shows the full function instead of a certain date.

enter image description here

what should I do to have the date populated properly?

1
  • It's not clear what you expect to happen. You establish that onLoad() function as an event handler for the "load" event, but then you want to call it? The function itself returns undefined because there is no return statement except the one in the .forEach() callback, which will not have any effect. Commented Nov 3, 2021 at 11:40

3 Answers 3

2

You are not calling the function onLoad because there are no parenthesis, you are passing a reference to it which is your entire function.

var string = 'Date = ' + onLoad();

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

Comments

0

You are not running your function. You are doing something akin:

function return_string() {
 return 'a string';
}

var string = 'Date = ' + return_string;
console.log( string );

That returns the function, not the result. So just execute the function as normal

function return_string() {
 return 'a string';
}

var string = 'Date = ' + return_string();
console.log( string );

Comments

0

This is happening because in javascript if you just call the function without braces it returns the function definition instead of actually invoking the function. So, calling onload like this would return its' function definition. You should call onload() to get the actual return value of the function. But then I saw there's no return from that function as well. So what are you expecting from this function to be returned? If you want to get Date inside JavaScript you should call the Date constructor like this new Date() to get the current Date. For more information on the Date constructor visit mdn.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.