Variables Flashcards
var bgColor = "blue"; var textColor = "#FF9933";
var container = document.getElementById(‘container’);
container. style.background = bgColor;
container. style.color = textColor;
Formula:
document.getElementById(“selector”).style.background
- assigning bgColor to the value of “blue” and the textColor to “#FF9933”
- getting the element by the id of “container”
- object.property
- variable built into webpage.method.object.property
What characters are invalid in a variable name?
%, @, -, cannot start with a #
undefined vs. null
undefined == null
undefined === null
- undefined works as a keyword/variable
- null works as an empty value
- undefined == null —> true
- undefined === null —> false
What will console log out in the following code?
var part1 = “Team “;
function bam() { var part2 = "Treehouse"; console.log(part2); }
bam();
Treehouse
What will console log out in the following code?
var part1 = “Team “;
function bam() { var part2 = "Treehouse"; console.log(part1); }
bam();
Team
What will console log out in the following code?
var part1 = “Team “;
function bam() { var part2 = "Treehouse"; }
bam();
console.log(part1);
Team
What will console log out in the following code?
var part1 = “Team “;
function bam() { var part2 = "Treehouse"; function boom() { var part3 = "Go "; console.log(part3 + part1 + part2); }
boom(); }
bam();
Go Team Treehouse
What will console log out in the following code?
var part1 = “Team “;
function bam() { var part2 = "Treehouse"; }
bam();
console.log(part2);
ReferenceError: part2 is not defined
Scope
variables can only be used within its respective curly braces
Shadowing
- idea applies to variables with the same name
- if no “var” is declared, then it becomes a global variable
What will console log out in the following code?
var person = “Jim”;
function whosGotTheFunc() { var person = "Andrew"; }
person = “Nick”;
whosGotTheFunc();
console.log(person);
Nick
What will console log out in the following code?
var person = “Jim”;
function whosGotTheFunc() { person = "Andrew"; }
person = “Nick”;
whosGotTheFunc();
console.log(person);
Andrew
function elevatorCloseButton(pushed) { if (pushed) { var status = "I'll close when I'm ready."; } }
elevatorCloseButton(true);
Alter the ‘elevatorCloseButton’ function to follow the best practices in declaring variables within the scope of the function.
function elevatorCloseButton(pushed) { var status; if (pushed) { status = "I'll close when I'm ready."; } }
elevatorCloseButton(true);
What does it mean to shadow a variable?
creating a new variable that has the same name as a variable from a higher scope
What is the correct syntax for creating a variable in JavaScript?
var myVariable = “some value”;