Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Numbers Parsing Numbers From Strings

Owen O
Owen O
3,737 Points

Difference between var.method() and method(var)?

Wondering why something like var numWidth = boxWidth.parseInt(); doesn't work compared to the accepted var numWidth = parseInt(boxWidth)?

It seems like one could evaluate var numWidth = boxWidth.toUpperCase(), but not the previous example.

Any good explanations?

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JavaScript Foundations: Parsing Numbers From Strings</title>
    <link rel="stylesheet" href="core.css">
    <script>
      var boxWidth = "640px";
      var boxHeight = "480px";
      var numWidth = boxWidth.parseInt();
      var numWidth = parseInt(boxWidth);

    </script>
  </head>
  <body>
    <h1>JavaScript Foundations</h1>
    <h2>Parsing Numbers From Strings</h2>
    <script src="viewer.js"></script>
  </body>
</html>

1 Answer

Sean T. Unwin
Sean T. Unwin
28,690 Points

When a method uses a dot operator (boxWidth.parseInt();, in your example), it means it is part of an Object prototype. i.e. an Object was created that has one or more various methods which do something relating to that Object. This is evident in the commonly used Array methods, such as Array.push()) - you create an Array and use the push() method to add one item to your Array.

Some methods are stand-alone functions, such as parseInt(). This is a global function, meaning it is packaged with JavaScript. These types of methods are still specific (they do a task), but don't really fit in with an Object type.

toUpperCase is a method on a String Object so if boxWidth is NOT a String (e.g. a Number) then an error will occur.