Press key to advance. Zoom in/out: Ctrl or Command + +/-.

Basic JavaScript: IV

Estelle Weyl

Functions / Methods

String Methods

Substrings

var word = "etcetera";
var abbr = word.substring(0,3);
substring(startPos, endPos)

Replace content

var pinkFloyd = "Goodbye cruel world";
var terryJacks = pinkFloyd.replace('cruel world', 'to you my trusted friend');
replace(origSub, newSub); first occurence
var colors = "Grey, lightgrey, darkgrey, slateGrey";
var colours = colors.replace(/grey/gi, "gray");
g = global, i = case-insensitive

String Methods (cont.)

Searching

var willS="To be or not to be, that is the question."
var first = willS.indexOf('be'); // 3
var last =  willS.lastIndexOf('be'); //16
returns index of first letter found, or -1

Slice or section of text

var section = willS.slice(9, 18); // "not to be"

// returns "that is the question."
var section = willS.slice(20); 
var section = 
   willS.slice(willS.lastIndexOf(',') + 2);
slice(start, end) where end is not included.
    If end is omitted, will return from firstChar on.

Case Change

UPPERCASE/lowercase

var speak = prompt('Write Something:');
var shout = speak.toUpperCase();
var whisper = speak.toLowerCase();

Methods

We've already used these:

console.log(arg);
window.prompt(arg);
window.alert(arg);
string.replace(old, new);
string.substring(start, end);
string.toUpperCase();
string.toLowerCase();
parseInt(string, radix);
array.push(val);
array.unshift(val);
array.pop();
array.unshift();
array.splice();

String Methods

charAt
Returns the character at the specified index.
charCodeAt
Returns a number indicating the Unicode value of the character at the given index.
concat
Combines the text of two strings and returns a new string.
indexOf
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
match
Used to match a regular expression against a string.
replace
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search
Executes the search for a match between a regular expression and a specified string.
slice
Extracts a section of a string and returns a new string.
split
Splits a String object into an array of strings by separating the string into substrings.
substr
Returns the characters in a string beginning at the specified location through the specified number of characters.
substring
Returns the characters in a string between two indexes into the string.
toLocaleLowerCase / toLocaleUpperCase
The characters within a string are converted to lower / upper case while respecting the current locale. For most languages, this will return the same as toLowerCase / toUpperCase.
toLowerCase
Returns the calling string value converted to lower case.
toString
Returns a string representing the specified object. Overrides the Object.prototype.toString method.
toUpperCase
Returns the calling string value converted to uppercase.
valueOf
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf method.

While strings are primitive types, and primitive types don't have methods (objects do), strings are wrapped into a String Object wrapper when methods are invoked on them.

Functions

Function declaration

function alertName(first, last) {
    alert("Your name is " + first + " " + last);
}

Function Expression

alertName = function(){
    alert("Your name is " + first + " " + last);
}

Function call

alertName('Estelle', 'Weyl');

functions are objects that can execute a set of statements

Functions are reusable

Reusable code that does something!

Function

yummy = function(){
  for(var i = 0; i < arguments.length; i++){
	console.log("I love to eat " + arguments[i])
  }
}

Function calls

yummy("chocolate", 
      "ice cream", 
      "raspberries", 
      "pineapple");
yummy(prompt('name a yummy food'));

//declare variables

var val1, val2, total;
val1 = prompt('Enter a number'); 
val2 = prompt('Another number');

// the function

var multiplier = function (num1, num2){
    var value =  num1 * num2;
    console.log(num1 + " X " + num2 + " = " + value);
    return value; }

//call function and assign the return

total = multiplier(val1, val2);

// but what about scope??? local v global scope?

//console.log(num1 + " X " + num2 + " = " + value);
  console.log(val1 + " X " + val2 + " = " + total);
  

Variable Scope

Variables defined outside a function are global variables. They are accessible anywhere in your program once declared.

Variables declared with var inside a function are local to that function.

Variables defined in a function without being locally declared are global. Arguments are always local whether implicit or explicit.

Global v Local Scope

var vDays = 14; // global variable

var holiday= function(vDays) { // local scope
 var name = prompt('Name');
 console.log(name+"'s trip lasted "+vDays+" days");
}

// vDays = 7 here is a local variable to the function
holiday(7);
// see, vacationdays is still 14 days
console.log(vDays);
//console.log(name);

Methods are Functions

var functionName = function () {
  // do something
};
functionName();
window.functionName();
var answers = {
  color: window.prompt('Favorite Color'),
  tool: window.prompt('Analog Printer?'),
  count: window.prompt('Favorite Number?'),
  message: answers.count + ' ' + answers.color + ' ' + answers.tool + 's',
  annoy: function(){ 
      alert('You told us: ' + answers.message);
    }
};
answers.annoy();

Return Values

"return" is used inside a function to send back the return value when a function is called.

var squared = function(x){
	return x * x;
}

// the prompt method returns what was entered
var num = +prompt('Enter a number');

// the value written is the return value of function
console.log(num + " squared is " + squared(num));

Return rules

Functions with no explicit return will return undefined.

var squared = function(x){
	console.log( x * x)
}
var num = +prompt('Enter a number');
console.log(num + " squared is " + squared(num));

All functions have a return value. If no return is included, the function call returns undefined

When a function hits a return, it exits the function and goes back to the caller.

var ageLimit = function(age) {
  if(isNaN(age)) {
      return "Ummmm.... hello!";           }
  if(age >=65)   { 
      return "You're old enough to retire!";}
  if(age > 30)   {
      return "Aren't you 29 for the " + 
              (age-28) + "th time?";        }
  if(age >= 25)  {
      return "You can finally rent a car!"; }
  if(age < 18)   {
      return "You're too young to vote!";  }
  return "I'm speechless ...";
}

var message = ageLimit(+prompt("How old are you?"));
could have also used else/if

Exercises

  • Define a function that writes your name to the console.
  • Call that function
  • Change your function so it accepts a name as a parameter
  • Call that function

Putting it all together

  • Define a function that takes a first name and last name and write the initials to the console.
  • Create another function that asks the user for their first and last names.
  • Make the second function call the first function, passing the names.
  • Make it run by calling the 2nd function
  • Extra: make it so the first function only takes 1 value and returns only 1 initial. Call it 2x.

Next

Go