Lessons 112 to 113 – Complete 2020 Web Development Bootcamp

Lesson 112 – Creating and Calling Functions

Functions allow you to create a series of instructions, package them into a block of code which will be executed when you call the function. This is what a function looks like:

function getName() {

}

The keyword is “function” which is what tells Javascript that you are creating a function. You give the function a name which in this case is “getName”. The code which the function will run is placed within the curly braces. The end curly brace is not followed by a semi-colon.

Once you have created the function, you call it by using the function name and brackets. The function will then run the code inside the curly braces of the function. For example, you call the “getName” function using this language –

getName();

Functions help you to save time because it reduces the amount of code you have to write and they keep your code DRY.

All of the rules that apply to naming variables also apply to naming functions. You can review the naming rules here.

Lesson 113 – Functions Part 1 Challenge – The Karel Robot

The challenge is to write a function that moves the Karel Robot all the way to the top right corner of the screen on a 5 x 5 world.

The webpage that has the Karel Robot is here.

This is my solution:

function main(){
   //your code here
   goToCorner();
}

function goToCorner() {
   move();
   move();
   move();
   move();
   turnLeft();
   move();
   move();
   move();
   move();
   }

The next challenge is to have Karel put down a diagonal line of beepers from the bottom left hand corner to the top right hand corner.

This is my solution:

function main(){
   //your code here
   placeFirstBeeper();
   
   placeSecondBeeper();
  
   placeSecondBeeper();
   
   placeSecondBeeper();
}

function placeFirstBeeper() {
   putBeeper();
   move();
   turnLeft();
   move();
   putBeeper();
}

function placeSecondBeeper() {
   turnLeft();
   turnLeft();
   turnLeft();
   move();
   turnLeft();
   move();
   putBeeper();
}

The third challenge is to use Karel to create a chess board pattern.

This is my solution –

/**
 * Welcome to the Stanford Karel IDE.
 * This is a free space for you to 
 * write any Karel program you want.
 **/
function main(){
   //your code here
   putBeeper();
   
   movePutBeeper();
   
   movePutBeeper();
   
   turnLeftMovePut();
   
   movePutBeeper();
   
   moveTurnRightPut();
   
   turnRight();
   
   movePutBeeper();
   
   movePutBeeper();
   
   turnLeftMovePut();
   
   movePutBeeper();
   
   moveTurnRightPut();
   
   turnRight();
   
   movePutBeeper();
   
   movePutBeeper();
}

function movePutBeeper() {
   move();
   move();
   putBeeper();
}

function turnLeftMovePut() {
   turnLeft();
   move();
   turnLeft();
   move();
   putBeeper();
}

function moveTurnRightPut() {
   move();
   turnRight();
   move();
   putBeeper();
}