Built-in Functions in JavaScript

Built-in Functions in JavaScript

This article explains the built-in functions in JavaScript.

YouTube Video

Built-in Functions in JavaScript

JavaScript provides a variety of built-in functions, which are powerful tools for efficiently creating programs. Here, we will explain in detail about the typical built-in functions in JavaScript.

What Are Built-in Functions?

Built-in Functions are functions that are provided as standard in JavaScript. These functions are designed to execute specific tasks concisely. Programmers do not have to implement them independently, which improves the readability and maintainability of the code.

Representative Built-in Functions

parseInt()

1// Convert string to integer
2console.log(parseInt("42"));      // Output: 42
3console.log(parseInt("42px"));    // Output: 42
4console.log(parseInt("0xF", 16)); // Output: 15
5console.log(parseInt("0xF"));     // Output: 15
6console.log(parseInt("px42"));    // Output: NaN
  • parseInt() is a function that parses a string and converts it to an integer. If the beginning of the string contains a number, that part is returned as an integer. An optional radix (base) can also be specified.

  • If the beginning of the string does not contain a number, it returns NaN (Not-a-Number). Also, if a radix is not specified, it defaults to decimal, but if the string starts with "0x", it is interpreted as hexadecimal.

parseFloat()

1// Convert string to float
2console.log(parseFloat("3.14"));      // Output: 3.14
3console.log(parseFloat("3.14abc"));   // Output: 3.14
4console.log(parseFloat("42"));        // Output: 42
  • parseFloat() parses a string and converts it to a floating-point number. It is used when dealing with numbers that include a decimal point.

  • Like parseInt(), if the beginning of the string is not a number, it returns NaN. It is characterized by correctly parsing not only the integer part but also the decimal part.

isNaN()

1console.log(isNaN(NaN));         // Output: true
2console.log(isNaN(42));          // Output: false
3console.log(isNaN("hello"));     // Output: true
  • isNaN() determines whether a given value is NaN. NaN (Not-a-Number) represents an invalid value as a number.

  • isNaN() is also valid for data types other than numbers, and for example, returns true if a string cannot be converted to a number.

Number()

1console.log(Number("42"));        // Output: 42
2console.log(Number("3.14"));      // Output: 3.14
3console.log(Number("0xff"));      // Output: 255
4console.log(Number("abc"));       // Output: NaN
5
6console.log(parseFloat("3.14abc"));  // Output: 3.14
7console.log(Number("3.14abc"));      // Output: NaN
  • Number() is a function that converts strings or other data types into a number. It returns NaN if a non-numeric string is given.

  • Unlike parseInt() or parseFloat(), Number() considers it an invalid conversion and returns NaN if the string contains non-numeric characters.

String()

1console.log(String(42));           // Output: "42"
2console.log(String(3.14));         // Output: "3.14"
3console.log(String(true));         // Output: "true"
4console.log(String(null));         // Output: "null"
5console.log(String(undefined));    // Output: "undefined"
  • String() is a function that converts numbers and other data types into strings. String(42) returns the string "42".
  • If the value to be converted is null or undefined, it returns the strings "null" or "undefined", respectively.
  • It is useful for handling various data types, such as numbers, booleans, or objects, by converting them into strings.

Array

1const arr = Array(3);
2console.log(arr); // Output: [ <3 empty items> ]
3
4const arr2 = Array(1, 2, 3);
5console.log(arr2); // Output: [1, 2, 3]
  • Array is a constructor used to create new arrays.
  • If there is one argument, it is treated as the length of the array, and an empty array is created.
  • If there are multiple arguments, an array with those values as its elements is created.

Array.isArray()

1console.log(Array.isArray([1, 2, 3])); // Output: true
2console.log(Array.isArray("not an array")); // Output: false
  • Array.isArray() is a method that determines whether the argument is an array.
  • It returns true if the argument is an array, and false otherwise.

isFinite()

1console.log(isFinite(42));         // Output: true
2console.log(isFinite(Infinity));   // Output: false
3console.log(isFinite(NaN));        // Output: false
  • isFinite() determines whether a given value is finite. Returns true for finite numbers, and false otherwise (such as for infinity or NaN).

  • In JavaScript, Infinity and -Infinity represent infinity and are of the number type, but isFinite() considers infinity as an invalid value.

eval()

1let expression = "2 + 2";
2console.log(eval(expression));    // Output: 4
3
4console.log(eval("var x = 10; x * 2"));  // Output: 20
  • eval() is a function that evaluates and executes JavaScript code given as a string. You can execute JavaScript code dynamically.

  • eval() is very powerful, but it poses a security risk, so it should be avoided in actual development. Executing externally provided code with eval() can lead to unintended behavior and security vulnerabilities.

encodeURI() / decodeURI()

1let url = "https://example.com/?name=John Doe&age=25";
2let encodedUrl = encodeURI(url);
3console.log(encodedUrl);
4// Output: https://example.com/?name=John%20Doe&age=25
5
6let decodedUrl = decodeURI(encodedUrl);
7console.log(decodedUrl);
8// Output: https://example.com/?name=John Doe&age=25
  • encodeURI() is a function used to encode (convert) characters that cannot be used in a URL. On the other hand, decodeURI() decodes an encoded URL to its original form.

  • Encoding is particularly important when dealing with special characters. For example, characters like spaces or & need to be encoded to be correctly included in a URL, so they must be appropriately processed using encodeURI().

setTimeout() / setInterval()

 1// Execute a function after 2 seconds
 2setTimeout(() => {
 3    console.log("This runs after 2 seconds");
 4}, 2000);
 5
 6// Execute a function every 1 second
 7let intervalId = setInterval(() => {
 8    console.log("This runs every 1 second");
 9}, 1000);
10
11// Stop the interval after 5 seconds
12setTimeout(() => {
13    clearInterval(intervalId);
14}, 5000);
  • setTimeout() is a timer function used to execute a function once after a specified time. setInterval() repeatedly executes a function at specified intervals.

  • setTimeout() and setInterval() execute asynchronously, calling the function after the specified time elapses. It's also possible to cancel executions using clearTimeout() or clearInterval().

Summary

Utilizing JavaScript's built-in functions allows you to write simpler and more efficient programs. The functions introduced here are basic and useful in various situations.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video