Skip to content

Instantly share code, notes, and snippets.

@ninabreznik
Last active May 4, 2016 18:30
Show Gist options
  • Save ninabreznik/7e90000011c8b29b63a2 to your computer and use it in GitHub Desktop.
Save ninabreznik/7e90000011c8b29b63a2 to your computer and use it in GitHub Desktop.
if-else
###########################
# IF / ELSE / ELSE IF #
###########################
You can make a block of code execute when a conditional expression is true using an if statement.
The conditional expression is the expression surrounded by parenethesis following the word IF.
#IF
var x = 11;
if (x < 10) {
console.log("True");
}
You can put an else statement after an if statement to tell the computer what to do if the if conditional expression wasn't true.
#ELSE
var x = 11;
if (x < 10) {
console.log("True");
}
else {
console.log("False");
}
Use else if to chain together fall-through cases - if first condition is not true, then check the new condition and execute first one that is true.
#ELSE IF
var x = 22;
if (x > 10) {
console.log("x > 10");
}
else if (x === 22) {
console.log("x === 22");
}
else {
console.log("None of the above");
}
#NESTING CONDITIONALS
var flag = {color: "violet", position: {x: 30, y: 23 }};
var enemy = "Brak";
if (flag) {
console.log("Build fire-trap");
}
else {
if (enemy) {
console.log("Attack");
}
else {
console.log('Do nothing');
}
}
###########################
# INDENTATION #
###########################
4 spaces
if (true) {
if (true) {
if (true) {
// ...
}
}
}
2 spaces
if (true) {
if (true) {
if (true) {
// ...
}
}
}
RULES OF INDENTATION
1. However you choose to indent, be consistent!
2. Your code will be much easier for others and yourself to read.
3. Remember to line up closing braces at the same level as opening statements!
###########################
# RELATIONAL OPERATORS #
###########################
&& ........... and
|| ........... or
! ........... not
var x = 5;
var y = 10;
if (x < 10) {
console.log("True")
}
if (x < 10 && y > 20 ) {
console.log("True")
}
if (x < 10 || y < 20 ) {
console.log("True")
}
if (y != 20 ) {
console.log("True")
}
###########################
# OBJECTS #
###########################
# OBJECT FLAG
key value
----------------------|---------
color | green
pos | x:67, y:102
# SAVING OBJECT INTO VARIABLE FLAG
var flag = {
color: "green",
pos : {
x: 67,
y: 102
}
}
var flag = { color: "green", pos: {x:67, y:102}}
console.log(flag)
# PICKING OUT A SINGE ATTRIBUTE (or A FIELD)
console.log(flag.color)
console.log(flag.pos)
console.log(flag.pos.x)
console.log(flag.pos.y)
# CREATING NEW ATTRIBUTES
flag.distance = 55
console.log(flag.distance)
console.log(flag)
# UPDATING ATTRIBUTES
flag.color = "violet"
console.log(flag.color)
console.log(flag)
# DELETING ATTRIBUTES
delete flag.distance;
console.log(flag.distance);
console.log(flag);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment