TOP-40 List of JavaScript Commands, JS Codes List - ByteScout
  • Home
  • /
  • Blog
  • /
  • Discover the List of 45 JavaScript Commands in 2020

Discover the List of 45 JavaScript Commands in 2020

As the most common programming language, it is imperative that programmers and developers understand JavaScript code and JS commands. Developers with mastery over JavaScript code are the most valuable to employers. If you are new to web development and programming language, you will want to familiarize yourself with the JavaScript commands list.

In learning JavaScript, it is essential that you learn about the best JS commands because this will allow you to craft JavaScript code with more precision. Here, you will find a detailed JavaScript developer tutorial with everything you need to know about the top 20 in JavaScript list of commands.

  1. document.getElementById()
  2. Basic Input / Output
  3. SetTimeout()
  4. Setinterval()
  5. ClearTimeout
  6. Var
  7. Self-calling
  8. Math
  9. Map
  10. Debounce
  11. Poll
  12. Once
  13. GetAbsoluteUrl
  14. String
  15. Array.Push
  16. Array.filter
  17. Array.reduce
  18. String.toLowerCase
  19. IsNative
  20. String.substr
  21. debug
  22. string.toLowerCase
  23. Retur
  24. floor
  25. For loop
  26. The If-Else
  27. constructor
  28. Math Object
  29. JS Date
  30. Error Object
  31. toExponential
  32. toFixed
  33. toPrecision
  34. valueOf
  35. parseInt
  36. normalize()
  37. slice(start,end)
  38. Epsilon
  39. toJSON()
  40. toISOString()
  41. Proxy()
  42. Promise
  43. Mixins
  44. Autocorrection
  45. unescape()
  46. Bonus query – NEGATIVE_INFINITY

Check this video about the most common JavaScript commands:


 

The Three Data Types of JavaScript Code

There are only three data types in JS commands that are considered primitive. This means that more complex operations can be built using these three data types, but the data types are not derived from other procedures themselves. Additional properties cannot be added onto the primitive data types. These data types are number, string, and boolean.

Number

The Number() function returns the solution to an equation. The Number() function can also return a value of NaN, meaning not a number. This happens when a calculation is impossible to perform, as an attempt to divide 0 by 0. Any mathematical expression that is undefined will result in NaN. For example, a line of JS code that reads Number(“JS tutorials for developers”) will return NaN because this is not a numerical value. You would need to use the String() function for this object. The Number() function will return a value of 0 if there is no argument provided within the object’s parameters.

String

The String() function of JavaScript code returns a value containing alphabetic characters. For example, a line of code that reads String a=new String(“There are three primitive data types”); will print the phrase There are only three primitive data types. The character, a, is a reference variable. The words in parentheses are known as the object. It is important to remember that you cannot make changes to a String() method after it is created.

Boolean

The Boolean() function converts an object into one of two responses. A Boolean returns a value of either true or false. The instances in which a Boolean object has a value of false are…

  • when the value parameter is null
  • when the value parameter is undefined
  • when the value parameter is 0
  • when the value parameter is -0
  • when the value parameter is not included
  • when the string is empty

Learn Business Automation – Try RPA Tools

Importance of Semicolons

When working with JS code, it is important that you properly execute line termination. The best practice for terminating a line of code is to place a semicolon at the end, though if you forget, JavaScript software will insert one on your behalf. In the case of JavaScript malfunctions, you could end up with a line of code that has not been properly terminated. This is a rarity. However, it could happen and potentially cause an error in your JavaScript coding. Manually inserting semicolons should be a habit that you adopt, even with JavaScript’s automatic insertion of semicolons. Semicolons make JS code easily readable by everyone.

Just about every webpage, mobile app, and web application use some JavaScript. The open-source programming language allows for more dynamic and engaging applications. It is also very easy to learn because it only has a few rules, letting you achieve simple tasks with just a few lines of code. You do not need to import packages or declare namespaces. You just write some code, and it works. However, the lack of structure can lead many beginner developers to write unstructured, fragile code that can lead to unexpected, difficult-to-find bugs.

Because of this, it might be wise to develop a JavaScript cheat sheet for yourself. You would then have a list of useful commands you can reference when you need help completing a project. With the flexibility of the language, you will never find a definitive list of the best JavaScript keywords. Every programmer is different and your particular needs can vary wildly from everyone else.

Still, here’s a list of the most popular commands that are worth keeping up your sleeve:

1. document.getElementById()

JavaScript and its many frameworks such as JQuery let you process code based on a particular HTML name or class. While this works, it can slow your script as it must go through the entire script to find the right tag. You can speed up this search through your applications document object model (DOM) by using element ID.

2. Basic Input / Output

Except for the most basic scripts, all applications require some user interaction. With JavaScript, this function comes in the form of the alert() and prompt() commands. Alert sends info to the user through a dialog box, while prompt asks for a response.

alert("message");

stringVar = prompt("message")

3. SetTimeout()

SetTimeout lets you automatically run commands at a specific time without user input. This simple JS command just requires the command you want to run and when you want to run it.

setTimeout(command, time);

You must express the time in milliseconds, but you can use any JavaScript statement as the command. For example, the following code runs the myfunction command after 5 seconds.

setTimeout(myfunction, 5000);

4. Setinterval()

You can also repeatedly run JavaScript commands using the setinterval command. Setinterval is great when you need your application to refresh its data from the database.

setInterval(command, time);

5. ClearTimeout() and ClearInterval()

If you will use either settimeout or setinterval, you will want to use their associated clear command as well. ClearTimeout and ClearInterval take the variable name for a set command and then delete it from memory.

$timer = setInterval(command, 5000);
clearInterval($timer);

6. Var

It’s a simple command, but most JavaScript developers forget to use it. Var formally creates your variables. While you can create and use JavaScript variables without it, the language treats these variables as a global variable. This is fine if that is your intention, but risks overriding something if you are not careful. It also uses more resources. You can improve the performance of your app just by formally declaring your variables.

7. Self-calling Function

A self-calling function is a JavaScript command that runs as soon as you create it. These commands are also called Self-Invoked Anonymous Functions or Immediately Invoked Function Expressions (IIFE).

(function(){    // some private code that will be executed automatically})

8. Math.random()

The Math.random command generates random numbers.

9. Map()

The map() command lets you loop through an array or collection. This is perfect for running the same command over a large array.

10. Debounce()

Debounce limits how often a JS command will run. Functionally, it is the opposite of timeout. It is especially good if some repeated user interaction would slow down performance or cause other problems.

11. Poll()

Many JavaScript commands do not warn the system when they finish running. Sometimes, you must manually poll to see if something stops or if there is an exception. It is a complex command to use though, but it is worth the effort.

12. Once()

Once lets you run a command once and only once during the execution of an application. You mostly find these commands in event listeners.

13. GetAbsoluteUrl()

This JavaScript command gets you the actual URL of a web address, especially if it is contained in a string. It just takes the URL string and it gives back the address with all the queries and other elements removed.

var getAbsoluteUrl = (function() {var a;return function(url) {if(!a) a = document.createElement('a');a.href = url;return a.href;};})();// UsagegetAbsoluteUrl('/something'); //

14. String.replace()

The replace command lets you change the text in a string. It searches the string for the text you want to be replaced and switches it out for what you want. The search pattern can be either a simple text string or a regular expression. The command then returns this new string, leaving the original string unmodified.

15. Array.Push()

Push adds items to arrays. It changes the array directly without returning anything.

16. Array.filter()

The filter takes items out of an array based on some criteria and then creates a new array with just those items.

17. Array.reduce()

Reduce is an often-overlooked array command. It converts the items of an array into a single item. Perfect for calculations, it can return any type of variable.

18. String.toLowerCase()

ToLowerCase sounds like what it does. It converts a string to all lower-case letters. This popular command lets you convert data into standard URL formats that most web browsers will understand.

19. IsNative()

This function indicates if a given browser feature is native to a particular browser or if it comes from a third-party app.

20. String.substr()

Substr dives into a string and returns text based on the provided criteria. You must specify where you want it to start, and how many characters you want the command to retrieve.

Some of these twenty commands are built into the language. Others are useful snippets of code that the JavaScript developer community saw fit to create. Either way, all JavaScript commands will help you improve your knowledge and skills.

21. debug(message)

This is one of the most important Javascript commands. This command is used to send messages to the console window. For example,

console.debug("log message");

The above command is sending the log message to the console window. This command is equal to console.log command. Objects that are transferred by applying the command are transformed into a string value. This is mostly used in Microsoft Visual studio as a console log command.

22. string.toLowerCase()

The toLowerCase() function does precisely what you believe it would. It just delivers a new string that has been transformed to all lower case from the old string. The initial string is not modified. For example, if your text is in the capital and now if you want it in the lower case then this function helps you to get that output.

23. Function Retur

When JavaScript arrives at a return statement, the function will terminate performing. If the function was requested from a Javascript statement then JavaScript will “return” to perform the code after the beginning statement. Functions usually calculate a return value. You can always reuse this code. The return value is “reflected” back to the “visitor”. For example,

var a = newFunction(6, 4);   // called Function, the return value will       be in a
function newFunction(x, y) {
  return x * y;             // Function returns the multiplication of x and y
}

The output of the above function is 24   

24. floor()

The floor is one of the most important javascript methods. The floor() method spins a number to the most next integer and delivers the result. If the given parameter is an integer, the argument will not be rounded. For example, the below command will round the entered argument to the nearest integer.

Math.floor(1.6);

25. For loop

JavaScript contains for loop commands like Java and C.If you want to execute some code repeatedly then the For loop command is crucial. The syntax of this command is as follows:

for(initialize; condition; iteration)
{
    // Code
}
for (var a = 0; i < 10; a++) { console.log(a); }

The for the loop needs the three sections. The first one is Initializer which initializes a variable, to begin with. The second section is a condition where you define a situation that must decide to true for the next repetition. The third segment is Iteration which is used to increase or decrease the counter.

26. The If-Else

The if/else command performs a section of code if a defined condition is valid. If the condition is invalid, another section of code can be performed. The if/else command is a piece of JavaScript’s “Conditional” commands, which are utilized to execute various activities based on various circumstances. For example, the following command is displaying the use of the command.

var time = new Date().getHours();
                               if(hours<12)
                               document.write("Hello, We will meet tomorrow morning<br />");
                               else
                               document.write("Hello, We will meet tomorrow afternoon<br />")

The above example shows that the conditional command is used to determine the course of the execution on various conditions. As mentioned earlier, if a condition is valid, you can complete one step and if the condition is invalid, you can complete a different step.

27. constructor()

These JavaScript Commands are useful for creating special methods. Now, if you want to make a special method for creating and initializing an object created within a class the constructor() can be used. You just have to mention it in the following format.

constructor([arguments]) { ... }

28. Math Object

These best JS Commands are also known as objects which are essential for making a dynamic application. The Math object allows users to complete mathematical assignments. Math is not a constructor. All features/techniques of Math can be summoned by applying Math as an object, without building it. For example,

Math.sqrt(25);

29. JS Date

The date is an important member of the JavaScript Command List. The Date object is applied to operate with dates and times. These objects are constructed with a new Date(). For example,

var a = new Date();

30. Error Object

The Error object gives an error message when an error happens. Out of all the JavaScript List of Commands, the Error object is crucial for identifying and presenting error messages. For example,

try {
myalert("Hello");
}

catch(err) {
  document.getElementById("task").innerHTML =
  err.name + "<br>" + err.message;
}

31. toExponential()

These JavaScript commands are part of the numerical methods and properties. This toExponential() method gives a string, with a number wheeled and formulated using exponential representation. For example, a parameter specifies the number of characters following the decimal point. For example,

var y = 9.656;
y.toExponential(2);   will return 9.66e+0

32. toFixed()

with JavaScript, methods, and features are also possible to use for fundamental values. This is because JavaScript uses primitive values as objects when executing systems and characteristics. toFixed() passes a string, with the number addressed with a detailed number of decimals. For example,

var y = 9.656;
y.toFixed(6); will return 9.656000

33. toPrecision()

The toPrecision() gives a string. It returns a number addressed with a detailed length. In JavaScript, toPrecision() is applied to change a number to accuracy like spinning the result where required and deliver its content as a string. It must be called through a special case of the Number class. For example,

var y = 9.656;
y.toPrecision(2) will return 9.7

34. valueOf()

The valueOf method delivers the appropriate Number Object containing the value of the argument declared. The parameter can be a primitive data type. This is static. The method can accept two parameters. For example, 

var y = 125
;
y.valueOf(); will return 125 from variable 
y (123).valueOf(); will returns 125 from literal 125

35. parseInt()

The parseInt() parses a string parameter and gives an integer of the stipulated radix. You can also say that it returns the base in analytical number systems. In this, the spaces are allowed and only the first number is passed. For example,

parseInt("20");  will return 20

36. normalize()

The normalize is a browser-based Javascript method. It merges neighboring text nodes into a separate text node and eliminates void text nodes. It has a return value and in the Internet Explorer, this method does not remove empty text nodes.

This method is also used to obtain the Unicode Normalization Form also called a code point of the string. It creates unique numerical value and is one of the most important members of the String family.

Syntax:
string.normalize()

Example:
var a = "Hello World";
b= a.normalize('NFC')

37. slice(start,end)

arr.slice() is a javascript function that returns a new array holding a part of the array on which it is executed. For example, the primary array remains constant. This function accepts two parameters and it is an inbuilt function in Javascript. The parameters are start index and end index.

This function only copies the array and creates a new one. It does not change the original array. The following example is displaying the use of slice function. It is only copying and creating a new array.

For example:
var myarr = [20,30,40,50,60,70];
var my_new_arr = arr.slice();
print(myarr);
print(my_new_arr);

Output:
[20,30,40,50,60,70]
[20,30,40,50,60,70]

38. Epsilon

EPSILON is one of the static properties of javascript that is applied to give the smallest positive number nearing zero (ie: a positive tiny number). EPSILON is a number object property and can be called through the Number object.

Syntax:
Number.EPSILON;

Example:
console.log(Number.EPSILON);
Output: 2.220446049250313e-16

39. toJSON()

The JSON is a JavaScript Object Notation. This function is a common setup to express conditions and objects. The JSON function can be used for data exchange when the client utilizes JavaScript and the server is based on Ruby/PHP. It gives two methods JSON.stringify and JSON.parse. The JSON.strigify is used to convert objects into JSON and the JSON.parse is used to convert JSON back into an object.

40. toISOString()

The toISOString() is a function of the date object in Javascript. This function gives the obvious extensive ISO format of the date. It is one of the most important functions of the data objects. To use this function it is necessary to create a Date object. After creating the data object, there are a number of methods that allow users to work on the created object. Most methods only enable users to retrieve various elements of the calendar such as the year, month, day, hour, minute, second, and millisecond. These factors can be obtained by using local time, UTC, or GMT.

Syntax:
dateObj.toISOString();

Example:
document.write("Current Date: "+dateObj.toISOString());

41. Proxy()

A Proxy object covers a single or many other objects and blocks methods, like writing properties. Proxies are utilized in many libraries and frameworks. A proxy is a unique object. It doesn’t hold its own properties. With a void handler, it just sends operations to the destination. Many proxy methods can be used as internal methods. For example, GET, SET, DELETE are some of the proxy’s internal methods that get triggers when respective events occur. The following is the example of a proxy to store user data.

const proxyUser = new Proxy(user, handler);

42. Promise

promise is a specific JavaScript object that combines the “building code” and the “utilizing code” collectively. In terms of the relationship: this is the “recommendation list”. The “building code” accepts whatever event it requires to deliver the promised outcome, and the “promise” makes that outcome accessible to all of the recommended code when it’s available. It is like fulfilling the promise. This is one of the most important javascript codes. It is used in many event-driven software applications. It is also used to handle asynchronous operations. Following is the example of Promise:

promise
then(function () {
console.log('Life is Beautiful');
})

43.Mixins

Mixin is a style in which attributes are appended to objects without utilizing inheritance. It gives an alternative method of designing the application that isn’t explicitly included in chapters on design models. Mixins are a kind of object creation, where element characteristics get merged into a composite object so that attributes of each mixin display characteristics of the composite object. The Javascript does not support multiple inheritances this is the reason why Mixin is used to add various properties to objects without using inheritance. Following example is showing the use of Mixin:

let myMixin = {
sayHello() {
console.log(`Hi ${this.name}`);

44. Autocorrection

The autocorrection is a really beneficial feature of Date objects. In this, users can configure a range of values, and it also auto-adjusts itself. For example, if you want to increase the date “28 August 2020” by 2 days. It is “30 August” then you just have to add 2 days. The Date object will execute it properly. This function is often applied to receive the date after the assigned period. For example,

let date = new Date(2020, 8, 28);
date.setDate(date.getDate() + 2);

45. unescape()

The unescape() function calculates a new string in which hexadecimal escape strings are substituted with the number that it describes. The escape series might be presented by a function like escape. Normally, decodeURI or decodeURIComponent are used instead of unescape. This function was introduced in Javascript version 1.5 and it is mostly used to decode the encoded string. The escape function is used to create a string portable to send it using a network and in return, users can use unscape() function to decode the original string. These functions are useful in preventing the Cross-Site Scripting (XSS) attack. This feature has been removed from the web standards but some browsers still support these functions. An example is given below:

unescape('xyz123');

Bonus query – NEGATIVE_INFINITY

The negative infinity in JavaScript is a fixed value that is applied to describe a value which is the most moderate. This indicates that no other figure is more inferior than this number. It can be made by applying a self-made procedure or by an arithmetic progression. For example,

var y = Number.NEGATIVE_INFINITY;

 

About the Author

ByteScout Team

ByteScout Team of Writers

ByteScout has a team of professional writers specialized in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.

prev
next