Javascript Basics Flashcards

1
Q

means to “commented out”

A

// on the line first line

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

the “.” is a “full stop” and the length give you the length of the word

A

“word”.length

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

This will make a pop up box that you have to click to continue

A

confirm(‘some sentence here’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

an input the the program needs to take an action

A

prompt(“What is your name?”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

strings are written with quotes

A

“what is your name?” or “42”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

booleans are used to compare numbers and strings

A

true or false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

this determines if this is string is greater than 10 characters and returns the result “true”

A

“I’m coding like a champ!”.length > 10;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

whatever is in the parentheses is “logged to the console” (sometimes called “printing out”), or displaying what the computer is thinking/doing

A

console.log(2 * 5)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

standard operators

A

> ,=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

equal to

A

===

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Not equal to

A

!==

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

If statement that if true, will “log the string in the console”

A

if ( “Brent”.length < 7 ) {
console.log(“Wonderfully True”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Modulo - When % is placed between two numbers, the computer will divide the first number by the second, and then return the remainder of that division.

A

%

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Substring - x is where you start chopping, and y is where you stop chopping each character is numbered starting at 0

A

“some word”.substring(x, y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

var varName = data;

A

once you “declare” a variable name, you can call up that value by declaring the variable nameusing a variable, you don’t put it in parenthesis because it will turn it into a string, rather than using the variable value (which can be a string or a number)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

this will ask the user for a response, and store the response as the value of the variable “age”

A

var age = prompt(“What is your age?”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Function structure

A
var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};
          divideByThree(12);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Parts of a function

A

the code between the { } is what is run every time the function is calledInputOutputCallThe code in the (parentheses) is parameterit’s a placeholder word that we give a specific value when we call the function. Parameters go in the parentheses. The computer will look out for it in the code block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

D.R.Y.

A

don’t repeat yourself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

return structure

A
var timesTwo = function(number) {
    return number * 2;
           }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

about return

A

return saves the number to the machine so that it can be used in other code, like this:

var newNumber = timesTwo(6) {
console.log(newNumber);
}

note you do not need to define a second variable to do some calculation and then return the variable, it all can be calculated with the return on one line
only valid inside functions!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

scope global

A

Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

scope local

A

Variables defined inside a function are local variables. They cannot be accessed outside of that function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Random number

A

Math.random()

If we declare a variable and make it equal to Math.random(), that variable will equal a number between 0 and 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

for loop structure

A
for (var counter = 1; counter < 11; counter++) {
     console.log(counter);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

about for loop

A
  • Every for loop makes use of a counting variable.
  • When the for loop executes the code in the code block—the bit between { }—it does so by starting off where i = 1.
  • the second part of the for loop tells the loop when to stop
  • see third section in for loop
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

3rd section in for loop

A
i++
     i + 1
i--
     i - 1
i += x
     i + x
i -= x
     i - x

In general, a += b; means “add b to a and put the result of that addition back into a. This is also available for the other basic arithmetic functions: -=, *=, and /= do what you expect.

var cashRegister = {
    total:0,
    add: function(itemCost){
        this.total += itemCost;
    }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

array structure

A
var arrayName = [data, data, data];
Any time you see data surrounded by [ ], it is an array.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

about array’s

A
  • store lists of data
  • store different types of data at the same time
  • ordered so each piece of data is fixed
  • The position of things in arrays is fixed. The position (or the index) of each bit of data is counted starting from 0, not 1.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

print the 4th element of the array “junk”

A

console.log(junkData[3]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

how to go through a “for” loop and stop the cycling through an array before there becomes an infinite loop

A
var cities = ["Melbourne", "Amman", "Helsinki", "NYC"];
for (var i = 0; i < cities.length; i++) {
    console.log("I would like to visit " + cities[i]);
the “i < cities.length” is referring to the number of data points there are in the  array (in this case four, or i=3 because we start off at i=0)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

how to add something to an array

A

.push()

.push() method that adds the thing between parentheses to the end of the array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

what do you use when you don’t know how long you want to do something?

A

a “while” loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Structure of a “while” loop

A
var understand = true;
while(  ){
     console.log("I'm learning while loops!");
     understand = false;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

additional features of the “while” loop

A
  • When you use a number in a condition, as we did earlier, JavaScript understands 1 to mean true and 0 to mean false.
  • When assigning a variable boolean value of true, you do not have to put “=== true” in the condition, only put the variable and the system will know it is true
  • Make sure to set an initial condition outside of the while loop or else it will continue resetting the initial condition every time
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

do/while loop

A

This loop says: “Hey! Do this thing one time, then check the condition to see if we should keep looping.” After that, it’s just like a normal while: the loop will continue so long as the condition being evaluated is true.

var loopCondition = false;

do {
console.log(“I’m gonna stop looping ‘cause my condition is “ + loopCondition + “!”);
} while (loopCondition);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Sets a variable to a random number that’s either 0 (false) or 1 (true)

A

Math.floor(Math.random() * 2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

a function that checks to see if “is not a number”

A

isNaN

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

to be used when you don’t want to use a bunch of “else if” statements

A

Switch statement

you have a series of “cases” that it will run through and then a default case if no scenarios match the cases given

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Switch statement structure

A

var lunch = prompt(“What do you want for lunch?”,”Type your lunch choice here”);

switch(lunch){
case ‘sandwich’:
console.log(“Sure thing! One sandwich, coming up.”);
break;
case ‘soup’:
console.log(“Got it! Tomato’s my favorite.”);
break;
default:
console.log(“Huh! I’m not sure what “ + lunch + “ is. How does a sandwich sound?”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Logical Operators

A

and(&&)
or (||)
not (!)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

and(&&)

A

“logical operator”

It evaluates to true when both expressions are true; if they’re not, it evaluates to false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

or (||)

A

“logical operator”

It evaluates to true when one or the other or both expressions are true; if they’re not, it evaluates to false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

not (!)

A

“logical operator”

It makes true expressions false, and vice-versa.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

make a prompt all upper case or lower case

A

prompt().toUpperCase() or prompt().toLowerCase()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

if statement structure

A
if (/* Some condition */) { 
// Do something 
} else if (/* Some other condition */) { 
// Do something else 
} else { 
// Otherwise // Do a third thing }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

multi-dimensional arrays

A

each array separated by a , makes a new row

48
Q

two-Dimensional (multi-dimensional) arrays

A

var twoDimensional = [[1, 1], [1, 1]];

49
Q

jagged arrays

A

may have different numbers of columns in each row

50
Q

object literal notation

A
var myObj = {
    type: 'fancy',
    disposition: 'sunny'
};

var emptyObj = {};

note that the key’s are implicitly assumed to be strings, so you can leave them off if wanted.

51
Q

object constructor

A

var myObj = new Object();

52
Q

object custom constructor format

A
function AnyObject(name, age){
     this.name = name;
     this.age = age;
     this.species = "Homo Sapiens";
}
NOTICE HOW THE CONSTRUCTORS FIRST LETTER OF THE NAME IS IN CAPS
53
Q

properties of an object

A

The key is “name” and “number”

The value is “Oxnard Montalvo” and “(555) 555-5555”;

54
Q

object dot notation

A

ObjectName.PropertyName (e.g., bob.name)

55
Q

object bracket notation

A

ObjectName[“PropertyName”]
- don’t forget the “” in the brackets unless you have created a var that is equal to the the name of the object property string

var someObj = {propName: someValue}; 
var myProperty = "propName"; 
someObj[myProperty];
56
Q

what is a method

A

method is just like a function associated with an object.

57
Q

why are methods helpful

A
  • usefull for Updating the object properties, and Calculating something based on an object’s properties.
  • Functions can only use parameters as an input, but methods can make calculations with object properties.
var rectangle = new Object();
rectangle.height = 3;
rectangle.setHeight = function (newHeight) {
  this.height = newHeight;
};
rectangle.setHeight(6);
58
Q

the keyword “this” in a method

A
var setAge = function (newAge) {
  this.age = newAge;
};
The keyword thisacts as a placeholder, and will refer to whichever object called that method when the method is actually used.
59
Q

Object constructor

A
var anObject = new Object()
the Object is a constructor (built into JavaScript to create an empty object).
60
Q

Array constructor

A

var family = new Array();

61
Q

for in loop (with a search function example)

A

var search = function (name) {
for(var key in friends) {
if(friends[key].firstname === name) {
console.log(friends[key]);
return friends[key];
- “friends[key].firstname === name” is how you would reference the key in the Object
- note that the “key” can really be any variable and the loop will assign that variable as the name of each of the object properties

62
Q

what is returned when comparisons are made? (>, <, !==)

A

boolean values (true or false)

63
Q

how can objects be put into arrays?

A

array[position] = object
To append something to the end of the array, you need to put it in the position one after the last item.

var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
64
Q

how to determine what type of thing something is

A

var someObject = {someProperty: someValue}; console.log( typeof someObject );

65
Q

lets you know if an object has a particular property

A

hasOwnProperty
console.log( myObj.hasOwnProperty(‘name’) );
will print true if the object has the property

66
Q

how to make a class and what a class is

A
  • Constructors can make objects, but you are also defining a new class
  • A class can be thought of as a type, or a category of objects—kind of like how Number and String are types in JavaScript.
67
Q

what defines what a class has or does not have

A

A prototype. it is basically what a constructor defines the new object to have initially. properties or methods can be added to an object, but they are not part of the prototype

68
Q

how to use a prototype

A

Dog.prototype.bark = function() {

console. log(“Woof”);
- This had now changed the prototype for the class Dog. This immediately teaches all current and future Dogs the new method.

className.prototype.newMethod = function() {
statements;
};

69
Q

Whenever this X is-a Y relationship exists, there’s a good chance that we should be using

A

inheritance

70
Q

how to set inheritance

A
To say that Penguin inherits from Animal, we need to set Penguin's prototype to be Animal.
Penguin.prototype = new Animal();
71
Q

prototype chain

A
  • By default, all classes inherit directly from Object, unless we change the class’s prototype, like we’ve been doing for Penguin and Emperor
  • The “prototype chain” in JavaScript knows this as well. If JavaScript encounters something it can’t find in the current class’s methods or properties, it looks up the prototype chain to see if it’s defined in a class that it inherits from. This keeps going upwards until it stops all the way at the top: the mighty Object.prototype
72
Q

properties of an object are automatically (public or private)

A

public

73
Q

how to create a private property or method of an object

A
use a var instead of "this"
function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
}
74
Q

how to show a private variable

A
function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;

this.getBalance = function() {
return bankBalance;
};
}

75
Q

how to display a private method

A
function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
   var returnBalance = function() {
      return bankBalance;
   };
   // create the new function here
  this.askTeller = function() {
      return returnBalance();
  };
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);
  • This means that it returns the method itself and NOT the result of calling that method. So you should NOT have parentheses after returnBalance.
  • when referring to a function within a function, use this.method, so that it refers to its own defined method
76
Q

using a function that has been defined outside of an object as an object method

A

you need to first set object.method (which is the function) = function

var setAge = function (newAge) {
  this.age = newAge;
};
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;

bob.setAge(50);

77
Q

creating a variable without current scope

A

The var keyword creates a new variable in the current scope. That means if var is used outside a function, that variable has a global scope. If var is used inside a function, that variable has a local scope.

78
Q

pointing to a specific letter in a string

A

You can use an array on a String
var myName = ‘Eric’;
myName[0]; // equals ‘E’

79
Q

how do you use a key or value from an object in the object’s method

A
var james = {
    job: "programmer",
    married: false,
    sayJob: function() {
        // complete this method
       console.log("Hi, I work as a " + this.job); 
    }
};

(make sure to reference the object.key or this.key or else the variable will be undefined)

80
Q

where should you put your functions in your script

A

it is good idea to put your functions at the top of the page

81
Q

what happens when you hit “return” in the code

A

the program will stop running immediately

82
Q

using global variables inside functions

A

try to avoid accessing or changing global variables within a function - it makes it more error prone and difficult to test

83
Q

How to remove the First Item from an array

A

.shift()

var items = ['Hat', 'Ball', 'Shoes'];
var firstItem = items.shift();
// firstItem now holds 'Hat'
// and items is now ['Ball', 'Shoes']

unshift()
it(“should push and pop”, function() {
var array = [1, 2];
array.push(3);

expect(array).toEqual([1, 2, 3]);

var poppedValue = array.pop();
expect(poppedValue).toBe(3);
expect(array).toEqual([1,2]);   });
84
Q

Remove the Last Item from an array with

A

.pop()

var items = ['Hat', 'Ball', 'Shoes'];
var lastItem = items.pop();
// lastItem now holds 'Shoes'
// and items is now ['Hat', 'Ball']
85
Q

add all the elements of an array into one string

A

.join() method

var daysInWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"}
var daysString = daysInWeek.join(",")

would return: Mon, Tue, Wed…

you can join the items in an array by anything

86
Q

add one array to another array

A
var firstArray = [1,2,3];
var secondArray = [a,b,c];

var bothArrays = firstArray.concat( secondArray);

console.log( bothArrays );

[1,2,3,a,b.c]

it doesn’t change any of the original arrays - but creates a new array and puts the values there

87
Q

index

A

look this one up

88
Q

document method that allows you to replace the content in an html <div></div>

A

in the html -

<div>
</div>

function print(message){
     var outPutDiv = document.getElementByID("output");
     outPutDiv.innerHTML = message
}
the document.getElementByID("output") is an object with reference to a particular part of the page (also called a "node")

the innerHTML is a DOM property, of which you set to what you want to display on in the tag “output”

89
Q

how to log multiple things to the console with one line of code

A

separate items by a comma:

console.log(“I want”, “ to “, “go to sleep);

90
Q

JavaScript Object Notation

A

JSON - sends a string of text that can be easily passed from server to client. The client will then automatically convert it to object format from the string

for more info:

http: //teamtreehouse.com/library/ajax-basics
http: //teamtreehouse.com/library/ajax-basics/programming-ajax/introducing-json

91
Q

represents the idea of nothingness, or non-existence

A

null

you will encounter null when someone or some system is trying to indicate that the item you are looking for definitely doesn’t exist

92
Q

represents an unknown or undetermined state

A

undefined

you will encounter undefined when someone or some system is trying to indicate that the item you are looking cannot be found for some reason. an example is when you try to access a value in an object for a key that doesn’t exist.

93
Q

an expression that ends in a semicolon allows the interpreter to proceed to the next line with a relatively clean slate

A

expression: console.log(3+2)
statement: console.log(3+2);
(this is known as an expression statement)

94
Q

variable declaration statement

A

introducing a new value by using the var keyword. Allows you to assign the initial value. Can be thought of some label or alias that points to some value

95
Q

variables can refer to values or other variables (T or F)

A
False.  while you can set a var oneVariable = otherVariable, you are not actually setting it equal to the otherVariable, just the value of the otherVariable
So if: 
var result = 5;
var otherResult = result;
result = 0;
console.log(otherResult);
---> 5!!!
96
Q

key are available to have only letters or number (T or F)

A

they are allowed to have slashes, spaces or dots

97
Q

difference between alpha and numeric keys on arrays

A

alpha properties don’t count towards the array.length and numeric properties do

98
Q

enumerable properties of an object or array

A

properties like length on an array that do not get iterated over during a for in loop for example

99
Q

what is the only difference between regular objects and functions?

A

functions have the magical ability to be invoked (which means to activate a whatever behavior the function is capable of

Also, functions can have properties just like objects

100
Q

what do you need to put on the function to run it?

A

two parenthesis for example: function();

101
Q

immediate invocation of a function

A
when you put a trailing () at the end of a definition, without anything in between.
example:
var two = function() {return 2;} ();
102
Q

arguments variable

A

a variable in the function that stores an array of the parameters passed into the function. it automatically holds a new array each time the function gets called and stores the values of the parameters

103
Q
limitations to the special objects: 
var obj = null;
var obj = undefined;
A

not allow to set set or access variables of the object, as it is null/undefined. (same thing goes for booleans, strings and numbers)

104
Q

accessing (with dot or bracket notation) a property of an object that happens to be another object, will evoke the property object (T or F)

A

False, access a property of an object does not itself run the object;

105
Q

how to use ? and : to do if/else statements

A

_.last = function(array, n) {
return n === undefined ? array[array.length - 1] : n > array.length ? array : array.slice(array.length - n)
};

106
Q

what is scope

A

part of a program where the binding between a variable and a value is valid

107
Q

can variables created within blocks like if or while be access outside of the blocks themselves?

A

Yes, they will be considered in the “global scope” lexicon. Only vars created inside of a function are considered to be in an a different scope lexicon.

108
Q

how to pass a function and it’s arguments into another function

A

var result = func.apply(this, arguments);

109
Q

an example of closure scope: ._once

A
// Return a function that can be called at most one time. Subsequent calls
  // should return the previously returned value.
  _.once = function(func) {
    // TIP: These variables are stored in a "closure scope" (worth researching),
    // so that they'll remain available to the newly-generated function every
    // time it's called.
    var alreadyCalled = false;
    var result;
    // TIP: We'll return a new function that delegates to the old one, but only
    // if it hasn't been called before.
    return function() {
      if (!alreadyCalled) {
        // TIP: .apply(this, arguments) is the standard way to pass on all of the
        // infromation from one function call to another.
        result = func.apply(this, arguments);
        alreadyCalled = true;
      }
      // The new function always returns the originally computed result.
      return result;
    };
  };
110
Q

arguments vs parameters

A

parameters are the used when constructing the function, arguments are when you pass into a function when calling it (after it has been built)

111
Q

what happens when you assign a variable (var “b”) to another variable (var “a”) that is a function?

A

var b will equal to the function var a. (not the result of var a)

112
Q
what would happen if you ran this?
var fun = function(input){
     console.log(input);
}
setTimeout(
     fun('hi')
, 1000);

and how should i change it to call fun after 1 second? Why?

A
setTimeout(
     function(){
          fun('hi');
     }
, 1000)

you do this because by wrapping the function within an anonymous function, setTimeout will not run the function fun immediately. if i left it as before, it would run fun immediately because the () are invoking the function.

113
Q
Array.prototype.slice()
var myArray = ["a","b","c","d","e"];
myArray.slice(1,4)
A

slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3)

returns [“b”, “c”, “d”]

114
Q

different between changes made to an assigned array, vs a copy of an array

A

when you use array.slice() to make a copy of an array, you are creating an entirely separate object. so even though the contents of the original array matches the content of the copy, they are entirely separate objects in memory. So if one array is [1] and the other is [1], the 1s are unrelated to each other

if the arrays contain other objects (including other arrays), then the new arrays (which are still separate) will point to the same objects

this is because array.slice creates a shallow copy of the original array. arrays contain pointers to other objects, and when an array is copied by slice the pointer is copied, not the object to which it is pointing

so, if you have [{a: true}] and copy it with slice, and then you do copy[0][a] = false, and then call original[0] you’ll get {a: false} (edited)

so primitive types (numbers, strings, booleans, etc) are copied entirely, while objects are copied by reference

if i just assign a new var to an existing array, such as:
var array = [1,"purple", false, {a: true}];
var assignedArray = array;
All items are just a referenced copy (a change to the original array will make a change to the assignedArray
115
Q

what would you use “in” keyword for in objects

A

1) to loop over the keys of an object
2) determine if there is a key in an object (returns true or false. So:
var object = {firstName: “brent”, lastName: “colson”}

“firstName” in object –> true

“fullName” in object –> false

116
Q

shorthand for if/else statements

A

_.last = function(array, n) {
return n === undefined ? array[array.length - 1] : n > array.length ? array : array.slice(array.length - n)
};