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();

Functions

Reusable code that does something!

function functionName(param1, param2) {
    // javascript you want to run
}
   // function call
  alertName('Estelle', 'Weyl');

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

Functions

Reusable code that does something!

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

//call function and assign the return
total = multiplier(val1, val2);

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

// 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.

function kiss(){
  for(var i = 0; i < arguments.length; i++){
	console.log("I want to kiss " + arguments[i])
  }
}
kiss("Bill", "Barack", "Johnny", "Angelina");

Global Scope

var vacationDays = 14;
// vacationDays = global variable
var holiday= function(vacationDays) {
    var name = prompt('Name');
    console.log(name + "'s trip lasted " + vacationDays + " days")
}

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

Functions are methods

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));

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