Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I shorthand my code to "print(//some text)?"

I am learning JavaScript, and I am working on this code, but part of it requires me to continuously send new alerts to the screen. I found a way to print the messages straight on the screen, and it works perfectly.

I’m just wondering if there is a way to shorten it further. It’s not a super big issue, other than it looks cleaner to me, but mostly its just once i get an idea in my head i want to figure how to do it. For example, as you can see in the code below, right now I use:

const show = document.getElementById('htReadOut');

show.innerHTML = `some text`;

BUT I’d like to reduce the second line further to just be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print = `some text`;

I tried making a function and an object type, but get an error that the the id’s in the new html aren’t defined.

I tried making a constant variable so that print would be short for show.innerHTML, but I get an error when I try to use "print = someText" since it thinks I’m trying to redefine print.

>Solution :

Set your code like this. Then, you can use the print function as much as you want to print the message to the screen. If you are only using show with text, you don’t need to use innerHTML, it is enough to just use innerText like in the example below.

const show = document.getElementById('htReadOut');

function print(message) {
    show.innerText = message;
}

print("Hello"); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading