var x = “This is a string”;
var y = x.length // value is 16
console.log(y); // logs 16 to the console
Interestingly our variable y is now a number, the number 16. We have created a new variable of the type number, from our variable which is a string. Cool, right?
Congratulations, you have just seen your first property. These will play a big part in our understanding later on in this chapter, so feel free to sit with this concept for a bit to ensure you fully understand exactly what is happening here.
When you’re ready to move on, let’s take a look at our first method …
The search method is a very useful ‘helper’ that we can make use of for searching through a string to find a search term. It literally searches the string to find your result. Now you might have noticed that there are parentheses on the end of the word ‘search’ – a bit like the functions we saw earlier in this chapter. A method is still a property, just like the.length property we just looked at; however, a method is a property that contains a function, rather than a snippet of information.
When we declare a string variable, we assign it to a piece of text, then behind the scenes, JavaScript also assigns a set of properties and methods (remember, methods are actually properties themselves) to our string that we can use at will.
With this in mind, how do you think we might use the search method? Very similarly to our.length property, with a slight twist on things. Let’s see an example: