//keywords and reserved words
(don’t use them for variable names)
break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield
//basic function structure
var square = function(x)
{ return x * x; };
console.log(square(12));
//conditional Logic Flow
Booleans & Comparators
(Type the following into your console, can you guess what will be returned?)
- > !true
- > !false
- > !!false
- > !!true
- > !!"type coercion"
- > !!"all strings are 'truthy' except for..."
- > !!""
- > true && true
- > true && false
- > false && true
- > false && false
- > true || true
- > true || false
- > false || true
- > false || false
- > true && "what does this evalute to?"
- > false && "and this?"
- > true || "sigh, i'm not needed"
- > false || "default value"
//write a while loop that counts from 0 to 50 by twos
var n = 0
console.log("I am called the Count... because I really love to count!")
while (n <= 50) {
console.log(n)
n += 2
}
console.log('fin!')
//count from 1 to 10, with a comma after each integer
var n = 0
while (n <= 10) {
if (n < 10){
console.log(n+",")
} else {
console.log(n)
}
n++
}
//iterate over property/properties in object, the for in loop
for (var i in car) {
if (i === "color") {
console.log(car.color)
$("#favorite_car_colors").append(car.color)
}
}
//iterate over key in object, the for in loop
for (var key in obj) {
var value = obj[key]
if (value === "down") {
console.log(key)
$("#direction_headed").append(key)
}
}
//use for in to iterate/loop over and find the value of a property in an object
for (var i in obj) {
if (i === target_key) {
console.log(obj[i])
$('#direction_headed').append(obj[i])
}
}
//take values from array and place them into object using for loop
var numbers = [2, 4, 5, 37, 0]
var doubled_numbers = {}
for (var i = 0; i < numbers.length; i++) {
key = numbers[i]
value = numbers[i] * 2
doubled_numbers[key] = value
$("#doubles").append("
" + key + " doubled is " + value + "
")
}
//find even numbers of an array
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
b = [];
for (var i = 0; i < a.length; ++i) {
if ((a[i] % 2) === 0) {
b.push(a[i]);
}
}
//create object using bracket notation
var gradebook = new Object()
//get average of an array, an array that is part of a nested object within a property of an Object
gradebook.getAverage = function(name){
return average(gradebook[name].testScores);
}
var average = function(scores){
var total = 0
for (var i in scores)
total += scores[i];
return total / scores.length
}