Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

The valueOf method in Javascript

Javascript’s valueOf method returns the primitive value of the object to which it is applied. The returned value is typically of type boolean, number, string, or symbol, depending on the object.

Let us write a simple Javascript program to apply this method on a string.

We will embed our Javascript code inside a HTML page like so:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>The valueOf method in Javascript</title>
</head>

<body>
  <script>
  </script>
</body>

</html>

In the above HTML page you see the basic elements of the page like the head element containing the title (“The ValueOf method in Javascript”) and a body with an empty script tag. The Javascript code goes inside these tags.

The valueOf method applied to strings

Let us consider applying the valueOf() method to strings.

<script>
  mystring = "Hello Kodeclik!"
  document.write(mystring)
  document.write('<BR>')
  document.write(mystring.valueOf())
</script>

The output is:

valueof Javascript

Hello Kodeclik!
Hello Kodeclik!

Note that both the write() methods print the same string because the valueOf() method essentially returns the string that it is applied to (it does not modify the string).

Let us create a String object and go through the same motions with the valueOf() method:

<script>
  mystring = new String("Hello Kodeclik!");
  document.write(mystring)
  document.write('<BR>')
  document.write(mystring.valueOf())
</script>

The output is (still):

Hello Kodeclik!
Hello Kodeclik!

So what is the big deal if valueOf() returns the same value as when the string is printed? valueOf() is a method that is also used internally by Javascript and you will typically not need to use it in your code. Whenever Javascript encounters a program that needs a primitive value (e.g., a string) but is instead given an object, it will internally use the valueOf() method to convert it.

One place where you might find it useful is that there are some Javascript functions that treat a string or string object literally, and not as its primitive value. In those cases, you can use valueOf() to obtain its primitive value.

Consider for instance the program:

<script>
  mystring = new String("4")
  mystringobject= new String("2+2")
  document.write(eval(mystring))
  document.write('<BR>')
  document.write(eval(mystringobject))
</script>

Here we are creating two String objects, one with value “4” and one with value “2+2”. When we try to evaluate them we get the output:

4
2+2

Note that eval is unable to evaluate the string object(s) that involve some arithmetic/computation. In these cases, we can use valueOf() before applying eval:

<script>
  mystring = new String("4")
  mystringobject= new String("2+2")
  document.write(eval(mystring))
  document.write('<BR>')
  document.write(eval(mystringobject.valueOf()))
</script>

The output is:

4
4

as desired. You can use this in a conditional now to compare objects:

<script>
  mystring = new String("4")
  mystringobject= new String("2+2")
  firsteval = eval(mystring)
  secondeval = eval(mystringobject.valueOf())
  if (firsteval == secondeval) {
    document.write("They are the same!")
  }
</script>

The output is:

They are the same!

as expected.

The valueOf method applied to integers

Let us apply the same method to an integer and see the results:

<script>
  myfavinteger = 2345;
  document.write(myfavinteger)
  document.write('<BR>')
  document.write(myfavinteger.valueOf())
</script>

The output is:

2345
2345

as expected, there are no surprises here.

The valueOf method applied to arrays

Let us apply the valueOf method to arrays.

<script>
  myarray = ['Spiderman','Superman','Batman']
  document.write(myarray)
  document.write('<BR>')
  document.write(myarray.valueOf())
</script>

The output is:

Spiderman,Superman,Batman
Spiderman,Superman,Batman

Note that, again, the valueOf() method when applied to an array returns the array (and does not modify the array in any way).

The valueOf method applied to dates

Let us apply the valueOf() method to a date, like so:

<script>
  mybirthday= new Date('February 3, 2010')
  document.write(mybirthday)
  document.write('<BR>')
  document.write(mybirthday.valueOf())
</script>

The output is:

Wed Feb 03 2010 00:00:00 GMT-0500 (Eastern Standard Time)
1265173200000

Wow - what happened? The first line reflects the date that we initialized the Date() constructor with, i.e., Feb 3, 2010. This line in addition prints a timezone and the day that this date falls on. But what does the second line mean? The second line refers to the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored. In other words, the primitive value of a date (i.e., the way dates are stored internally) is the number of milliseconds since this arbitrarily chosen date.

Does this mean that if we chose a date before 1970 the primitive value will be negative? Let us try it out! Let us pick a date before Jan 1, 1970 and redo this program:

<script>
  mybirthday= new Date('December 10, 1969')
  document.write(mybirthday)
  document.write('<BR>')
  document.write(mybirthday.valueOf())
</script>

The output is:

Wed Dec 10 1969 00:00:00 GMT-0500 (Eastern Standard Time)
-1882800000

Indeed, true enough, the primitive value is negative.

The valueOf method applied to boolean values

Let us try applying the valueOf method to boolean values:

​​<script>
  willitrain= true
  document.write(willitrain)
  document.write('<BR>')
  document.write(willitrain.valueOf())
</script>

The output is:

true
true

Let us try applying it to a newly created Boolean object:

<script>
  isitholiday = new Boolean(false)
  document.write(isitholiday)
  document.write('<BR>')
  document.write(isitholiday.valueOf())
</script>

The output is:

false
false

We have learnt in this blogpost that the valueOf method in Javascript returns the primitive value of a Javascript object. The main takeaway is that it is an internal method used by Javascript for a lot of its basic functioning.

If you liked learning about the valueOf() method, explore the Math.floor() method!

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.