JavaScript Flashcards

1
Q

What is a varibale in JavaScript?

A

A variable is a named container (space in the memory) that stores some value.

The main purpose of variables is to store some information in them. Variables are labeled with names so that we may easily access the information contained within them when we need it. A common way of saying “access a variable” is “reference a variable by its name”.

You decided to pack all your stuff into different boxes and place them in your garage. You put a label on each box so that it’s easier to find it later and obviously, the name is descriptive, so you know what is in that box.

  • the garage is the memory,
  • the box is the variable,
  • the box label is the variable’s name,
  • the box content is the variable’s value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is meant by the term ‘variable decleration’?

A

A variable declaration is when you create a variable and give it a name.

When we declare a variable, we create storage space in the memory and give it a name (label) by which we can access it later.

To declare a variable, we can use the keyword let or const and in older versions of JavaScript, you would find the keyword var. To start, we’ll use let to declare variables. Later in the lesson, we’ll explain how to use const.

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

What is meant by the term ‘variable initialization’?

A

Variable initialization is when you assign some value to a newly declared variable.

After declaring a variable, you can assign it a value. This process is called variable initialization.

Example
let company; <- decleration
company = ironhack; <- initialization

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

What is the default value of a variable?

A

We you declare a variable but you don’t initialize it, the default value is ‘undefined’

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

What’s the difference between a variable decleration with ‘let’ and ‘const’?

A

let is used to declare variables whose value may change in the future.

const is used to declare a variable that will remain constant and whose value can’t be reassigned.
Note: a constant variable must be declared and initialized at the same time

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

What naming rules are there for variable naming in JavaScript?

A

Variable Naming Rules

1) Variable names must begin with a letter, a dollar sign $ , or an underscore _ .

2) Variable names can contain letters (uppercase and lowercase), numbers and the symbols _ and $.

3) Variable names must not contain spaces.

4) Variable names are case sensitive (Name, name and NAME are all different variables)

5) Reserved keywords cannot be used as variable names.

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

What is meant by the naming convention camelCase?

A

camelCase (see also) https://en.wikipedia.org/wiki/Camel_case

Used for variable naming in Javascript, because it should inc rease readability, when there are more than one word:

Begin words or abbreviations in the middle of the phrase with a capital letter. The purpose of this practice is to enhance readability.

Example:
let myAge = 18;
let yourEyeColor = “green”;

However, there are more conventions like:
- camelCase
- PascalCase
- snake_case
- kebab-case

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

Which data types do exist in JavaScript?

A

There are primitive data types and non-primitive data types:
1) Primitive data types are
1) string &raquo_space; let name = “Hello”;
2) number &raquo_space; let price = 1034;
3) boolean &raquo_space; let isActive = true;
4) undefined &raquo_space; let myUndefined = undefined;
5) null &raquo_space; let myNull = null;
(6) bigInt_ and symbol_)

2) Non-Primitive data types are
1) object &raquo_space; let student = { name: “Ana”, age: 40 };
2) array &raquo_space; let numbers = [7, 23, 31, 45, 60];

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

What is meant by the typeof operator?

A

The typeof operator gives me the type of the variable.
Example:

let favoriteFood;
favoriteFood = ‘Steak’;
console.log(typeof favoriteFood); // <== string

Read more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

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

What is meant by the term expression?

A

An expression is a combination of any values (number, string, array, object) and operators that produces another value.

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

Data Type String:
What is a string?

A

A string is a sequence of characters (text).
A string can contain any character: letter, number, punctuation, or even new lines and tabs.

To create a string, we wrap a piece of text with quotes. You can use any of the following types of quotes when creating a string:

”” - double quotes,
‘’ - single quotes and
`` - backticks (in most keyboards, it is placed above the tab in the upper-left corner).

Backticks `` allow string interpolation, which we’ll explain in the next step

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

Data Type String:
What is meant by string interpolation?

A

String interpolation is the process of embedding variable values into a string using placeholders.

In JavaScript, string interpolation is available for strings created with backticks `` .

Example:
const name = “John”;
const surname = “Doe”;
const greeting = Hello, my name is ${name} ${surname}!!;

console.log(greeting);

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

Data Type String:
What is a multiline string?

A

A multiline string is a long string that spans multiple lines.
In JavaScript, multiline string is available for strings created with backticks `` only.

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

Data type String:
What is meant by Concatenation?

A

Concatenation is the process of appending (adding) one string to the end of another string.

We can do that by + or += (this adds the new string to the previous one)
Example:
let greeting = “”;
greeting += “Hello there.”;
console.log(greeting); // ==> Hello there.

greeting += “ Welcome to Ironhack!”
console.log(greeting); // ==> Hello there. Welcome to Ironhack!

However, we can also add strings and numbers by +
Example:
let birthYear = 1990;
let birthDate = “My birthday is on May 8th “;
let evasBirthday = birthDate + birthYear;
console.log(evasBirthday);
console.log(typeof evasBirthday) // <== “string”&raquo_space; string + number is turned into string

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

Data Type String:
How can you access the length of a string?

A

By adding . length at the end.
Example:
let evasHobby = “Coding is my favorite hobby”;
console.log(evasHobby.length) // <== 27

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

Data Type String:
How can you index a string?

A

A string character can be indexed by adding a bracket at the end with the number of the indexed character. However, you must be aware that JavaScript always starts counting at 0.
Example:
let evasHobby = “Coding is my favorite hobby”;

console.log(evasHobby[0]) // <== C
console.log(evasHobby[11]) // <==y

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

Data Type String:
How would you check if a string has a certain character? And how does it work?

A

You can check with the method
.indexOf(“String you search for”);

E.g.
let evasHobby = “Coding is my favorite hobby”;

console.log(evasHobby.indexOf(“Coding”)) // <== returns 0 as it starts there

console.log(evasHobby.indexOf(“o”)) // <== returns 1, as it will always name ths index of the first found letter

console.log(evasHobby.indexOf(“z”)) // <== returns -1 as non existent

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

Data Type String:
How would you cut out a part of a string without modifying the original string?

A

You can do it with the method
.slice(index start, index end)

The string method slice() extracts a part of a string and returns it as a new string without modifying the original string.

let evasHobby = “Coding is my favorite hobby”;
let cutOut = evasHobby.slice(10,21)

console.log(cutOut) // <== “my favorite”

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

Data Type String:
How would you turn all letters of a string to uppercase?
How can you achieve just turning the first letter to uppercase?

A

You can do it with the method
.toUpperCase()

All letters:
let evasHobby = “Coding is my favorite hobby”;
evasHobby = evasHobby.toUpperCase();

First letter only:
let name = “sandra”;
let firstCharacterUp = name[0].toUpperCase()
let formattedName = firstCharacterUp + name.slice(1);

console.log(formattedName) // <== “Sandra”

vereinfacht auch
let name = “sandra”;
let formattedName = name[0].toUpperCase() + name.slice(1)
console.log(formattedName);

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

Data Type Number:
What is the difference between an integer and floating number?

A

Integer: a whole number, such as 1, 12, 256, 10000, -5, -83, etc.
Floating-point number: a number with a decimal point, such as 0.2, 5.5, -123.55, etc

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

Data Type Number:
Name all the operators you know in JavaScript

A

Basic:
- Addition: a + b
- Substraction: a - b
- Multiplication: a*b
- Division: a / b

Advanced:
- Exponential: a ** 2 // <== a * a * a ==> a^3
- Modulo: a % b // <== gives the remainder of a/b; if a is a multiple of a it will be 0

Note: to check if you have a odd number all you need to do is check if the modulo %2 === 0&raquo_space; must retur ‘true’
for odd number modulo %2 ===1&raquo_space; must be true

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

Data Type Number:
What is meant by an Advanced Assignment Operator?

A

Assignment Operator:

Advanced Assignment Operator:
x += y &raquo_space; Addition Assignment&raquo_space; x = x+y
x -= y&raquo_space; Substraction Assignment&raquo_space; x = x-y
x = y&raquo_space; Multiplication Assignment&raquo_space; x = xy
x /= y&raquo_space; Division Assignment&raquo_space; x = x/y
x %= y&raquo_space; Remainder Assignment&raquo_space; x = x%y
x **= y&raquo_space; Exponentiation Assignment x = x ** y

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

Data Type Boolean:
What is meant by the Boolean Data Type?

A

Boolean data type can have one of two possible values: true or false.

Booleans are used to represent two states, such as if a light is ON or OFF, or to indicate if something is true or false.

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

Data Type Boolean:
What are the comparision operators?

A

Comparison operators are used to check if two values or variables are equal or different.

Expression Description
exp1 == exp2 Returns true if the expressions have the same
value

exp1 === exp2 Returns true if the expressions have the same
value and the same data type of value.

exp1 != exp2 Returns true if the expressions do not have the
same value.

exp1 !== exp2 Returns true if the expressions do not have the
same value or the same type of value.

exp1 < exp2 Returns true if the value of exp1 is smaller than the
exp2 value.

exp1 > exp2 Returns true if the value of exp1 is bigger than the
exp2 value.

exp1 <= exp2 Returns true if the value of exp1 is smaller or equal
than the exp2 value.

exp1 >= exp2 Returns true if the value of exp1 is bigger or equal
than the exp2 value.

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

Data Type Boolean:
What is meant by a Boolean expression?

A

A boolean expression is simply an expression that turns true or false

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

Data Type Boolean:
What is meant by strict equality?

A

Strict equality means that the operator checks for same value AND for same data type.
The operator is the 3 equal signs: ===

It is recommended to always use this operator to prevent bugs.

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

Data Type Boolean:
What are logical operators?

A

Logical operators are used for combining two or more boolean expressions (expressions that return true or false) into one large expression that returns true or false.

AND (&&) expr1 && expr2 Returns true if both operands are
true; otherwise, returns false.
OR ( ||) expr1 || expr2 Returns true if at least one of the
operands is true; if both are false,
returns false.
NOT (!) !expr Returns the opposite boolean state. If
the operand is true, returns false. If
the operand is false, returns true.

28
Q

Data Type Boolean:
What is meant by the terms truthy and flasy?

A

In addition to the boolean values true and false, JavaScript also allows you to evaluate any other value (such as string, number, etc) in a boolean context.

Truthy values, are values that JavaScript automatically converts to true, when in a boolean context.

> > All values in JavaScript are truthy except false, 0, -0, 0n, “”, null, undefined and NaN

Falsy values, are values that JavaScript automatically converts to false, when in a boolean context.

false The boolean value false
0 The number zero
-0 The number negative zero
“”, ‘’, `` Empty string of any kind
NaN NaN or Not a number is special value indicating an
incorrect numerical operation. For example, dividing a
number by a string (2 / “bob”) generates NaN.
null Represent the absence of any value.
undefined Special value that JavaScript automatically assigns to
uninitialized variables.

29
Q

Data Type Undefined:
What is meant by the Data Type Undefined?

A

Whenever a variable s not initiatied it will be assigned ‘undefined’. This is a data type on its own.

30
Q

Data Type Null:
What is meant by the Data Type Null

A

Null represents the intentional absence of a value. We commonly assign it to a variable to indicate that the variable has been left empty on purpose.

31
Q

Conditions:
What is meant by a statement?
What is meant by a conditional statement?

A

A statement is a set of instructions in the form of a code block.
Conditional statements (or conditionals) are blocks of code containing instructions that will be executed if a certain condition is met.

32
Q

Conditions:
What is meant by a if-statement?

A

The if statement (or conditional block) executes a block of instructions if a specified condition is true. The condition is an expression that evaluates to true or false.

CODE:
if (/* condition /) {
/
code block with instructions that will
run if the above condition is true */
}

CODE EXPLANATION:
If the condition inside of the parenthesis evaluates to true, the code block inside of the curly braces {} will run.
Conditional statements are commonly used in combination with comparison operators (e.g., >, <, >=, <=, ===, etc.) or logical operators (&&, ||, !).
When creating conditional expressions, we can use any JavaScript data type.

EXAMPLES:
String:
const language = “English”;

if (language === “English”) {
console.log(“Welcome!”);
}

In the above if statement, we check if the string stored in the variable is equal to “English”. If the expression evaluates to true, the code inside of the curly braces {} will be executed.

Number:
const age = 30;

if (age >= 18) {
console.log(“You are allowed to join!”);
}

The above if statement is checking if someone’s age is greater or equal to 18. If the expression evaluates to true, the console.log inside of the curly braces {} will execute.

You can also use it with undefined, null and of course booleans.
For the latter the following is the case:
When you have a boolean variable like finishedPrework, you can use it directly in the if statement to check if it’s true. The code will only run when it’s true:

const finishedPrework = true;

if (finishedPrework) {
console.log(“Ready to start the course!”);
}

Attention: you don’t need to have a boolean value, you can use any data type variable as JavaScript, does the coercion automatically, you just need to be aware of truthy and falsy values&raquo_space; see above

33
Q

Conditions:
What is meant by a else-statement?

A

The else statement is executed when the previous if/else if statement conditions are false.

CODE:
if (/* condition /) {
/
code block with instructions that will
run if the above condition is true /
} else {
/
code block with instructions that will
run when the if condition is false */
}

34
Q

Conditions:
What is meant by the else-if-statement?

A

To be able to chain multiple conditions, we use else if statements.

The else if statement is executed when the previous if or else if statement condition is false.

CODE:
if (/* condition1 */) {
// If the “condition1” is true only this block will run

} else if (/* condition2 /) {
/
This block runs if “condition2” is true
and the previous conditions are false. */

} else if (/* condition3 /) {
/
This block runs if “condition3” is true
and the previous conditions are false. */

} else {
// This block runs only if all above turns out to be false
}

In a conditional statement with if, else if and else, only one of the blocks in the entire conditional statement will run. In other words, when one condition has fulfilled the code in the corresponding curly brackets {} runs and the other conditions are ignored.

NOTE:
A couple of important syntax rules to follow when writing if, else if and else statements:

if and else if statements always require a condition in order to work,
else statements do not need a condition, as it means to run the block of code in every other possible case.

35
Q

Conditions:
What is meant by the switch-statement?

A

The switch statement is an alternative to the if/else/else if blocks.
It is used to simplify the if/else/else if conditional statements that have too many conditions.

CODE:
switch (/* expression */) {
case value1:
// statements are executed when the result of an expression matches the value1
break;
case value2:
// statements are executed when the result of an expression matches the value2
break;

case valueN:
// statements are executed when the result of an expression matches valueN
break;
default:
// statements are executed when none of the above cases match the value of the expression
break;
}

Multiple case clause:
To avoid code redundancy in switch statements, you can combine multiple case clauses to run the same block of code by just leaving the break between them.
Multiple case clauses act as a logical OR operator.

Attention with the break clause:
Ensure to always add a break clause between the separate blocks as otherwise you will produce a ‘fall-through’, i.e. from the first true case on that is executed all following cases will be executed as well, no matter if their condition is true or not!

36
Q

Loops:
What is a loop?

A

A loop repeatedly runs some code or a set of instructions until a certain condition is met.

37
Q

Loops:
What loop types do exist in JavaScript?

A

for
while
do…while
for..in
for…of

38
Q

Loops:
What is the while loop?

A

The while loop repeatedly executes the provided code, while the specified condition is true. The loop will stop running once the condition evaluates to false.

CODE:
while (/* condition */) {
// code to execute repeatedly while the condition is true

// condition update
}

CODE EXPLANATION:
The while loop consists of 3 key parts:

1) the condition - the loop keeps running while the condition is true. Once the condition is false, the loop will end;

2) the code to execute - the purpose of the loop is to run some code repeatedly, a certain number of times.

3) the condition update - the loop condition must be updated at some point to ensure the condition eventually evaluates to false. Otherwise, the loop will run infinitely.

39
Q

Loops:
What is the for-loop?

A

A for loop is much like the while loop, except that the initialization, condition and expression update is all handled in it:

CODE:
for (/* initialization /; / condition /; / update expression */){
// code to execute
}

CODE EXPLANATION:
The for loop consists of 4 key parts:

1) the initialization - runs only once on the start of the loop; it is used to initialize the counter variable.

2) the condition - the loop keeps running while the condition is true; once the condition is false, the loop will end;

3) the code to execute - the purpose of the loop is to run some code repeatedly, a certain number of times.

4) the update expression - An expression that will be evaluated at the end of each loop iteration; it is used to update (increment/decrement) the counter after each iteration.

40
Q

Loops:
Can you do nested loops?

A

Yes you can do it with for and while.
The outerloop is always executed as soon as the innerloop has finished.

E.g. for loop
for (i = 0; i < 3; i++) {
console.log(“OUTERLOOP”);

  for(j=0; i<=2; i++) {
  console.log("INNERLOOP");
  } }

OUTPUT:
“OUTERLOOP”
“INNERLOOP”
“INNERLOOP”
“INNERLOOP”
“OUTERLOOP”
“INNERLOOP”
“INNERLOOP”
“INNERLOOP”

Outerloop is executed 2 times, while innerloop is executed 3 times

E.g. while loop&raquo_space; to achieve the same with a while loop
let i = 1
while(i < 3) {
console.log(“OUTERLOOP”);
i++;

   let j = 0;
    while(j <= 2) {
        console.log("INNERLOOP");
        j++;
    } }
41
Q

Loops:
Why do you need to use a break or continue statement in a loop?

A

A break statement is useful, when you want to stop a loop at a certain point once the desired result is achieved. One such example is searching for a certain character in a string, e.g. a point in a string

EXAMPLE:
const password = “$123abc.456789$”;

for (let i = 0; i < password.length; i++) {
const char = password[i];

if (char === “.”) {
console.log(“Character not ‘.’ is not allowed!”)
break;
}
}

A continue statement is useful, when you want to skip a loop iteration when a certain condition occurs, e.g. when you skip even numbers and only print odd numbers

EXAMPLE:
for (i = 0; i <= 100; i++) {
if(i % 2 === 0) {
continue;
}
console.log(i);
}

42
Q

Functions:
What is a function?

A

A function is a reusable block of code.

43
Q

Functions:
What is the decleration of a function?

A

A Function declaration is just an inactive statement containing code (set of instructions).

CODE:
function name ( /* parameters / ) {
/
the code to execute
when the function is called */
}

A function declaration consists of 4 key parts:

1) the keyword function - a function declaration must start with the keyword function.

2) the function’s name - function name is the identifier by which the function can be called (accessed).

3) parameters - a list specifying the input values that the function is expecting.

4) the code to execute - a set of instructions that will be executed when the function runs.

44
Q

Functions:
What is meant by the term: invoking a function?

A

The function invocation is the process of executing (calling) a function. To invoke a function, add a set of parenthesis () after the function’s name.

45
Q

Functions:
What are parameters and arguments?

A

A parameter - is a placeholder for the value the function is expecting. Parameters are set during the function declaration.

An argument - a value given to the function when invoked. Arguments are passed to the function during the invocation.

CODE:
// Function declaration
function doSomething (/* parameters */) {
// code to execute
}

// Function invocation
doSomething(/* arguments */);

46
Q

Functions:
What happens if you add more arguments than there are parameters for a function?

A

In JavaScript, additional arguments (not specified as function’s parameters) passed during the function’s invocation get ignored.

47
Q

Functions:
What happens when arguments are missing?

A

Function parameters are placeholder variables that store argument values provided when the function is invoked.

If an expected argument is not provided during the invocation, the value is set to undefined.

48
Q

Functions:
What is meant by the keyword return? What does it do in the function context?

How does it differ from console.log?

A

The return keyword stops the function’s execution and returns the provided value.

The value returned from the function becomes available in the place where the function was invoked.

Console.log prints sth to the console. Return provides a value which can be reused then.

49
Q

Functions:
What effect does return have on code execution of the function?

A

As soon as the function executes return, it stops; i.e. code after the return statement will not be executed anymore

50
Q

Functions:
What is meant by ‘returing stored values’?

A

When returning a value we can as well return values stored in variables defined inside of the function body

CODE:
function getFullName (firstName, lastName) {
// Store the value in a variable
const fullName = firstName + “ “ + lastName;

// Return the value stored in the variable
return fullName;
}

Storing a value in a variable before returning it has its benefits. Using a variable, we give a meaningful name to the value and make the code easier to understand.

51
Q

Functions:
What happens if you forget the return?

A

If the return keyword is omitted, the function will by default return undefined

EXAMPLE:
function divide (a, b) {
a / b; // missing a return keyword
}

const divisionResult = divide(100, 4);

/* if the return keyword is omitted
function by default returns undefined */
console.log(divisionResult); // ==> undefined

52
Q

Functions:
What should be considered when naming functions?

A
  • Use camelCase method
  • start with a verb to show what it is doing
  • don’t add special characters like - or _
53
Q

Data Type Array:
What is meant by an array?

A

Array is a data type that allows us to store a collection of (mixed), ordered elements together in one variable.

The values stored in an array can be of any data type: strings, numbers, booleans, objects and even other arrays.

54
Q

Data Type Array:
How can you create an array?

A

You can create an array literal by using [], and then adding values, separated by a ,

CODE:
let pets = [“dog”, “cat”, “bird”];

55
Q

Data Type Array:
How can you check the amount of variables stored in an array.
How can you access different variables of the array?

A

In order to find out how many variables are stored in an array you can use the array method .length

EXAMPLE:
let pets = [“dog”, “cat”, “bird”];
console.log(pets.length) // => 3

An array element can be accessed by its index (because arrays are oredered). Attention, array index starts with 0. When an element that does not exist tried to be accessed it will return the value ‘undefined’

EXAMPLE:
let pets = [“dog”, “cat”, “bird”];
console.log(pets[0]) // => “dog”
console.log(pets[2]) // => “bird”

console.log(pets[3]) // => undefined

56
Q

Data Type Array:
How can you easily access the last element of an array?

A

By using the “array.length-1” term.

EXAMPLE:
EXAMPLE:
let pets = [“dog”, “cat”, “bird”];
let lastIndex = pets.length-1
console.log(pets[lastIndex]) // => “bird”

57
Q

Data Type Array:
Name ways how to add and remove elements from an array

A

Adding elements:
- at the end by array.push(element)
- at the beginning by array.unshift(element)

Removing elements:
- at the end by array.pop()
- at the beginning by array.shift()

However, when you want to store the element you remove from beginning or end you should store that in a variable

EXAMPLE:
let pets = [“dog”, “cat”, “bird”];

const lastPet = pets.pop()
const firstPet = pets.shift()

When you want to add or remove an element at any position use the method .splice() with:

1) first argument: the index position from which you want to start deleting or adding elements, note when you add this will be the index of the first argument added.

2) second argument: specify how many items will be deleted. If this argument is 0, it will simply not remove anything,

3) third argument (optional): specify an item that will be added at the position specified in the first argument. If the argument isn’t provided, nothing will be added to the array.

Important: splice() just modfies the original array, when you add sth you can not assign the modified array with added elements to a new variable.

EXAMPLE:
const students = [‘Amy’, ‘Bob’, ‘Chloe’, ‘Dan’, ‘Eva’];
let a = students.splice(3,0, “Susanna”, “Peter”, “Marie”) // <= empty array
console.log(a)
Will return an empty array

58
Q

Data Type Arrays:
What does ‘iterating through an array’ mean?
How can you do it?

A

Iterating through an array means: use the loop to go through the array and do something with each element of the array. Another name for this is “Looping through an array”.

By using the for-loop:

const students = [‘Amy’, ‘Bob’, ‘Chloe’, ‘Dan’, ‘Eva’];

for (let i = 0; i < students.length; i++){
const element = students[i];
console.log(students[${i}], element);
}

By using the while-loop:
const students = [‘Amy’, ‘Bob’, ‘Chloe’, ‘Dan’, ‘Eva’];

let i = 0;
while (i < students.length) {
console.log(The ${i+1}. element of the array is, students[i]);
i++;
}

NOTE TO SETUP
1) The counter should start at 0, like: let i = 0;. This corresponds to the array’s first element index.

2) The end condition should use the array’s length, like: i < array.length. This corresponds to the last element in the array.

3) Use the counter value i to access each array element, like: array[i]

59
Q

Data Type Objects:
What is an object in javaScript?

A

An object is a unordered data structure, i.e. a collection of properties stored together in one variable, where each property consists of a key-value pair.

An object is represented by a set of curly braces {}.

Each property, or key-value pair, consists of the following:
1) key is the name of a property; also called a property name.
2) value is the content associated with the key.

A property, or key-value pair, of an object acts as a variable stored in the object. Object properties are basically the same as regular JavaScript variables, except they are contained within objects.

Each key, or a property name, is unique in one object. This means an object can’t have two keys with the same name.

60
Q

Data Type Objects:
How can you create an object?

A

An empty one:
const objectName = { };

One with properties:
const objectName = {
myText: “abc”,
myNum: 123
};

An object can also store other objects.

61
Q

Data Type Objects:
How can you access a property of an object?

A

You can access a value of a key via the

1) Dot notation
Syntax: objectName.key

2) Bracket Notation
Syntax: objectName[“key”]

The bracket notation has the benefit that we can use the values stored in variables as property names (more dynamic objects), that wouldn t be possible for dot notation.

Dot notation is more useful for fixed and less dynamic objects, where you know the property beforehand already.

62
Q

Data Types Objects:
How can you add a property to an object?

A

To add a new property to an existing object, write a new property name (key) you wish to add, and assign it a value. You may use either dot notation or bracket notation.

EXAMPLE:
student3.lastName = “Ray”;
student3[“lastName”] = “Ray”;

63
Q

Data Types Objects:
How can you update a property of an object?

A

To update a property of an object, specify the name (key) of the property (key) you wish to update, and assign it a new value. You may use either dot notation or bracket notation

EXAMPLE:
student3.city = “London”;
student3[“city”] = “London”;

64
Q

Data Types Objects:
How can you delete an object property?

A

To remove a property existing on an object, use the operator delete, followed by the name of the object and the property you want to delete.

delete student3.city;

65
Q

Data Types Objects:
How can you list all keys of an object?

A

You can use the object method Object.keys() like
Object.keys(objectName)

The method returns an array with all the keys of the object.

Once you have the array, you can use a for or while loop as seen in the previous lesson, to iterate over the elements and do whatever you please, like listing the values, updating, or even deleting them.

66
Q

Data Types Objects:
How can you list all values of an object?

A

You can use the object method Object.values() like
Object.values(objectName);

The method returns an array with all the values of the object. Once you have the array with values, you can iterate over it using either a for or a while loop.

67
Q
A