Exercise 10.2
This is Exercise 10.2, lecture on Javascript basics, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.
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):
-
hello(firstname, lastname)
: returns a string"Hello, firstname lastname"
. - Make a test - call (invoke) that function with parameters firstname:"John", lastname:"Doe". Print the result to the console.
-
Make another test call: print the result of
hello("Chuck")
to the console. -
Set a default value for the
lastname
parameter to "Norris" inside thehello
function. -
Create another function
includes(s, search)
: return true, if strings
includes substringsearch
, false otherwise. For example, all of these would return true:includes("Chuck", "u")
includes("Chuck", "C")
includes("Chuck", "uck")
includes("Chuck", "a")
includes("Chuck", "Chuckie")
includes("Chuck", "chu")
includes("Chuck", "Buck")
includes("Chuck", "Mercy")
- In general, you should write some tests for every function you create. Otherwise - how do you know if it is correct?
-
countA(s)
: returns the number of times letter "a" appears in the string s. -
Write some tests for
countA
function - print the results to console. Check the console to make sure the function works correctly. -
countChars(s, c)
: returns the number of times the character c appears in string s. -
Refactor the
countA(s)
function to re-use thecountChars()
function (in case you did not do that right from the beginning). -
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.