Tuesday, May 4, 2021

Javascript Practice 21: JS Hero - String: charAt()

 
Question: 
 
Write a function shortcut that takes two strings and returns the initial letters of theses strings.

Example: shortcut('Amnesty', 'International') should return 'AI'.
 
 
 
 
Answer: 
 
function shortcut (str1, str2) {

return str1.charAt(0)+str2.charAt(0);

};
 
or 
 
function shortcut (str1, str2) {

return str1[0] + str2[0];

};
 
or 
 
function shortcut (str1, str2) {

return str1.charAt()+str2.charAt();

}; 
 

> all answers will work and will return the same output for the above question
> the first example uses the charAt method which returns a new string that consists of the first character of the index which is 0. 
> characters in a string are indexed from left to right
> index of the first character is 0
> 0 is enclosed in round brackets
> the second example does not use the charAt method 
> in the second example, we treat the string like an array object 
> individual characters in an array correspond to a numerical index
> in this case we use 0 enclosed in square brackets 
> the third example is similar to the first one
> the only difference is that we do not provide any index number like 0,1 or 2 etc
> if no index number is provided to charAt method then the default value is 0. 
> function name is shortcut
> it is a function expression
> 2 parameters: str1 & str2
> in all three examples we concatenate the parameters using the '+' sign


 

No comments:

Post a Comment