JavaScript Flashcards

1
Q

What is SAML

A

Security Application Mark up Language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
function calc() {
    console.log("inside function")
}

calc()

A

calc() //hoist

function calc() {
    console.log("inside function")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
var calc = function() {
    console.log("inside function")
};

calc()

A

calc()

var calc = function() {
    console.log("inside function")
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Assigning a function to a variable

A
function calc(){
    console.log("inside function")
};
var anotherfn = calc;
anotherfn();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Adding a return value with “return”

A
function calc(){
    return "inside function";
};
var returned = calc();
console.log(returned);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Adding a return value with using a var

A
function calc(){
    var stringVar "inside function";
    return stringVar;
};
var returned = calc();
console.log(returned);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Passing data to a function

A
function calc(number1, number2){
    return number1 + number2;
};
var returned = calc(10,8);
console.log(returned);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Passing data to a function via a variable

A
function calc(number1, number2){
    return number1 + number2;
};
var calculator = calc;
console.log(calculator(15,2));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

If statement “executed”

A

var condition = true;

 if (condition){
     console.log('Executed');
 }else{
     console.log('Not executed');
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

If statement “not executed”

A

var condition = false;

 if (condition){
     console.log('Executed');
 }else{
     console.log('Not executed');
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Checking multiple conditions with else if

A
var condition = true;
 var anotherCondition = false;
 if (condition){
     console.log('Executed');
 }else if (anotherCondition){
     console.log('Still Executed');
 }else (condition){
     console.log('Not executed');
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Casting “true” with 1 and “false” with 0

A
var condition = 0;
var anotherCondition = 1;
if (condition){
  console.log('executed');
}else if (anotherCondition){
  console.log('still executed')
}else {
  console.log('not executed');
}
=> returns "still executed"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

“0” is explicitly true, even though only 1 == true and all other numbers are not treated the same as true.
Only 1 and 0 are booleans and the rest are treated as true (compared to 0). Negative values (i.e. -1) are also treated as true. Any text is interpreted/treated as true.

A
var condition = 0;
var anotherCondition = 0;
if (condition){
  console.log('executed');
}else if (anotherCondition){
  console.log('still executed')
}else {
  console.log('not executed');
}
console.log(2==true);

=> returns “still executed” , false

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

Null condition is treated as false to make sure that a certain number is set correctly.

A
var condition = null;
var anotherCondition = 0;
if (condition){
  console.log('executed');
}else if (anotherCondition){
  console.log('still executed')
}else {
  console.log('not executed');
}
console.log(2==true);

=> returns “not executed” , false

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

Switch statements vs. lots of “else if”. More convenient if we know the cases we need to solve for. It’s much more structured than reading lots of else if statements.

Also, without the break statements, you get all 3 values since it falls through. Once it finds it’s case, it continues to execute.

A

var luckyNumber = 8;

switch (luckyNumber){
  case 1: 
    console.log('Is 1');
    break;
  case 8:
    console.log('Is 8');
    break;
  default:
    console.log('Default');
    break;
}

vs.

var luckyNumber = 8;

if (luckyNumber ==1){
  console.log('Is 1');
}else if (luckyNumber ==8){
  console.log('Is 8')
}else {
  console.log('Default')
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

For loop

  1. define a variable.
  2. follow by semicolon
  3. define parameters of how long it will run
  4. counter
A
for (var i=0; i < 5; i++){
  console.log(i)
}

===> prints 0 through 4 (runs 5 times)

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

Nested For Loop

  1. We just j since i is already taken
  2. The inner loop is executed upon each iteration of the outer loop and before the inner loop isn’t finished, the outer loop won’t continue.
A
for (var i=0; i < 5; i++){
  for (var j=0; j<2; j++)
  console.log(i*j)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

For loop with an if condition

A
for (var i = 0; i < 5; i++){
  if (i == 0){
    console.log('1');
  }
}
===> prints "1"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
for (var i = 0; i < 5; i++){
  if (i == 1){
   continue;
  }
   console.log(i);
}
A

==> 0, 2,3,4

For loop with a conditional if statement and continue statement. This should tell JS that once it meets the condition in the if statement, it should continue executing the for loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q
for (var i = 0; i < 5; i++){
        if (i == 1){
            break;
    }
    console.log(i);
}
A

==> 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
for (var i = 0; i < 5; i++){
    for (var j = 0; j < 2; j++){
        if (i == 1){
            continue;
        }
    }
    console.log(i);
}
A

==> 0,1,2,3,4

This continues statement is trigger if i is 1, which is the case. Upon the second iteration, will refer to this inner loop. So this inner loop will continue which doesn’t really matter because we weren’t executing code here anyways.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
for (var i = 0; i < 5; i++){
    for (var j = 0; j < 2; j++){
        if (i == 1){
            break;
        }
        console.log('inside inner loop, j = ' + j);
    }
    console.log(i);
}
A

The break is only applied to the inner loop. Therefore, “continue and “break” only refers to the lop in which they are written and not to any other wrapping loop around them.

inside inner loop, j = 0
inside inner loop, j = 1
0
1
inside inner loop, j = 0
inside inner loop, j = 1
2
inside inner loop, j = 0
inside inner loop, j = 1
3
inside inner loop, j = 0
inside inner loop, j = 1
4
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q
for (var i = 2; i > 1; i--){
    console.log(i);
}
A

==> 2

We only make 1 round because we start with 2, subtract 1 and we are at 1 so i > 1 is no longer satisfied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
for (var i = 4; i > 2; i--){
    console.log(i);
}
A

==> 4,3

It subtracts 4 until the condition of i > 2 is met. Here, 3 and 4 are greater than 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
for (var i = 6; i > 2; i--){
    console.log(i);
}
A

==> 6,5,4,3

It substracts 6 until the condition of i > 6 is met. Here, 6, 5,4,3 is greater than 2.

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

array.length - how should we create a for loop that can loop through an array as long as i is smaller than the length of the array.

A
var array = [1,2,3];
for (var i = 0; i < array.length; i++){
    console.log(array[i]);
}
note: we don't want it to be i <=  because in this case, we would loop until i takes the value of 3 which actually tries to access the 4th element which is not the behavior we want.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

While loop with condition where you print a number less than 7, then increment until it’s 1 less than 7.

We use the wile loop to check a condition “while (condition) so we can check that a condition is no longer true.

A

var number = 5;

while (number < 7) {
    console.log(number);
    number ++;
}
Note: currently at 5, it prints number which is 5, then it increments to 6 which is smaller than 7 and I print 6, then it increments to 7, which is no longer smaller than 7, therefore we quite the loop
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

while with multiple conditions

var condition = true;
var i = 2;
while (condition) {
    if (i == 3) {
        condition = false;
    }
    console.log(i);
    i++
}
A

==> 2, 3

Note: 2 is the starting point and then we increment it to 3 which is when we set condition to false, but we are not instantly skipping out of the loop, we’re just setting condition to false. When we reach the next iteration, we again check the condition as it was set to false, now the loop is finished.

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

do-while loop: We’re still using this while condition but we specify that we want to execute this code anyways even if it starts out as false.

var condition = false;

do{
console.log(‘executed’);
}
while (condition);

A

==> “executed”

This is executed even when the condition is false, which is what this “do” keyword allows us to do.

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

Multiplication:
Javascript has issues with long floating numbers. We therefore try to fix it with .tofix method.

 var a = 1.3;
 var b = 2.2;

console.log(a *b);

if ((a * b).toFixed(2) == 2.86) {
console.log(‘true’);

}else {
console.log(‘false’);
}

A

==>
2.8600000000000003
true

Note: we are fixing it and cutting off all the part we don’t want since it might be a source of hard to trace down bug.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q
var a = 2;
 var b = '2.2';

console.log(a *b);

A

==> 4.4

Javascript will try to cast (interpreting of numbers) a string to “figure out” what the intent of the operator is, as long as it can be casted to a number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q
var a = 2;
 var b = 'join';

console.log(a *b);

A

==> NaN

“join” This is not possible to cast to a number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q
var a = 2;
 var b = infinity;

console.log(a *b);

A

==> infinity

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q
var a = 3.3;
 var b = 2.2;

console. log (a / b);
console. log((a / b).toFixed(3));

A

==>

  1. 4999999999999998
  2. 500
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q
var a = 10;
 var b = 3;

console.log (a % b);

A

==> 1

Modulus returns the value that in the first non-decimal case.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q
var a = 10;
 var b = 0;

console.log (a / b);

A

==> Infinity

JS will show the limit value. when dividing by something extremely big

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

comparison operators

console.log(1 !== 2);

A

==> true

Checking for both value and types are not equal.

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

console.log(null == undefined);

A

==> true

NULL can’t be compared, except it can be compared to undefined.

Undefined is always false, except when comparing to null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q
if (( 1 == 1) && (2 == 2)) {
    console.log('true');
}else{
    console.log('false');
}
A

==> True

The boolean operator here tells JS both sides of this operator have to be true, or combine both results into one single result.

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

console.log((1 == 1) || (2 ==3 ) (4 == 5));

A

==> true

The Or operator will return true as long as any of the conditions we have here is true.

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

console.log((1 == 1) || (2 ==3 ) && (4 == 5));

A

==> true

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

console.log((1 == 1) && (2 ==3 ) || (4 == 5));

A

==> false

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

inversion with a variable

var isTrue = true;
console.log(!isTrue);
A

==> false

true comes false and false becomes true. You want to do this to check for the opposite.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q
var a = 5;
var b = 5;

console.log(a == b ? ‘Equals’ : ‘Not Equal’);

A

==> ‘equals’

ternary operator same as writing. First comes the check ‘a==b’, or “:” we execute the else case.

if (a == b){
    console.log('Equals');
}else {
    console.log('Not equal');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Primitive vs. Reference:

var aNumber = 5;
console.log(aNumber);
var anotherNumber = aNumber;
console.log(anotherNumber);
aNumber = 12;
console.log(aNumber);
console.log(anotherNumber);
A

==>
5, 5, 12,5.

Note: anotherNumber is still 5 even though number has changed after being assigned to anotherNumber. The reason for this is that a copy of the value is created and therefore anotherNumber has the value 5, and no reference to aNumber, therefore, it doesn’t care what I do with aNumber.

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

Primitive vs. Reference

var array = [1,2,3];
var anotherArray = array;
console.log(array);
console.log(anotherArray);

array. push(4);
console. log(array);
console. log(anotherArray);

A
==> 
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]

Note: Since objects are by reference and reference are references to pointers, so even though we didn’t change anotherArray, it still got changed. When we assign array to anotherArray, we copy that reference. When we push a new item on array, the value itself is changed. The 2 pointers aren’t changed, and therefore, both point to the new value with the additional 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q
var array = [1,2,3];
var anotherArray = array;

array = [‘a’, ‘b’];

console. log(array);
console. log(anotherArray);

A

==>

[ ‘a’, ‘b’ ]
[ 1, 2, 3 ]

Note: We are creating another array so it print out the old and new value. With array.push, we were editing an existing object so both pointers to the identical pointer were therefore updated.

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

Scope:

var test = 'Global test';
var test = 'Test';
function localScope() {
    var test = 'Local Scope';
    console.log(test);
}
localScope();
console.log(test);
A

==> local scope. global scope

the function has it’s own scope and therefore, it’s own registry.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q
function localScope() {
    var test = 'Local Scope';
    console.log(test);
}
localScope();
console.log(test);
A

==> localscope

==> reference error, since it can’t access the local function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q
function localScope() {
   test = 'Local Scope';
    console.log(test);
}
localScope();
console.log(test);
A

In non-strict mode:

local scope
local scope

note: If you try to use a variable which hasn’t been declared before, such variable have global scope. Therefore, use strict mode or remember to put var in front of the variable name.

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

var array = [1,2,3];

console. log(1);
console. log(array.length);

A

==> 1, 3

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

var array = [1,2,3];
console.log(1);
array[1] = 100;
console.log(array);

A

==>

1, [1,100,3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q
var array = [1,2,3];
array[5] = 100;
console.log(array);
A

==> [1,2,3,undefined, undefined, 100]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q
var array = [1,2,3];
array.forEach(function(element){
    console.log(element);
});

Explain

A

I use the forEach method and inside that method, I use an anomalous function and call out the ‘element’ of the array.

In general, this is something we’ll often see if we have a method which expects a function as an argument, like this method does, that don’t create a new function and then pass a reference to that–so instead, you create this function on the fly –and you don’t need a name because you are only passing it for this argument –and not using it anywhere else. The function takes an argument ‘element’ and we can name it anything.

So this forEach function expects an argument of type function, which in turn takes an argument and the name. You can then log element. “forEach, it only takes 1 element at a time of the array.

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

push

var array = [1,2,3,,];

array. push(4);
console. log(array);

A

==> pushes the argument into the last position.

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

pop

var array = [1,2,3,4];

array. pop();
console. log(array);

A

==> [1,2,3]

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

return the popped element

var array = [1,2,3,4];

console. log(array.pop());
console. log(array);

A

==>
4
[ 1, 2, 3 ]

58
Q

shift

var array = [1,2,3,4];

console. log(array.shift());
console. log(array);

A

==>
1
[ 2, 3, 4 ]

59
Q

unshift

var array = [1,2,3,4];

array. unshift(‘new’);
console. log(array);

A

==>

[ ‘new’, 1, 2, 3, 4 ]

60
Q

indexOf

var array = [1,2,3,4];

array. unshift(‘new’);
console. log(array.indexOf(‘new’));

A

==> 0

61
Q

var array = [1,2,3,4];
array.unshift(‘new’);
array[array.indexOf(‘new’)] = ‘old’;
console.log(array);

A

==>

[ ‘old’, 1, 2, 3, 4 ]

62
Q

Splice

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

var newArray = array.splice(3);

console. log(newArray);
console. log(array);

A

==>

[ 3, 4 ]
[ ‘old’, 1, 2 ]

63
Q

Splice with indexing

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

var newArray = array.splice(2, 2);

console. log(newArray);
console. log(array);

A

==>
[ 2, 3 ]
[ ‘old’, 1, 4 ]

Note: Splice expects starting index and number of elements.

64
Q

Slice with indexing

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

var newArray = array.slice(2, 4);

console. log(newArray);
console. log(array);

A

Note: Slice from which index to which index. It stores it into a new array. Slice expects starting and ending index.

65
Q

filtering to see what number in the array is the largest

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

console.log(array.filter(function(value) {
return value >2;

}));

A

==> [3,4]

Note: here, we can use the filter function on the array. This method takes an anonymous function, like the forEach method did. Then we also pass an argument here which we will name value. What this method will do is it will access/call each value of the array, pass the value of the element and we can do something with that element. We have to return something with this function, true or false. If the value I am currently interested in/looking at be included in the array returned by this method call is greater than 2 or not? So I will return if the value is greater than 2.

66
Q

Map:

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

console.log(array.map(function(value) {
return value * 2;

}));

A

==>
[ NaN, 2, 4, 6, 8 ]
[ ‘old’, 1, 2, 3, 4 ]

note: map will create a new array and it needs to know what to do with each element of that array. So here, with the new array that you create, double each value. It makes a new array and leaves the old array untouched.

67
Q

reverse()

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

console. log(array.reverse());
console. log(array);

A

==>
[ 4, 3, 2, 1, ‘old’ ]
[ 4, 3, 2, 1, ‘old’ ]

This changes the original array.

68
Q

concat

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

var newArray =[‘Join’,’me’];

console. log(array.concat(newArray));
console. log(array);

A

==> [“old’, 1,2,3,4,’join,me]
[“old”, 1,2,3,4]
[join, me]

Note: Concat allow us to combine 2 arrays into 1 single array. It creates a new array.

69
Q

join

var array = [1,2,3,4];
array.unshift('new');
array[array.indexOf('new')] = 'old';

var newArray =[‘Join’,’me’];

console. log(array.join(‘,’));
console. log(array);
console. log(newArray);

A

==>
old,1,2,3,4
[ ‘old’, 1, 2, 3, 4 ]
[ ‘Join’, ‘me’ ]

Note: Join allows us to join an array into a string. It turns the array into a string and we tell it how to separate the elements inside the string.

70
Q

reduce(): Again, takes a function as an argument.

var array = [1,2,3,4];

console.log(array.reduce(function(total, value) {
console.log(‘Total: ‘ + total + ‘, Value: ‘ + value);
return total + value;

}));
console.log(array);

A
==>
Total: 1, Value: 2
Total: 3, Value: 3
Total: 6, Value: 4
10
[ 1, 2, 3, 4 ]

Note: reduce() reduces an array to a single value and with the function we pass here, we specify the logic by which this array should be reduced–where, all the values add up to 10. It’s a recursive function

71
Q

Objects notation:

var person = {
    name: 'Peter',
    age: 27
};
console.log(person);
console.log(person.name);
A

==>
{ name: ‘Peter’, age: 27 }
Peter

72
Q
var person = {
    name: 'Peter',
    age: 27
};
var field = 'name';
console.log(person[field]);
A

==> peter

Note: This is another way to access the property using [ ] then passing in the fields. It’s not how we should do it by default. This is more useful if we have another variable, and let’s say that this variable is dynamically derived from with your code. Then you could pass this variable here, like we were passing the index i in a for loop when accessing different fields or elements in an array.

73
Q

Objects within objects and accessing it through chaining properties with the dot notation.

var person = {
    name: 'Peter',
    age: 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    }
};

console.log(person.details.hobbies);

A

==>

[ ‘sports’, ‘cooking’ ]

74
Q

function inside of an object

var person = {
    name: 'Peter',
    age: 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    },
    greet: function(){
        console.log('hello');
    }
};

person.greet();

A

==> ‘hello’

Note: Great use of objects is that it allows a user to entier some data about himself and then you want to use that in your JavaScript. You could create a variable for that name, for the last name and so on– or you group it all in 1 object which makes much more sense since were are going to use it that object throughout our code anyway. They are also reference types, which means you can use object in multiple variables and if you change it in 1 place, the rest will be updated too–so you can keep an object in sync and allows the same state through the application.

75
Q

Using string as variable names.

var person = {
    "first-name": 'Peter',
    "age": 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    },
    greet: function(){
        console.log('hello');
    }
};

console.log(person[‘first-name’]);

A

note: you might need this if we are dynamically creating our property names for example. The advantage is that it allow you to use property names which you would not be able to use otherwise. To print it, we would need to use the bracket notation.

76
Q

changing a property after an object has been created.

var person = {
    name: 'Peter',
    age: 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    },
    greet: function(){
        console.log('hello');
    }
};
person.name = 'Anna';
console.log(person)
A
{
  name: 'Anna',
  age: 27,
  details: { hobbies: [ 'sports', 'cooking' ], location: 'Germany' },
  greet: [Function: greet]
}

Note: This is important because you don’t have all the object right at the point of creation. You want to be able to change it later on

77
Q

reading properties from an object.

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    },
    greet: function(){
        console.log('hello, I am ' + age + ' years old');
    }
};
person.greet();
A

==> hello, I am 30 years old.

Note: We have to tell JS that we are interested in a property of this object and not a variable. We do this by adding the “this” keyword.

“this” keyword is like ‘person’.greet outside of this object, just inside of it. It referrs to the object and not to the global variable.

78
Q

using the “this” keyword to access a variable / property inside an object.

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
    details: {
        hobbies: ['sports', 'cooking'],
        location: 'Germany'
    },
    greet: function(){
        console.log('hello, I am ' + this.age + ' years old');
    }
};
person.greet();
A

==> hello, I am 27 years old

Note: We have to tell JS that we are interested in a property of this object and not a variable. We do this by adding the “this” keyword.

“this” keyword is like ‘person’.greet outside of this object, just inside of it. It referrs to the object and not to the global variable.

79
Q

Another way to create an object. Top is preferred.

var age = 30;

var person = {
    name: 'Peter',
    age: 27,
};
var anotherPerson = new Object();
anotherPerson.name = 'Anna';
anotherPerson.age =  30;
console.log(anotherPerson);
A

==. >

{ name: ‘Anna’, age: 30 }

Note: The second way is long handed.

80
Q

Reference types

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};
var person1 = {
    name: 'Peter',
    age: 27,
};
var anotherPerson = new Object();
anotherPerson.name = 'Peter';
anotherPerson.age =  27;
console.log(person1 == person);
A

==> false

Note: JS does not know that these are exactly the same since it has 2 reference pointers, which is good since if we changed the person1, person would not change. Here, we are comparing the pointers and what they hold.

81
Q

Prototype creation

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};
var anotherPerson = Object.create(null);
anotherPerson.name = 'Anna';
console.log(anotherPerson.name);
A

==> Anna

Note: This is longer than the literal notation, but this has an advantage. This is related to prototypes which is JS form of inheritance. Prototypes allows you to have a prototype of an object and then creates objects of that prototype. If that prototype has a certain function, all the objects based on that prototype would have that function too.

The built-in object which is the root prototype of all objects here.

Object.prototype.

The argument which is null which needs to be passed in specifies which prototype and what we want to set for the object we create.

82
Q

setting a prototype

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};
var anotherPerson = Object.create(person);
anotherPerson.name = 'Anna';
console.log(anotherPerson.  age);
A

==> 27

Note: here we pass in the prototype that we want the object to create/mode after. Here we get 27, even though “anotherPerson” does not have the age property but it’s prototype does.

So object create is a useful way of creating new object where you can control what the prototype should be.

83
Q

Prototype Chain

var age = 30;

var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there!’) ;

}; person.greet();
A

==> Hello there

Note: Here we can use the root object to extend or chain a “greet” method to person, even though the person object does not have the greet method.

So JS will first see if the object has agreed method, which it doesn’t. It will then reach out to the prototypical object, which could be an prototype in between Object (root) and another prototype. It will look for the prototype of prototype that an object might have inherited from.

84
Q
var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};
Object.prototype.greet = function() {
    console.log('Hello there!') ;
    };
var max = Object.create(person);
console.log(max.name);
A

==> Peter

It has person as a prototype ad this prototype has this name field.

85
Q
var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there!’) ;

    };
var max = Object.create(person);
person.greet();
A

==>

Hello there!
Hello there!

note: This is a bit confusing since person doesn’t have ‘greet’. This works due to prototype chaining. JS will work it’s way up. It does not find greet on “max”, so it looks in person. It doesn’t find it there so it looks at prototoypical person which it finds.

Here, we can create multiple objects of a certain blueprint of a certain prototype and they all have access to the methods of this prototype.

86
Q

‘this’ object with prototypes.

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there, I am ‘ + this.name + ‘!’) ;

    };
var max = Object.create(person);
var anna = Object.create(person);
anna.name = 'Anna';
max.greet();
anna.greet();
A

==>

Hello there, I am Peter!
Hello there, I am Anna!

Note: ‘this’ refers to the object on which we’re calling this greet method, not to the prototype here. It refers to the object on which you’re calling this ‘greet’ function. We are calling it on Max and Anna, and Max has a name and Anna has a name and therefore, this name refers to the respective names and doesn’t search for a name property in the prototype Anna or Max

87
Q

We remove Anna’s name..

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there, I am ‘ + this.name + ‘!’) ;

    };
var max = Object.create(person);
var anna = Object.create(person);

max. greet();
anna. greet();

A

==>

Hello there, I am Peter!
Hello there, I am Peter!

Here, we start at the Anna Object, we don’t find the name here, so we go up a level to the prototypical level which is Person, which is Max, therefore we’re seeing Max 2 times .

So prototypes is all about blueprints from which you can build different objects and which have the advantage of providing you with functions or with properties you would not have access to in your object on it’s own, through chaining.

88
Q
var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there, I am ‘ + this.name + ‘!’) ;

    };
var max = Object.create(person);
var anna = Object.create(person);

console.log(anna.__proto__ == person);

A

==true

the prototype of Anna is “person”

89
Q

prototype of the prototype (which is the prototype of person

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there, I am ‘ + this.name + ‘!’) ;

    };
var max = Object.create(person);
var anna = Object.create(person);

console.log(anna.__proto__.__proto__ == Object.prototype);

A

==> true

So the prototype of the prototype, is that then the Object.prototype? True or Yes.

The prototype of person and this is the prototype of proto is person – so we can start to see the chain of the prototypes which is where we get our functions and fields from –which again is JS way of inheritance and with this prototype chain, we have a way of accessing fields and methods our object might otherwise not have.

90
Q

Safer and more secured way of getting prototype is:

var age = 30;
var person = {
    name: 'Peter',
    age: 27,
};

Object.prototype.greet = function() {
console.log(‘Hello there, I am ‘ + this.name + ‘!’) ;

    };
var max = Object.create(person);
var anna = Object.create(person);

console.log(Object.getPrototypeOf(anna)== person);

A

==> True

91
Q

What are 3 ways of creating objects:

A
  1. Literal
  2. new Object
  3. Object create.
92
Q

Constructor function to create new objects.

function Person(){

}
var person = new Person();
var name = 'Max';
console.log(person);
A

==>

Person { name: ‘Max’ }

93
Q

what is the prototype of person?

function Person(){

}
var person = new Person();
person.name = 'Max';
console.log(person.\_\_proto\_\_==Object.prototype);
A

==> false

94
Q

Is prototype == to person?

function Person(){

}
var person = new Person();
person.name = 'Max';
console.log(person.\_\_proto\_\_== Person);
A

== false

95
Q

Is prototype person.prototype

function Person(){

}
var person = new Person();
person.name = 'Max';
console.log(person.\_\_proto\_\_== Person.prototype);
A

==> true

Note: We did not create person.prototype. JS creatd it for us. Person() is a constructor function. It’s a normal function, but you use it as a constructor function by adding the ‘new’ keyword. This means we are constructing an object using this function. JS automatically gives us a prototype for each of our functins here or of our object created of this constructor function, which we can access at person, or whatever the name of our constructor function dot prototype.

So there is a certain prototype automatically created for us.

96
Q

function Person(){

}

Person.prototype.greet = function(){
    console.log('Hello');
};
var person = new Person();
person.name = 'Max';
person.greet();
A

==> hello

Note: then we can create person.prototype.greet and again create my greet function.

Now, we set our own prototype and we created an object of our own constructor.

97
Q

Advantage of function constructor?

function Person(){
    this.name = 'Max';

}

Person.prototype.greet = function(){
    console.log('Hello');
};
var person = new Person();
console.log(person.name);
A

Note: Here in the constructor, we are referring to our person when we are using this.

Because I am setting it up here in my constructor function with which I’m creating the object and therefore I have access to this name here in console.log.

98
Q

Is it Anna or Max

function Person(){
    this.name = 'Max';

}

Person.prototype.greet = function(){
    console.log('Hello');
};
Person.prototype.name='Anna';
var person = new Person();
console.log(person.name);
A

==> Max

“Max” is set to the object itself whereas Anna is set to the Prototype. It is not overwriting Max. It is set to a higher level to the prototype instead of the object.

Therefore, we can create our own object, we can preconfigure them and then use this constructor to create objects based on it, to use it as such, a blueprint.

we are creating a person object of “function” blueprint and this blueprint still has its prototype and so on. This prototype is not interferring with constructor functions, constructor function are just an addition to create objects.

99
Q

Adding a function to a blueprint

function Person(){
    this.name = 'Max';
    this.greet = function (){
        console.log('Hello, I am ' + this.name);
    }

}

Person.prototype.greet = function(){
    console.log('Hello');
};
Person.prototype.name='Anna';
var person = new Person();
person.greet();
A

==> Hello, I am Max.

‘this.name’ refers to the blueprint function.

100
Q

Overwriting the blueprint

function Person(){
    this.name = 'Max';
    this.greet = function (){
        console.log('Hello, I am ' + this.name);
    }

}

Person.prototype.greet = function(){
    console.log('Hello');
};
Person.prototype.name='Anna';
var person = new Person();
person.name = 'Anna'
person.greet();
A

==> Hello, I am Anna

We are overwriting the name of the object only and not the blueprint.

101
Q
function Person(){
    this.name = 'Max';
    this.greet = function (){
        console.log('Hello, I am ' + this.name);
    }

}

Person.prototype.greet = function(){
    console.log('Hello');
};
Person.prototype.name='Anna';
var person = new Person();
person.name = 'Anna'

Person.prototype.name = ‘Chris’;

var anotherPerson = new Person();

person.greet();
anotherPerson.greet();

A

==>

Hello, I am Anna
Hello, I am Max

Here, even though we added prototype = Chris, JS has no need to look up a higher level because we get name in the object itself.

So what’s the relationship between prototypes and constrcutor functions? Constructor functions allow us to create objects with some default fields and values. Prototypes allows us to inherit from objects, so they are on a different level.

Prototypes are more than just blueprints, they can act as blueprint, but we always inherit them. so we are at a lower level.

102
Q
function Person(){
    this.name = 'Max';
    this.greet = function (){
        console.log('Hello, I am ' + this.name);
    }

}

Person.prototype.greetGeneral = function(){
    console.log('Hello');
};
Person.prototype.name='Anna';
var person = new Person();
person.name = 'Anna'

Person.prototype.name = ‘Chris’;

var anotherPerson = new Person();

person.greet();
anotherPerson.greetGeneral();

A

Hello, I am Anna
Hello

greetGeneral is available since it’s set up in the prototype of our blueprint, of our constructor function or the prototype of the object on which this instance here is based.

103
Q

“instanceof”

console.log(person instanceof Person);

A

true

JS has a convenient keyword to check if a certain variable is an instance of such a constructor function.

constructor functions are helpers to allow us to create our own objects and they ship with their own prototope .prototype on our constructor function.

104
Q

Using constructor function as a regular function to pass values.

function Person(name, age){
    this.name = name;
    this.age = age;
}
var person = new Person('Max', 27);
console.log(person);
A

==>

Person { name: ‘Max’, age: 27 }

Note: In the end, this is a normal function so we can work inside it as we could in any function. Therefore, we can pass ‘Max’, and 27. This is what we will need, a chance to have a generic blueprint but fill it with different values for different object based on that blueprint.

105
Q

Using Constructor function as a blueprint.

function Person(name, age){
    this.name = name;
    this.age = age;
}
var Max = new Person('Max', 27);
var Anna = new Person('Anna', 30);
console.log(Max);
console.log(Anna)
A

Person { name: ‘Max’, age: 27 }
Person { name: ‘Anna’, age: 30 }

Note: Here, we create a Max object and then create an Anna object here as well, using the same blueprint but with different values and print both out to the console.

106
Q

What are the 4 ways to create an object:

1) Literal

var person ={
    name: 'Max',
    age: 27,
};
console.log(person instanceof Object);
A
  1. Constructor are blueprints for our objects of which we can create an instance of, so that you can create instances of your constructor functions
  2. We have prototypes which allows you to implement inheritance which sits on a higher and provide a fallback mechanism to find missing functions and fields.
  3. 4 different ways of creating objects.
  4. Literal notation and checking “instanceof” we can check Objct.prototype as a prototype.
    5.
107
Q

2) new Object()

var person = new Object();

person. name = “Max”;
person. age = 27;
console. log(person);

A

{ name: ‘Max’, age: 27 }

Note: This is almost identical to the literal way of creating an object. Object that objects seems to be the constructor function used with new.

108
Q
  1. Object.create(null)

var person = Object.create(null);

person. name = ‘Max’;
person. age = 27;
console. log(person);

A

[Object: null prototype] { name: ‘Max’, age: 27 }

Note: Here, we can pick our prototype and we can set it to null if we don’t want this to have a prototype. If null, you would not have Object.prototype as a fallback mechanism –here “toString” would work on all objects but we get an error.

109
Q

Object.create(null) with toString.

var person = Object.create(null);

person. name = ‘Max’;
person. age = 27;
console. log(person.toString());

A

==> error
TypeError: person.toString is not a function

Note: If null, you would not have Object.prototype as a fallback mechanism –here “toString” would work on all objects but we get an error.

110
Q

var person = Object.create(null);

person. name = ‘Max’;
person. age = 27;
console. log(person instanceof Object);

A

==> false

Note: This is a way to create an object that is pretty much standalone

111
Q
  1. Constructor function
function Person (){
    this.name = 'Max';
    this.age = 27;
}
var person = new Person();
console.log(person);
A

Person { name: ‘Max’, age: 27 }

Note: Here, we are not using the built-in new object but instead new person based on this function set up.

This has the advantage of allowing you to build our own blueprint which you create objects and we can create multiple objects of that blueprint. It ships with it’s own protototype (person.prototype) but it also would have Object.prototype as a high level fallback, which all object have, besides the exception with object.create(null)

112
Q

function fn(){
console.log(this);
}
fn();

A

We see the window object –the global object.

Note: the ‘this’ keyword has it’s own head inJS and it’s not always referring to the same thing. On the top level, it is referring to the global object, to the window object and in the browser, it was referring to the ‘this’ object. But a general rule, could this always refer to the left part of the dot which executes something where this is included. Example:

Here’s a function where I log ‘this’ and then I call ‘this’ function

113
Q
function fn(){
    console.log(this);
}
//fn();

var obj = {
obfn: fn
};
obj.obfn()

A

Note: Now ‘this’ referrs to ‘obj’ object. So this is what we meant when we say that it refers to the thing on the left of the dot, object here–since it is the left obj that is calling the function.

114
Q

bind()

function fn(){
    console.log(this);
}
//fn();

var obj = {
obfn: fn
};
obj.obfn.bind(this)();

A

==> Back to global window

115
Q

Bind

var obj = {
    obfn: fn
};
var person = {
    name: 'Max'
}

obj.obfn.bind(person)();

A

==> { name: ‘Max’ }

Note: We create another object. With bind, we can pass whatever ‘this’ here (i.e. function fn() console.log (this) should refer to person object.

Or if we leave it out without the bind, it will refer to part on the left of the dot.

116
Q
function fn(){
    console.log(this);
}
//fn();
var obj = {
    obfn: fn
};
var person = {
    name: 'Max'
}

obj.obfn();

A

==> { obfn: [Function: fn] }

we see the var obj –> which is the left side of the dot.

Note: ‘this’ is not always the same. It is whatever calls a function where ‘this’ is used in. It is what ‘this’ refer to.

117
Q

bind() – we want to pass message and ‘this’

function fn(message){
    console.log(message + this);
}
//fn();
var obj = {
    obfn: fn
};
var person = {
    name: 'Max'
}

obj.obfn.bind(person, [‘Hello’])();

A

Hello[object Object]

bind takes multiple argument. The first is always to what ‘this’ should be bound but all the other arguments are the normal function.

118
Q

call() what are the differences.

function fn(message){
    console.log(message + this);
}
//fn();
var obj = {
    obfn: fn
};
var person = {
    name: 'Max'
}

obj.obfn.apply(person, [‘Hello’]);

A

==> Hello[object Object]

Note: Don’t need the extra (). This instantly calls the method on its own. With bind, you can bind the ‘this’ value and use it later because it’s not called instantly. With call(), it is called instantly.

119
Q

apply() what are the differences.

function fn(message){
    console.log(message + this);
}
//fn();
var obj = {
    obfn: fn
};
var person = {
    name: 'Max'
}

obj.obfn.apply(person, [‘Hello’]);

A

==> Hello[object Object]

Apply() works almost the same as call(), it also calls the function immediately but you pass the argument as an array.

bind, call and apply are the important helpers here which makes sure that your function call uses ‘this’ in the right context and you’re not using a ‘this’ if we don’t want to use it.

120
Q

Object.defineProperty. Why use this since it is slightly more complicated. This way allows us to create and delete properties on objects, which can be done in a more powerful way.

var account = {
    cash: 12000,
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'deposit', {
    value: function(amount) {
        this.cash +=amount;
    }
});
account.deposit(3000);
account.withdraw(1000);
A

==> 14000
Note: This Objct reduces the cash property by the amount passed to the function and then prints out the new amount,

We create the ‘defineProperty’ method. With that, I pass as a first argument the object on which I want to define a new property, account and as a string, the name of the property I want to create. The 3rd is a JS object and here I configure this property. Why would we choose this way instead the dot notation? With this, we can configure this property and there are some keys available which we can set.. for example, the value key.

Value should be the value of this property which takes an amount and it increases cash.

There are are other keys beyond value.

121
Q

defineProperty –> writable

var account = {
    cash: 12000,
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    value: 'ID000-1',
    writable: true
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
A

==>
ID000-1
ID000-3

Note: We changed to ID00-3, but it did not change it because if we create defineProperty, but default, it’s read-only. Adding ‘Writeable” makes it writeable.

defineProperty is very useful if we want to create a property with a more detailed configuration. You can’t do this with a normal dot notation

Other configuration include setting things to ‘enumerable’ to loop through objects.

122
Q

getters with Object.define

var account = {
    cash: 12000,
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    get: function() {
        return 'Hello';
    }
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
A

Hello
Hello

Create getters and setters and set to a function. This function will be called whenever I try to access this name value. Then we can define what happens when this gets called. In this case, return something.

123
Q

setters and getters

var account = {
    cash: 12000,
    _name: 'Default',
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    get: function() {
        return this._name;
    },
    set: function(name) {
        this._name = name;
    }
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
A

==>
Default
ID000-3

Note: We can also add setters. So to make it more useful, we add a property name (_name
_name is a property of my object and I’m creating a new property, also named ‘name’ but without the prefix (i.e.. in the Object.definePropery argument). That is all convention.

124
Q
var account = {
    cash: 12000,
    _name: 'Default',
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    get: function() {
        return 'hello';
    },
    set: function(name) {
        this._name = name;
    }
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
A

==>
hello
hello
default

With getters and setters, you can control how values in your objects are being set or fetched whenever something else from outside tries to access them. This can be used to filter values.

125
Q
var account = {
    cash: 12000,
    _name: 'Default',
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    get: function() {
        return this._name;
    },
    set: function(name) {
        if (name=='Max') {
            this._name = name;
        }
    }
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
A

==> Default, Default

It’s still default, default since “if” check is not successful whenever I’m not setting this name. This however is important because this name here is what I retrieved when I try to access this name property.

This name property is a filter which bridges the outside of this object and the inside, so which controls the access we have on this object.

Note: Here, I use an if statement to filter–so only in this case will I set the name.

126
Q
var account = {
    cash: 12000,
    _name: 'Default',
    withdraw: function(amount){
        this.cash -= amount;
        console.log('Withdraw ' + amount + ', new cash reserve is: ' + this.cash);
    }
};
Object.defineProperty(account, 'name', {
    get: function() {
        return 'Hello';
    },
    set: function(name) {
        if (name=='Max') {
            this._name = name;
        }
    }
});
console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);
console.log(account._name);
A

Hello, Hello, Default

Note: Here you can filter out the access to “default” with ._name

Again, you cn implement such filters and prevent certain values from being set and even besides setters and getters, as you learned, this defineProperty allows you to set up and configure your own properties for your objects.

127
Q

Build in methods and properties:

var person = {
    name: 'Max',
    age: 27
}
// person.name = null; 
delete person.name;
console.log(person.name);
A

==> null

==> undefined

128
Q
var person = {
    name: 'Max',
    age: 27
}
// person.name = null; 
//delete person.name;
//console.log(person.name);
console.log('name' in person);
A

==> true

129
Q

for (var) loop:

var person = {
    name: 'Max',
    age: 27,
    greet: function(){
        console.log('Hello');
    }
}

for (var field in person) {
console.log(field);
}

A

name
age
greet

130
Q

get the value of the fields:

var person = {
    name: 'Max',
    age: 27,
    greet: function(){
        console.log('Hello');
    }
}

for (var field in person) {
console.log(person[field]);
}

A

Max
27
[Function: greet]

131
Q
unction generator(input) {
    var number = input;
    return function(){
        number * 2;
    };
}
var calc = generator(900);
var calcAnother = generator(1000);
console.log(calc());
A

Closures is aware of it’s environment. So even thought we are now rerunning this funcitn and we are resetting number and binding it to a number variable, and therefore, this old variable is not touched by that. It stores it’s environment. That’s why it’s a really powerful tool for callbacks which have to execute a function, because we are able to store the environment.

132
Q

(function calc(){
console.log(‘Calc’);
})();

vs.

function calc(){
console.log(‘Calc’);
});
console.log(‘Calc’)

A

==>Calc

Immediately invoked function executions. (IFFE).

We do this so we make sure we don’t pollute the global scope with our variables.

133
Q
(function calc(){
    var number = 10;
    console.log(number);
})();
console.log(number);
A

10
/Users/peternguyen/Desktop/Function/function.js:979
console.log(number);
^

ReferenceError: number is not defined

Note: we get 10 and then the error because it’s registered in the local scope of this function and not in the global scope. We use IFFE because the global scope might impact the local scope. Maybe you are using a 3rd party package which uses certain local variable and you accidentally overwrite them. Again, you do this to make sure that the variable is only available inside this local scope and not everywhere else.

134
Q
var obj = {};
(function calc(input){
    obj.name = 'Max';
})(obj);
console.log(obj);
A

==> { name: ‘Max’ }

Note: I get the object with the name ‘cause we created the object on the global scope. I’m changing the global object, not a local scope variable. We are not creating a new variable inside this function.

135
Q

setTimeout(function(){
console.log(“Finished”)
}, 2000);

A

==> Finished, (after 2 seconds)

This method expects 2 arguments. The first argument is the function to execute. Here you could point towards a function you created in your code wit the traditional approaches, or we can pass a closure, so an anonymous function. In this case, we are going to do the latter. We will provide a function, then the code which should get executed. The first argument is before the comma and the second is after the comma.

This is a very important function since it will fetch some code after a specific time pass or fetch some animation, etc.

136
Q

setInterval(function() {
console.log(‘Ping’);
}, 500)

A

==> “ping” every half-second and it won’t stop.

137
Q
var interval = setInterval(function() {
    console.log('Ping');
}, 500)

setTimeout(function(){
clearInterval(interval);
}, 2500);

A
==>
Ping
Ping
Ping
Ping

Note: The behavior is to run it every half-second but we want to stop it at some point in the future.

We now have a reference to the setInterval by assigning a variable to it. Then at some point in my code, we run a certain check where we see if we still need the interval. We demo with the timeout function. So we have the function from before, then after 2500 milisconds, I’ll want to stop the interval and I can do this with the clearinterval, an we can pass the ‘var = interval’ reference, so this variable

138
Q
var interval = setInterval(function() {
    console.log('Ping');
}, 500)

setTimeout(function(){
clearInterval(interval);
}, 2500);

A
==>
Ping
Ping
Ping
Ping

Note: The behavior is to run it every half-second but we want to stop it at some point in the future.

We now have a reference to the setInterval by assigning a variable to it. Then at some point in my code, we run a certain check where we see if we still need the interval. We demo with the timeout function. So we have the function from before, then after 2500 milliseconds, I’ll want to stop the interval and I can do this with the clearinterval, an we can pass the ‘var = interval’ reference, so this variable

139
Q
var a = '5'
console.log(parseInt(a));
A

==> 5 instead of ‘5’ , a string

Note: Transformation functions.

140
Q
var a = 'FBB123';
console.log(parseInt(a, 16));
A

==> 16494883

Transforms a Hexidecimal into an integer.

141
Q
var a = 10;
console.log(a.toString());
A

==> ‘10’

Note: toString is a method defined in the Object.prototype, which is the base prototype of all objects, therefore all objects by default has this ‘toString” method.

142
Q
var a = 10.3;
console.log(a.toFixed(2));
A

==> 10.30

Note: You call a method() and passed the parameter so you can instruct it how to transform. Gotta keep this in mind Xy.

So these are built-in parser or ways to transform values and there are more.