ADITYA UDAY UBALE
ADITYA UDAY UBALE

Reputation: 23

is there any way to assign a particular line to a variable which is frequently used?

There is a frequent use of document.getElementById() in my code . so is there any way to abbreviate this long line of code to a small variable , if possible?

Upvotes: 0

Views: 34

Answers (1)

Omkar76
Omkar76

Reputation: 1628

You can use a wrapper function like :

const byId = (id) => document.getElementById(id);

Or

Assign document.getElementById to a variable by binding it with document object.

const byId = document.getElementById.bind(document);

Note: In second approach, If you don't bind document.getElementById with document you'll get error :

Uncaught TypeError: Illegal invocation

What Function.bind does is it creates a new function with its this keyword set to value that you provide as argument to Function.bind.

Read docs for Function.bind

Upvotes: 1

Related Questions