Open In App

JavaScript Symbol valueOf() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The symbol.valueOf() is an inbuilt method in JavaScript which is used to return the primitive value of a given symbol object. Syntax:

Symbol().valueOf();

Here Symbol() is the symbol object whose primitive value is to be found. Parameters: This method does not take any parameter. Return value: This method returns the primitive value of the given symbol object. JavaScript code to show the working of this method.

Example-1: 

javascript




// Some symbol objects are created
const symbol1 = Symbol('Geeks');
const symbol2 = Symbol("Geeks");
const symbol3 = Symbol(123);
const symbol4 = Symbol();
 
// Calling the symbol.valueOf() method
let result1 = symbol1.valueOf();
let result2 = symbol2.valueOf();
let result3 = symbol3.valueOf();
let result4 = symbol4.valueOf();
 
// Getting the primitive value
console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);


Output:

> Symbol(Geeks)
> Symbol(Geeks)
> Symbol(123)
> Symbol()

Example-2: 

javascript




// Some symbol objects are created
const symbol1 = Symbol('Geeks' + 'for' + 'Geeks');
const symbol2 = Symbol(2 + 3);
const symbol3 = Symbol(10 / 5);
const symbol4 = Symbol(1, 2, 3);
 
// Calling the symbol.valueOf() method
let result1 = symbol1.valueOf();
let result2 = symbol2.valueOf();
let result3 = symbol3.valueOf();
let result4 = symbol4.valueOf();
 
// Getting the primitive value
console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);


Output:

> Symbol(GeeksforGeeks)
> Symbol(5)
> Symbol(2)
> Symbol(1)

In the above code, it can be seen that the parameter of symbol object should be a single parameter otherwise it considers the first element as the parameter and remaining are discarded. If the parameter is an arithmetic operation then it considers them as the result of the operation as the parameter.

Supported Browser:

  • Chrome 38 and above
  • Edge 12 and above
  • Firefox 36 and above
  • Opera 25 and above
  • Safari 9 and above

Reference: https://devdocs.io/javascript/global_objects/symbol/valueof



Last Updated : 22 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads