Lesson 56 Calculator Project – Length

You will come to find that finding the length of something is a useful tool in coding. We get to use a built-in term, called simply, length. The term string, you may remember, is just a collection of characters. Most often they are words, but they can contain any sort of letters, symbols, numbers, and spaces. We can use “length” to find the length of a string, how many characters are in it, but in our calendar, we don’t have a string; we have a number.

I want to know the length of our answer. I want to set “click” to how many digits are in the answer. That will give us an accurate count of what’s on the screen so that we don’t run over the edge. When the user typed in the numbers, it was a string. Then we used parseInt to turn it into an integer, into a number so that we could do math with it. Now, we need a string to figure out its length. So, the first step is to make it into a string. Then we can use “length.” Click will then equal the number of digits in our answer.

Javascript has built-in functions for both of those things. We use toString() to turn something into a string. We use “length” to find the length of something. We tell it which to do and which variable to do it to by using what’s called dot notation.

answer.toString();

answerLength.length;

The function toString is being applied to our variable named answer. We put them together using a period between them. The function length is being applied to the variable answerLength. We know that toString is a function because of the parentheses. Length doesn’t have parenthesis. We write answerLength.length. That gives us the property of length for the variable answerLength.

var answerLength = answer.toString();

Takes the number saved as answer and turns it into a string.

                click = answerLength.length;

Finds how many characters are in the answer and assigns it to the variable click.

You can watch this lesson on YouTube.