Exercise 10.2

This is Exercise 10.2, lecture on Javascript basics, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.

Go back to exercise list.

Purpose

The purpose of the exercise is get familiar with defining and calling functions in Javascript.

Instructions

Create a new HTML document, include a Javascript block there (choose whichever way you want - inline JS, or external file). Create the following functions (and test them by calling them):

  1. hello(firstname, lastname): returns a string "Hello, firstname lastname".
  2. Make a test - call (invoke) that function with parameters firstname:"John", lastname:"Doe". Print the result to the console.
  3. Make another test call: print the result of hello("Chuck") to the console.
  4. Set a default value for the lastname parameter to "Norris" inside the hello function.
  5. Create another function includes(s, search): return true, if string s includes substring search, false otherwise. For example, all of these would return true:
    • includes("Chuck", "u")
    • includes("Chuck", "C")
    • includes("Chuck", "uck")
    , while these would return false:
    • includes("Chuck", "a")
    • includes("Chuck", "Chuckie")
    • includes("Chuck", "chu")
    • includes("Chuck", "Buck")
    • includes("Chuck", "Mercy")
    You can use some built-in string methods. Find it on the web! Finding the right functions in documentation is an important skill.
  6. In general, you should write some tests for every function you create. Otherwise - how do you know if it is correct?
  7. countA(s): returns the number of times letter "a" appears in the string s.
  8. Write some tests for countA function - print the results to console. Check the console to make sure the function works correctly.
  9. countChars(s, c): returns the number of times the character c appears in string s.
  10. Refactor the countA(s) function to re-use the countChars() function (in case you did not do that right from the beginning).
  11. Bonus: create a function isEmail(s): returns true if s is a valid email address. Multiple options here, some of them involve using regular expressions.

Solution

You can find a solution here.