Skip to content

Instantly share code, notes, and snippets.

View astout's full-sized avatar
๐Ÿ’š
Living Life

Alex Stout astout

๐Ÿ’š
Living Life
View GitHub Profile
@astout
astout / thinkful_js.md
Created October 7, 2018 19:38
Thinkful JS Response

JavaScript

Hi student,

Sure! This is actually a pretty common problem that everyone encounters at some point in web development. This is what is known as a "scope" issue. Scope is essentially the environment that is known to the software at a given time of execution. What is happening in your example, is that when your onclick function is executed, it's a different scope than the prizes and btnNum variables. By the time the onclick executes, prizes and btnNum are long gone. The onclick function doesn't "know" about these variables. These variables are out of the scope of the onclick function.

So to fix this, there are a few things you can do. I've written about a few of the other methods that could be used in some further reading, but for simplicity I only included the solution I would recommend here.

Set onclick Function on HTML elements

@astout
astout / thinkful_js_further_reading.md
Created October 7, 2018 19:36
Thinkful JS Further Reading

JavaScript (further reading)

Here are a few solutions for when the onclick function is trying to access out-of-scope data.

Function Returns A Function

This one is probably the most confusing, but functions that return functions is a common practice in JavaScript, so it's something you'll want to get familiar with. You can create a function that knows the full scope of what you need and returns a unique function that calls the alert with a given text.

function getPrizeFunction(prizeText) {
@astout
astout / fizzbuzz.js
Created January 10, 2018 17:02
FizzBuzz Interview Practice
function fizzbuzz(fizz = 3, buzz = 5, max = 100) {
for (let i = 0; i <= max; i += 1) {
if (i % fizz === 0 && i % buzz === 0) {
console.log('fizzbuzz');
} else if (i % fizz === 0) {
console.log('fizz');
} else if (i % buzz === 0) {
console.log('buzz');
} else {
console.log(i);