Scripting Week 5

studied byStudied by 0 people
0.0(0)
learn
LearnA personalized and smart learning plan
exam
Practice TestTake a test on your terms and definitions
spaced repetition
Spaced RepetitionScientifically backed study method
heart puzzle
Matching GameHow quick can you match all your cards?
flashcards
FlashcardsStudy terms and definitions

1 / 101

flashcard set

Earn XP

Description and Tags

(INCOMPLETE) note on Fri Mar 7 -- Only made flashcards on Lec1 of Week5

102 Terms

1

T or F: JavaScript is the most used scripting/programming language in the world.

True

New cards
2

Name the 3 core technologies of the World Wide Web.

HTML, CSS, JavaScript

New cards
3

JavaScript is primarily used to do what?

Create dynamic & interactive content on websites.

New cards
4

JS was created by ___________ at __________ in 1995.

JS was created by Brendan Eich at Netscape in 1995.

New cards
5

T or F: JS was originally called “Mocha”

True

New cards
6

T or F: JavaScript was named partly to capitalize on the popularity of Java at the time of JS’s release.

True

New cards
7

T or F: Java & JavaScript are not the same languages, but are directly related.

False. Java & JavaScript are NOT related.

New cards
8

Briefly describe JavaScript.

  • Scripting language (also considering a programming language)

    • High-level

    • Dynamic

    • Interpreted

  • Primarily used for web development

    • Web developers use JS to add interactive & dynamic content to their web pages

  • Can be used on client/browser end (front end) & the server (back end)

New cards
9

Is JavaScript an interpreted or compiled language? Justify your answer in one sentence.

JS is an interpreted language

  • Unlike compiled languages, JS scripts are interpreted/executed directly w/o intermediate steps

New cards
10

“JavaScript is a full stack programming language”.

Explain what this means in detail.

(Hint: Think ‘front-end’ & ‘back-end’)

A full-stack programming language is a versatile language that can be used for coding both client-side and server-side of web development.

  • Using one single language on both ends simplifies the development process of web pages as the developer only has to use one language to develop an entire web application

Client/Browser Side (Front End):

  • JS code runs directly in user’s web browser

  • JS is used to create interactive & dynamic web pages

  • For e.g: Interactive maps (like GoogleMaps)

Server-Side (Back End)

  • JS can also run on the server (through environments like Node.js or V8)

  • It handles server-side tasks (e.g. transmitting web pages to clients, database interactions, user authentication)

New cards
11

Describe the relationship JavaScript has with the following environments. Also discuss the role they play in web development.

(a) Node.Js

(b) V8

(a) Node.JS

  • Runtime environment

  • Allows JS to run outside of web browser

  • Uses V8 engine to execute JS on server’s side

  • Essentially extends JS’s capabilities by making it possible to handle server-side operations

    • E.g. reading/writing files, managing databases, serving HTTP requests

(b) V8

  • JavaScript Engine developed by Google

  • Converts JS into machine code super quickly

  • Ensures JS runs efficiently in web browsers (e.g. Google Chrome)

New cards
12

T or F: Node.Js is a JavaScript engine that depends on the runtime environment V8 to execute JavaScript on the server side.

False.

V8 —> JavaScript engine that converts JavaScript into machine super quickly, so that it can run efficiently on web browsers

Node.Js —> Runtime environment that depends on V8 to execute JavaScript on server-side

New cards
13

T or F: JavaScript is a programming language.

True. However, it is specifically used for scripting.

New cards
14

T or F: JavaScript is used primarily for web development, whereas Java is used for several uses, from mobile to enterprise systems..

True

New cards
15

Provide a brief history of JavaScript versions over the years.

(From JavaScript 1.0 to 1.3)

JS 1.0

  • Debuted in Netscape (1995)

  • Simple scripting language

  • Introduced ability to add interactive elements to websites

JS 1.1

  • Introduced API enhancements

JS 1.2

  • Introduced new control statements & array methods

JS 1.3

  • Aligned more closely w/ ECMAScript

New cards
16

(a) Define API

(b) How does it benefit web developers?

(a) Define API

  • API = Application Programming Interface

  • Set of rules & protocols that allows diff software applications to communicate w/ each other

(b) How does it benefit web developers?

  • Makes it easier for developers to integrate & use services from different applications w/o having to write all the code from scratch

New cards
17

___________ is the official standardization of JavaScript.

ECMAScript is the official standardization of JavaScript.

New cards
18

DOM stands for…

Document Object Model

New cards
19

(a) What is DOM manipulation?

(b) How is it achieved?

(c) What is its purpose?

(a) What is DOM manipulation?

Dynamically changing an HTML document or CSS styling sheet using JS.

(b) How is it achieved?

By adding, removing, or changing elements & attributes.

(c) What is its purpose?

To make web pages more interactive & responsive to user actions (e.g. adding animations onto webpage).

New cards
20

What is “Event Handling” defined as in JavaScript?

  • Refers to waiting for & responding to user events (e.g. button clicks or mouse movements)

  • JS allows you to code a response to these events, enabling interactive web experiences

    • E.g. A button used to submit a form

    • E.g. Hovering over an element might display a tooltip

New cards
21

Asynchronous Requests are typically achieved through…

AJAX (Asychronous JavaScript & XML)

New cards
22

Give an example of an Asynchronous Request

  • Submitting forms in the background

  • Fetching weather data

  • Loading new posts

New cards
23

A button used to submit a form on a webpage is an example of which specific concept in JavaScript.

Event Handling

New cards
24

(a) Define “Data Manipulation”

(b) Why is it beneficial to web developers?

(a) Define “Data Manipulation”

  • Processing & transforming a web application’s data

  • Involves sorting, filtering, organizing the data

(b) Why is it beneficial to web developers?

  • Crucial for use of web page features like search results, product listings, or any other scenario were data needs to be organized in a user-friendly manner

  • Enables easy & efficient handling of data

New cards
25

Imagine you visit a webpage that displays a list of products for sale. The website might allow you to sort and filter these products based on different criteria, like price, category, or user ratings.

What concept/practice is used in JavaScript to be able to do the above?

Data manipulation

New cards
26

T or F: The official standardization of JS is JavaScript 1.0

False.

ECMAScript is the official standardization of JavaScript.

New cards
27

Name 2 examples of how DOM manipulation makes web pages more interactive & user-responsive.

  • Implement interactivity into web designs by changing the style of HTML elements

  • Adding animations on page

  • Enabling real-time updates of the webpage

New cards
28

(a) Define “Asynchronous Request”

(b) What’s its purpose?

(a) Define “Asynchronous Request”

  • A certain way of making a web request w/o block the rest of JS code from running

  • Allows browser to communicate w/ server and load data on webpage simultaneously

(b) What’s its purpose?

  • Allows program to continue doing other things (i.e. running other code) while it waits for a response, rather than waiting until response from client comes back

New cards
29

(a) Define “Single Page Application (SPA)”

(b) What is the relationship between JavaScript & SPAs?

(c) How are SPAs beneficial to web development?

(a) Define “Single Page Application (SPA)”

A web application that loads a single HTML page & dynamically updates that page as the user interactions w/ it.

(b) Why is it beneficial in web development?

  • JS plays a key role in maintain SPAs by handling the..

    • routing

    • data management

    • UI rendering

(c) How are SPAs beneficial to web development?

  • Creates fluid experience

  • Reduces loading times

  • Minimizes server requests

New cards
30

SPAs are a _______ way to create web applications.

SPAs are a powerful way to create web applications.

New cards
31

To open the Deve tools in JavaScript on a browser…

Press CTRL + SHIFT + I

New cards
32

How is console.log used to print multiple items at once?

  • You can use console.log to print multiple items at once by separating them with commas.’

  • Example:

    //INPUT
    let name = "Wande";
    let age = 25;
    let city = "Burlington";

    console.log("Name:", name, "Age:", age, "City:", city);
    //OUTPUT 
    Name: Wande Age: 25 City: Burlington

New cards
33

How is an error message logged to the console?

console.error(‘Error message’);
  • Typically displayed in red to stand out

  • Often used for debugging

New cards
34

How is a warning message logged to the console?

console.warn(‘Warning...’);
  • typically displayed in yellow

New cards
35

The console.error message is similar to the ____________ message.

The console.error message is similar to the console.warn message.

New cards
36

(a) What code is used to display an object as a table in the console?

(b) What is the purpose of doing this?

(a) What code is used to display an object as a table in the console?

console.table takes an object & displays it as a table in the console

(b) What is the purpose of doing this?

It helps to visualize an object’s properties at a glance

New cards
37

What code is used to group multiple console messages together to organize related data that will be logged in a console?

console.group('insert-group-name-here');
//insert multiple console messages/commands here
console.groupEnd();

New cards
38

T or F: Every statement in JavaScript must end in a semi-colon.

False.

It’s recommended to mark the end of each statement with a semicolon for clarity, but JavaScript has a feature called “automatic semicolon insert” (ASI) that allows it to interpret the end of statements w/o semicolons

New cards
39

What does the following line of JS code do?


var style = 'padding: 20px; background-color: black; color: cyan’; console.log('%cRoger', style);

  • 1st line —> Creates a variable style containing CSS properties as a string

  • 2nd line —> Uses the style of string created in 1st line to format the output of ‘Roger’ in the console

New cards
40

Explain how to create & apply styles to console output.

Make sure to specify the syntax that should be used.

  1. Define Your Styles:

    • Create a string containing your CSS styles. You can include properties such as color, font-size, font-weight, etc.

    let style = "color: red; font-size: 16px; font-weight: bold;";
  2. Use %c Specifier:

    • Use console.log with the %c specifier to apply the styles to your text. The %c specifier indicates that the following argument should be styled using the CSS rules provided.

    console.log("%cHello, Wande!", style);
  3. Multiple Styles

    • You can apply different styles to different parts of the output by using multiple %c specifiers.

    console.log("%cHello, %cWande!", "color: blue;", "font-weight: bold; color: green;");

Completed Example in Action:

//INPUT
let greetingStyle = "color: purple; font-size: 20px;";
let nameStyle = "font-weight: bold; color: orange;";
console.log("%cHello, %cWande!", greetingStyle, nameStyle);
//OUTPUT
This will display "Hello, Wande!" in the console with "Hello," styled in purple and "Wande!" styled in bold orange.

New cards
41

How do you apply multiple styles to different part of console output?

You can apply different styles to different parts of the output by using multiple %c specifiers.

console.log("%cHello, %cWande!", "", "font-weight: bold; ");

New cards
42

How do you make a…

(a) Multi-line comment in JavaScript?

(b) A single-line comment in JavaScript?

(a) Multi-line comment in JavaScript?

/*
This is a multi-line comment
Blah Blah Bla
*/

(b) A single-line comment in JavaScript?

Using double forward slashes

//This is a single line comment 

New cards
43

Define each of the following terms/concepts (in context of JS data values):

(a) Scope

(b) Hoisting

(c ) Re-declaration

(d) Re-assignment

(a) Scope —> Refers to context in which a variable is defined & is accesible

(b) Hoisting —> Refers to JavaScript’s default behaviour of moving variable declarations to the top of their containing scope before code execution

(c ) Re-declaration —> Act of declaring a variable with the same name more than once w/in the same scope

(d) Re-assignment —> Act of assigning a new value to a variable that’s already been declared

New cards
44

The use of _________ in JS allows you as the programmer to use variables & functions in a program before they are actually declared in the code.

The use of hoisting in JS allows you as the programmer to use variables & functions in a program before they are actually declared in the code.

New cards
45

Describe each of the following for the data value Var .

(a) Scope

(b) Hoisting

(c) Re-declaration

(d) Re-assignment

Describe each of the following for the data value Var .

(a) Scope

  • If declared w/in a function —> Function Scope

  • If declared outside of a function —> Global Scope

(b) Hoisting

Variables declared w/ var are hoisted to the top of their scope, initialized w/ a value or are undefined.

(c) Re-declaration

  • Allowed

  • Same variable can be declared multiple times using Var

(d) Re-assignment

  • Not allowed

  • Variables declared w/ Var cannot be re-assigned

New cards
46

Describe each of the following for the data value let .

(a) Scope

(b) Hoisting

(c) Re-declaration

(d) Re-assignment

Describe each of the following for the data value let .

(a) Scope

  • Block scope —> A block is anything b/w (contained) w/in curly brackets

(b) Hoisting

Variables declared with ‘let’ are also hoisted but not initialized, meaning they’re in a “temporal dead zone” from the start of the block until the declaration is evaluated.

(c) Re-declaration

  • Not allowed

  • You cannot Re-declare the same variable w/in the same scope of using let

(d) Re-assignment

  • Not allowed

  • Variables declared w/ let cannot be re-assigned

New cards
47

Describe each of the following for the data value const .

(a) Scope

(b) Hoisting

(c) Re-declaration

(d) Re-assignment

Describe each of the following for the data value const .

(a) Scope

  • Block scope

(b) Hoisting

  • Const variable declarations are hoisted but not initialized

(c) Re-declaration

  • Not allowed (when variable is w/in same scope as the const you are going to create)

(d) Re-assignment

  • Variables declared w/ const cannot be re-assigned

    • They must be initialized at time of declaration

New cards
48

What important update to TESLA vehicles was made in 2015?

The introduction of let and const in ES6 (ECMAScript 2015) was a significant update because it allowed for more predictable behaviour compared to var, especially with block scope, which reduces the chance of bugs due to variable scope issues. In modern JavaScript, it's generally recommended to use let and const over var to declare variables, as they provide a clearer scope and more predictable behaviour. const is often used for variables that should not change, while let is used for variables that may change over time.

New cards
49

Name & describe the primitive types of data values in JS.

Provide an example of each data type.

New cards
50

Where are primitive data types stored in JS?

Primitive data types in JS are stored directly in the memory location the variable accesses.

New cards
51

T or F: Primitive types in JS are immutable, meaning it cannot be altered.

True

New cards
52

Roughly describes what occurs in memory when you…

(a) Manipulate a primitive value type.

(b) When you assign a primitive value to a variable.

(c) When you re-assign the same value to another variable.

(a) When you manipulate a primitive type, you work directly on its value.

(b) When you assign a primitive value to a variable, it's like giving that variable a box with the value inside it.

© If you assign this value to another variable, it copies it into a new box.

New cards
53

Name & describe the reference types of data values in JS.

Provide an example of each reference type.

New cards
54

Compare and contrast primitive & reference data types in JS?

Primitive Data Types

  • Def: Basic immutable data types that store values directly in memory

  • Types: string, number, boolean, null, undefined, symbol, and bigint

  • Characteristics:

    • Immutability: Once a primitive value is created, it cannot be changed.

    • Storage: Values are stored directly in the variable.

//Example (of primitive data types in memory) 

let x = 10;
let y = x; // y is a copy of x
x = 20;
console.log(y); // Output: 10 (y remains unchanged)

Reference Data Types

  • Def: Complex data types that store a reference (memory address) to the variable, rather than the value itself

  • Types: Object (including arrays & functions)

  • Characteristics:

    • Mutability: Values can be changed even after the reference is created.

    • Storage: Variables hold a reference to the actual value stored in memory.

let obj1 = { name: "Wande" };
let obj2 = obj1; // obj2 is a reference to the same object as obj1
obj1.name = "John";
console.log(obj2.name); // Output: John (obj2 reflects the change)

New cards
55

Name & briefly describe the key differences b/w Primitive data types & Reference data types in JS.

Key Differences:

  1. Storage: Primitives store actual values, while reference types store references to values.

  2. Immutability: Primitives are immutable, whereas reference types can be changed.

  3. Behavior: Copying a primitive creates a new value, whereas copying a reference type creates a reference to the same object.

New cards
56

Name & briefly describe each of the 5 arithmetic operators used in JS.

New cards
57

Name & describe the 6 incremental operators used in JS.

New cards
58

Define the following. Provide a sample code for each.

(a) Pre-Increment

(b) Post-Increment

Pre-increment (++variable)

Increments the variable first and then returns the new value.

let a = 5;
console.log(++a); // Output: 6 (pre-increment: increments first, then returns new value)
console.log(a); // Output: 6

Post-Increment (variable++)

Returns the current value of the variable first and then increments the variable.

let b = 5;
console.log(b++); // Output: 5 (post-increment: returns current value, then increments)
console.log(b); // Output: 6

New cards
59

Define the following. Provide a sample code for each.

(a) Pre-Decrement

(b) Post-Decrement

Define the following. Provide a sample code for each.

(a) Pre-Decrement (--variable)

Decrements the variable first and then returns the new value.

let c = 5;
console.log(--c); // Output: 4 (pre-decrement: decrements first, then returns new value)
console.log(c); // Output: 4

(b) Post-Decrement( variable--)

Returns the current value of the variable first and then decrements the variable.

let d = 5;
console.log(d--); // Output: 5 (post-decrement: returns current value, then decrements)
console.log(d); // Output: 4

New cards
60

In one simple sentence, explain the difference between Pre-increment/decrement and Post-increment/decrement.

  • Pre-increment/decrement: Changes the value first and then returns the new value.

  • Post-increment/decrement: Returns the current value first and then changes the value.

New cards
61

(a) What is addition assignment?

(b) What operator is used to do this?

(c) Provide a sample code that demonstrates its function.

(a) What is addition assignment?

  • Adding the value of the right operand to the variable on the left

  • Then re-assigning the sum to the variable

(b) What operator is used to do this?

  • +=

(c) Provide a sample code that demonstrates its function.

//INPUT
let days = 10;
c += 3;

//OUTPUT is 13

New cards
62
//INPUT
let x = 10;
let y = 5;
let z = x + y;
y--;

What would the output of the code above be? Briefly explain your answer.

Output is 15

Line-by-line breakdown:

  • variable ‘x’ is initialized to value of 10

  • variable ‘y’ is initialized to value of 5

  • variable ‘z’ is initialized to value of x+y, which is 10 + 5

    • so ‘z’ is 15

  • current value of ‘z’ (15) is assigned to the variable ‘result’

  • result is set to 15 (current value of z before decrement)

  • then ‘z’ is decremented to 14

The output is 15 because the type of decrement that occurs is post-decrement (meaning the current value of the variable is returned first & then decremented).

New cards
63
//INPUT
let a = 30
a++
console.log(a)

What is the output of the code above?

Output is 31

New cards
64
let x = 3;
let y = ++x;
console.log(x);
console.log(y);

What is the output of the code above?

  • x is initially 3.

  • y = ++x increments x by 1 first, then assigns the new value of x (which is 4) to y.

  • So, x becomes 4, and y is 4.

  • Output: 4 and 4.

New cards
65
let p = 10;
let q = p--;
let r = --q;
console.log(p);
console.log(q);
console.log(r);

What is the output of the code above?

  • p is initially 10.

  • q = p-- assigns the current value of p (which is 10) to q, then decrements p by 1.

  • So, p becomes 9, and q is 10.

  • r = --q decrements q by 1 first, then assigns the new value of q (which is 9) to r.

  • Output: p is 9, q is 9, and r is 9.

New cards
66
let x = 5;
let y = x-- + ++x + x++ - --x;
console.log(x);
console.log(y);

What is the output of the code above?

let x = 5;
let y = x-- + ++x + x++ - --x;
console.log(x);
console.log(y);

New cards
67

(a) Define “Concatenation” in a single sentence.

(b) Which operator is used to perform concatenation?

(a) Concatenation is the process of joining two or more strings together to form a single string.

(b) Concatenation is performed using the addition operator.

New cards
68

(a) What are “Template Literals”?

(b) Why are the beneficial for coding in JavaScript?

(a) What are “Template Literals”?

  • Template Literals = String interpolation

  • Features in JS that allows for easy string interpolation (i.e. “ “ & $)

(b) Why are the beneficial for coding in JavaScript?

Makes it easier to embed variables & expressions w/in strings.

New cards
69

When determine which type of loop to use in a program, it is helpful to associate the word “iterating” with ______ loops and the word “repeating” with ______ loops.

When determine which type of loop to use in a program, it is helpful to associate the word “iterating” with for loops and the word “repeating” with while loops.

New cards
70
New cards
71

In code, when you want to perform different actions/have different outcomes for different user decisions, you should use…

Conditional statements

New cards
72

Name & describe the 4 types of conditional statements used in JavaScript.

if

Usage: Specifies a block of code to be executed if condition is true.

if (condition) {
// Code to be executed if the condition is true
}

else

Usage: Specifies a block of code to be executed if condition in preceding if block is false.

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

else if

Usage: Specifies a new condition to test if the preceding if condition is false.

if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}

switch

Usage: Specifies many alternative blocks of code to be executed based on different possible values of an expression.

switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
default:
// Code to be executed if expression doesn't match any value
}

New cards
73

When are JavaScript loops (in general) helpful?

If you want to run the same code over and over again, each time with a different value.

New cards
74

Arrays are commonly iterated through using ________ loops.

Arrays are commonly iterated through using for/of loops.

New cards
75

Observe the code below.


text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

How would I use loops in JS to re-write this code so that it performs the same function, but only requires a few lines of the program?

for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}

New cards
76

Name & describe the 6 types of loops JavaScript supports.

  1. For — loops through a block of code a number of times

  1. for/in — loops through the properties of an object

  1. for/of — loops through the values of an iterable object (e.g. array)

  2. while — loops through a block of code while a specified condition is true

  1. do/while — also loops through a block of code while a specified condition is true

New cards
77

Describe the format/syntax of a for statement.

(Hint: ICU)

for (initialization, condition, update) {
//enter code here
}

a for statement creates a loop w/ 3 optional expressions:

Initialization — Sets the initial value of the loop control variable

Condition — The loop continues as long as this condition is true

Update — Updates the loop control variable after each iteration

**Helpful way to remember this is “ICU

Example:

for (let i = 0; i < 5; i++) {
console.log(i);
}

// Initialization: let i = 0
// Condition: i < 5
// Update: i++

New cards
78

T or F: All three expressions with a for statement are optional.

True

New cards
79

When can expression 1 (the initialization expression) of a for statement be omitted?

When you initialize the values that will be used in for loop directly before the loop starts.

Example:

let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}

New cards
80

T or F: You can initiate several values in expression 1 (initialization statement) of a for loop.

True. This is done by separating each individual value w/ a comma.

Example:

for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

New cards
81

What is the function of the 2nd expression in a for statement?

The 2nd expression in a for statement is used to evaluate the condition of the initial variable.

New cards
82

What happens when the 2nd expression in a for statement returns the value…

(a) True

(b) False

(a) If expression 2 in a for statement returns the value True

  • The loop will start over again

(b) If expression 2 in a for statement returns the value False

  • The loop will end

New cards
83

If you choose to omit the 2nd expression in a for statement, what must you do? Why?

  • Include a break inside of the loop.

  • If you don’t —> the loop will never end causing the browser to crash

New cards
84

What is the function of the 3rd expression in a for statement?

  • Expression 3 increments the value of the initial variable

New cards
85

Using var v.s. let in for statements

using var —> the variable declared in the loop redeclares the variable outside of the loop

using let —> the variable declared in the loop does not redeclare the variable outside the loop

—> therefore the variable will only be visible w/in the loop

New cards
86

for/in loop

(a) What does the ‘for in’ statement do?

(b) What’s its syntax?

(c) Provide a sample code and explain it.

(a) What does the ‘for in’ statement do?

Loops through the properties of an Object.

Loops through the properties of an Array.

(b) What’s its syntax?

//FOR/IN USED FOR AN OBJECT
for (key in object) {
// code block to be executed
}
//FOR/IN USED FOR AN ARRAY
for (variable in array) {
// code block to be executed
}

(c) Provide a sample code.

//EXAMPLE: FOR/IN LOOP USED FOR OBJECT
const person = {fname:"John", lname:"Doe", age:25};

let text = "";
for (let x in person) {
text += person[x];
}
//EXAMPLE: FOR/IN LOOP USED FOR AN ARRAY
const numbers = [45, 4, 9, 16, 25];

let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
  • The for in loop iterates over a person object

  • Each iteration returns a key (x)

  • The key is used to access the value of the key

  • The value of the key is person[x]

New cards
87

When should you NOT use a for/in loop for an array?

What should you use instead?

If the index order in the array is important.

Instead use a ‘for’ loop or ‘for of’ loop.

New cards
88

(a) What does the forEach() method do to arrays?

(b) Describe syntax to be used.

(c) Demonstrate with a sample code.

(a) What does the forEach() method do to arrays?.

The forEach() method calls a function (a callback function) once for each array element.

(b) Describe syntax to be used.

array_name.forEach(myFunction)

Note that ‘myFunction) takes 3 arguments:

  • The item value

  • The item index

  • The array itself

(c) Demonstrate with a sample code

const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {
txt += value;
}

New cards
89

Functions in JS take _____ arguments. They are the _____ value, _____ index, and _____.

Functions in JS take three arguments. They are the item value, item index, and array.

New cards
90

New cards
91

for/of loop

(a) What does the ‘for of’ statement do?

(b) What’s its syntax?

(c) Provide a sample code and explain it.

(a) What does the ‘for of’ statement do?

  • The JavaScript for of statement loops through the values of an iterable object.

  • It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.

(b) What’s its syntax?

for (variable of iterable) {
// code block to be executed
}

(c) Provide a sample code and explain it.

//EXAMPLE 1
const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let x of cars) {
text += x;
}
//EXAMPLE 2
let language = "JavaScript";

let text = "";
for (let x of language) {
text += x;
}

New cards
92

What does a while loop do?

The while loop loops through a block of code as long as a specified condition is true.

New cards
93
while (i < 10) {
text += "The number is " + i;
i++;
}

Describe what this code does.

the code in the loop will run, over and over again, as long as a variable (i) is less than 10

New cards
94

(a) Describe what the ‘do while’ statement does?

(b) What’s its syntax?

(c) Demonstrate with a sample code.

(a) Describe what the ‘do while’ statement does?

  • ‘Do while’ loop is a variant of the while loop

  • Loop executes the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

(b) What’s its syntax?

do {
// code block to be executed
}
while (condition);

(c) Demonstrate with a sample code.

do {
text += "The number is " + i;
i++;
}
while (i < 10);

New cards
95

If you forget to increase the variable used in a condition loop, the loop will…

New cards
96
New cards
97

(a) Define “While Loop”

New cards
98

while (i < 10) {
text += "The number is " + i;
i++;
}

Provide a short description of what is occurring in the code above.

In the example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:

New cards
99

When using a While Loop, if you forget to increase the variable used in teh condition, what will happen?

The loop will never end. This will crash your browser.

New cards
100
New cards
robot