Back to Web Programming 1

JavaScript Review

Question 1

There are two functions being called in the code sample below. Which one returns a value? How can you tell?

var grade = calculateLetterGrade(96);
submitFinalGrade(grade);
calculateLetterGrade(96) returns a value. Because the function calculateLetterGrade can be called and gives a value.
Question 2

Explain the difference between a local variable and a global variable.

A local variable is one that can only be used within the function that it is created in. A global variable can be used anywhere in the program.
Question 3

Which variables in the code sample below are local, and which ones are global?

var stateTaxRate = 0.06;
var federalTaxRate = 0.11;

function calculateTaxes(wages){
	var totalStateTaxes = wages * stateTaxRate;
	var totalFederalTaxes = wages * federalTaxRate;
	var totalTaxes = totalStateTaxes + totalFederalTaxes;
	return totalTaxes;
}
stateTaxRate & federalTaxRate are global, while wages is local
Question 4

What is the problem with this code (hint: this program will crash, explain why):

function addTwoNumbers(num1, num2){
	var sum = num1 + num2;
	alert(sum);
}

alert("The sum is " + sum);
addTwoNumbers(3,7);
Because sum is not defined, adding a (let sum = value) will fix it either outside of or within the function.
Question 5

True or false - All user input defaults to being a string, even if the user enters a number.

True, that's why the programmer has to implement a parseInt or parseFloat in order to turn it into a number value.
Question 6

What function would you use to convert a string to an integer number?

parseInt
Question 7

What function would you use to convert a string to a number that has a decimal in it (a 'float')?

parseFloat
Question 8

What is the problem with this code sample:

var firstName = prompt("Enter your first name");
if(firstName = "Bob"){
	alert("Hello, Bob! That's a common first name!");
}
in the if(firstName = "Bob") the = should be ==
Question 9

What will the value of x be after the following code executes (in other words, what will appear in the log when the last line executes)?

var x = 7;
x--;
x += 3;
x++;
x *= 2;
console.log(x);
20 is what appears in the log, (7-1+3+1)*2=20
Question 10

Explain the difference between stepping over and stepping into a line of code when using the debugger.

When stepping over a line of code it jumps to the next sibling, when stepping into a line of code it jumps into the line that you're on and shows the processes of it. Example: if you "step into" a call function it'll show you the processes of the called function.

Coding Problems

Coding Problems - See the 'script' tag at the bottom of the page. You will have to write some JavaScript code in it.