JavaScript Review

Question 1

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

let grade = calculateLetterGrade(96);
submitFinalGrade(grade);
The first one returns a value because it is being assigned to a variable.
Question 2

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

A global variable is declared outside of a function and can be referenced anywhere in the program. A local variable is declared inside a function and can only be referenced inside of that function.
Question 3

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

const stateTaxRate = 0.06;
const federalTaxRate = 0.11;

function calculateTaxes(wages){
	const totalStateTaxes = wages * stateTaxRate;
	const totalFederalTaxes = wages * federalTaxRate;
	const totalTaxes = totalStateTaxes + totalFederalTaxes;
	return totalTaxes;
}
stateTaxRate and federalTaxRate are global because they aren't in a function. totalStateTaxes, totalFederalTaxes, and totalTaxes are local because they are declared inside the function.
Question 4

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

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

alert("The sum is " + sum);
addTwoNumbers(3,7);
It won't work because the variable sum is a local variable and can't be used outside of the function.
Question 5

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

True, unless you use another function like parseInt.
Question 6

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

parseInt. An input by default is a string, so parseInt will make it an integer (number).
Question 7

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

parseFloat. This will convert a string to a number with a decimal.
Question 8

What is the problem with this code sample:

let firstName = prompt("Enter your first name");
if(firstName = "Bob"){
	alert("Hello Bob! That's a common first name!");
}
In the if statement, the operator should be == instead of =. One equals sign is trying to assign "Bob" to the firstName variable, but two will compare the values.
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)?

let x = 7;
x--;
x += 3;
x++;
x *= 2;
console.log(x);
20
Question 10

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

Stepping into a line of code will go into the function (if there is one) one line at a time. Stepping over a line of code will execute it and move to the next line.

Coding Problems

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