w3resource

JavaScript: String function

Description

The String function is used to converts a specified object to a string. String is a top-level function and is not associated with any object.

Syntax

String(obj)

Parameters

obj: Required. An object.

Example of String function

The following web document converts the Date object to a string.

JavaScript Code:

var dt = new Date (4400346634522);
var str1 = String(dt);
console.log('4400346634522 converted to : '+str1);

View the example in the browser

Live demo:

See the Pen string-function-1 by w3resource (@w3resource) on CodePen.


Previous: JavaScript: Number function
Next: JavaScript: encodeURI() function



JavaScript: Tips of the Day

Returns all unique values of an array, based on a provided comparator function

Example:

const tips_uniqueElementsBy = (arr, fn) =>
  arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) acc.push(v);
    return acc;
  }, []);

console.log(tips_uniqueElementsBy(
  [
    { id: 0, value: 'p' },
    { id: 1, value: 'q' },
    { id: 2, value: 'r' },
    { id: 1, value: 's' },
    { id: 0, value: 't' }
  ],
  (a, b) => a.id == b.id
)); 

Output:

[[object Object] {
  id: 0,
  value: "p"
}, [object Object] {
  id: 1,
  value: "q"
}, [object Object] {
  id: 2,
  value: "r"
}]