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);
calculateLetterGrade returns a value because its result is stored in the grade variable, while submitFinalGrade is just called and not stored.
Question 2

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

A local variable can only be used inside the function or block where it is created, but 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?

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 variables, and wages, totalStateTaxes, totalFederalTaxes, and totalTaxes are local to the calculateTaxes 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);
The variable sum is only created inside the addTwoNumbers function, so using sum in the alert before the function call causes an error and the program crashes.
Question 5

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

True, user input from prompt starts out as a string even when the user types a number.
Question 6

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

You would use the parseInt function to convert a string to 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')?

You would use the parseFloat function to convert a string to a number with a decimal (a float).
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!");
}
The if statement uses = which assigns "Bob" to firstName instead of == or === to compare, so the condition is always true.
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);
The value of x will be 20 when the last line runs.
Question 10

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

Stepping over runs the line without going inside any function call, and stepping into goes inside the function so you can debug it line by 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.