A JavaScript Symbol is a primitive data type, similar to Number, String, or Boolean.
It represents a unique, “hidden” identifier that cannot be accidentally accessed by other code.
For example, if multiple developers want to add a person.id property to a person object in third-party code, their values might conflict. Using Symbol() to create unique identifiers resolves this issue.
const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; let id = Symbol(‘id’); person[id] = 140353; // Now person[id] = 140353 // but person.id is still undefined |
Note: Even if you create two symbols with the same description, they will have distinct values.
|
ES6 allows you to assign default values to function parameters.
function myFunction(x, y = 10) { // y is 10 if not passed or undefined return x + y; } myFunction(5); // will return 15 |
The rest parameter (…) allows a function to collect an indefinite number of arguments into an array.
function sum(...args) { let sum = 0; for (let arg of args) sum += arg; return sum; } let x = sum(4, 9, 16, 25, 29, 100, 66, 77); |
The includes() method returns true if a string contains a specified value, and false otherwise.
let text = “Hello world, welcome to the universe.”; text.includes(“world”) // Returns true |
The startsWith() method returns true if a string starts with a specified value, and false otherwise.
let text = “Hello world, welcome to the universe.”; text.startsWith(“Hello”) // Returns true |
The endsWith() method returns true if a string ends with a specified value, and false otherwise.
var text = “John Doe”; text.endsWith(“Doe”) // Returns true |
Create an Array Iterator and iterate over the key/value pairs using it.
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; const f = fruits.entries(); for (let x of f) { document.getElementById(“demo”).innerHTML += x; } |
The entries() method returns an Array Iterator object containing key/value pairs:
The entries() method does not modify the original array.
The Array.from() method creates an Array object from any object that has a length property or from any iterable object.
Convert a string into an array:
Array.from(“ABCDEFG”) // Returns [A,B,C,D,E,F,G] |
The keys() method returns an Array Iterator object containing the keys (indexes) of an array.
Create an Array Iterator object that contains the keys (indexes) of the array.
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; const keys = fruits.keys(); let text = “”; for (let x of keys) { text += x + “<br>”; } |
The find() method returns the value of the first array element that satisfies a given test function.
In this example, it returns the first element that is greater than 18.
const numbers = [4, 9, 16, 25, 29]; let first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; } |
Note that the function accepts three arguments: