Javascript Basics Flashcards

1
Q

*

Explain this JS code? And what output will it give?

var name = "Sethu";
alert(`Hi, ${name}. Want to see something cool?`);
document.querySelector('html').innerHTML = `
  <h1>Welcome to ${name}'s site!</h1>
  <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif">
`;
A

This JavaScript code consists of three main parts. Let’s break it down:

  1. Variable Declaration and Initialization:
    javascript
    var name = "Sethu";

    Here, a variable name is declared using the var keyword and initialized with the string value "Sethu". This variable is used to store the name that will be used later in the code.
  2. Alert Dialog:
    javascript
    alert(`Hi, ${name}. Want to see something cool?`);

    This line displays an alert dialog box to the user. It uses a template literal (indicated by backticks `) to embed the value of the name variable within the string. So, the message in the alert will be: “Hi, Sethu. Want to see something cool?”.
  3. Modifying HTML Content:
    ```javascript
    document.querySelector(‘html’).innerHTML = `<h1>Welcome to ${name}'s site!</h1><img></img>
    ; ``
    This part of the code selects the entire HTML document (document.querySelector('html')) and sets its innerHTML to a new block of HTML code. This new HTML includes:
    • An <h1> heading: “Welcome to Sethu’s site!” (again using a template literal to insert the name).
    • An <img> tag: This embeds an image from the specified URL (a GIF from giphy.com).

The output of this code when run in a web browser environment would be:
1. First, an alert box appears with the message “Hi, Sethu. Want to see something cool?”.
2. After closing the alert, the entire HTML content of the page will be replaced with the new content, displaying a heading that says “Welcome to Sethu’s site!” and the specified GIF image underneath.

Note: The use of document.querySelector('html').innerHTML to replace the entire HTML content is quite drastic and would remove any existing content and scripts on the page. It’s generally not a recommended practice for dynamically updating content on web pages, especially for larger applications.

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

Now explain the following code and what it does?

var name = prompt("What is your name?");
alert(`Hi, ${name}. Want to see something cool?`);
document.querySelector('html').innerHTML = `
  <h1>Welcome to ${name}'s site!</h1>
  <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif">
`;
A

This JavaScript code interacts with the user and then dynamically updates the content of the web page. Let’s break down its functionality:

  1. Prompt for User’s Name:
    javascript
    var name = prompt("What is your name?");

    This line displays a prompt dialog box asking the user “What is your name?”. The user’s input is then stored in the variable name. If the user enters their name, it will be saved in this variable. If the user cancels the prompt, name will be null.
  2. Alert Dialog:
    javascript
    alert(`Hi, ${name}. Want to see something cool?`);

    This line shows an alert dialog box with a message that includes the user’s inputted name. For instance, if the user entered “John”, the message will be: “Hi, John. Want to see something cool?”. If name is null, the message will be “Hi, . Want to see something cool?”.
  3. Modifying HTML Content:
    ```javascript
    document.querySelector(‘html’).innerHTML = `<h1>Welcome to ${name}'s site!</h1><img></img>
    ; ``
    This part of the code selects the entire HTML document (document.querySelector('html')) and replaces its innerHTML with new content. The new HTML includes:
    • An <h1> heading: “Welcome to [user’s name]’s site!” (the user’s name is inserted using a template literal).
    • An <img> tag: This includes an image (a GIF from giphy.com).

Overall Behavior: When this script is run in a web browser:
1. It first asks the user for their name through a prompt dialog.
2. Once the name is entered (or if the prompt is canceled), an alert dialog appears with a personalized greeting.
3. After closing the alert, the entire HTML content of the page is replaced with a new heading that welcomes the user to their own site (using the entered name) and displays a GIF image.

Note: As with the previous code, replacing the entire HTML content with document.querySelector('html').innerHTML is an extreme way to update a page and will remove all existing content and scripts. It’s usually better to update or add to existing content rather than replacing everything, especially in more complex web applications.

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

What is the short-cut key to open console in Mac to run javascript code on web-browser?

A

To open the JavaScript console in most web browsers on both Mac and Windows, you can use the following shortcut keys:

  • On Windows: Press Ctrl + Shift + J. Alternatively, you can press F12 to open the developer tools and then navigate to the “Console” tab.
  • On Mac: Press Command + Option + J.

These shortcuts typically open the developer tools directly to the console tab, where you can write and execute JavaScript code. The exact behavior might vary slightly depending on the browser you are using (like Chrome, Firefox, Safari, etc.).

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

What is Syntax (in Javascript)?

A

Syntax in JavaScript, as in any programming language, refers to the set of rules that defines the combinations of symbols that are considered to be correctly structured programs in that language. These rules dictate how you can write statements, expressions, and other code elements in JavaScript. The syntax covers various aspects of JavaScript programming, such as:

  1. Variables and Data Types: Declaring variables using var, let, const, and assigning values to them. JavaScript is a dynamically typed language, so you don’t need to specify data types explicitly.
  2. Operators: Using arithmetic, comparison, logical, assignment, and other types of operators.
  3. Control Structures: Includes if...else statements, switch cases, loops like for, while, do...while.
  4. Functions: Defining and invoking functions, function expressions, arrow functions, and understanding scope and closures.
  5. Objects and Arrays: Syntax for creating objects and arrays, accessing and modifying their elements, methods for iteration and manipulation.
  6. Classes and Modules: Modern JavaScript supports class-based object-oriented programming and modules for code organization.
  7. Exception Handling: Using try...catch blocks for error handling.
  8. Asynchronous Programming: Syntax for Promises, async functions, and the await keyword.

Following the correct syntax is crucial for the JavaScript interpreter to understand and execute the code. Errors in syntax typically result in syntax errors, which stop the execution of the script.

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

What does “syntax” mean?

A

Syntax is like the vocabulary and grammar of a programming language. It’s a langauge’s words and commands as well as the instructions for putting them together to create a program.

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

*

Can you use JavaScript on a web server?

A

Yes, you can use JavaScript on a web server, primarily through Node.js. Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

Here’s how JavaScript, through Node.js, is used on a web server:

  1. Server-Side Scripting: You can write server-side code in JavaScript to handle tasks like database operations, file manipulation, and server logic.
  2. Building APIs: Node.js is commonly used for building RESTful APIs that can handle requests and responses in JSON format, making it ideal for web services and integrations.
  3. Real-Time Applications: With its non-blocking, event-driven architecture, Node.js is well-suited for real-time applications like chat applications, live updates, and collaborative tools.
  4. Working with Databases: Node.js can interact with SQL (like MySQL, PostgreSQL) and NoSQL (like MongoDB) databases, enabling you to build complex, data-driven websites and applications.
  5. NPM (Node Package Manager): NPM is a huge ecosystem of open-source libraries and tools, making it easy to extend the functionality of your Node.js applications with pre-built packages.
  6. Framework Support: There are numerous frameworks, like Express.js, Koa.js, and Hapi, which simplify the process of developing web applications and APIs.
  7. Streaming Data: Node.js can handle streaming data, making it a good choice for applications like video streaming services.
  8. Handling Concurrent Requests: Due to its asynchronous nature, Node.js can handle numerous concurrent connections, which is beneficial for high-traffic applications.

The use of JavaScript on both the client-side (in the browser) and the server-side (with Node.js) enables full-stack development with a single programming language, simplifying the development process and reducing the need to context-switch between languages.

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

A quick way to run JavaScript is in the web browser’s developer tools, using a tool called:

A

A quick way to run JavaScript in a web browser is by using the browser’s built-in “Console”. The Console is a part of the web browser’s developer tools and provides an environment where you can write, test, and debug JavaScript code directly within the browser.

Here’s how you can access and use the Console in most modern web browsers:

  1. Accessing the Console:
    • In Google Chrome, Mozilla Firefox, or Microsoft Edge, you can open the Console by pressing Ctrl + Shift + J (on Windows/Linux) or Cmd + Option + J (on macOS).
    • In Safari, you first need to enable the Developer menu by going to Safari’s Preferences, then Advanced, and checking the “Show Develop menu in menu bar” option. After that, you can access the Console by pressing Cmd + Option + C.
  2. Using the Console:
    • Once the Console is open, you can type JavaScript code directly into it and press Enter to execute the code.
    • The Console displays the results of executed scripts, and you can interact with the current page’s JavaScript environment.
    • It’s also a useful tool for debugging, as you can view errors and log messages from your webpage’s scripts.

The Console is an invaluable tool for developers for quick experimentation with JavaScript code, debugging, and understanding the behavior of web pages.

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

Explain the following line of codes in JS:

alert();
alert("hello world");
console.log("hello world!");
document.write();
document.write("Welcome to my webpage");
A

Sure, let’s break down these lines of JavaScript code:

  1. alert();
    • This line calls the alert function without any arguments. In a web browser, this would typically display a popup dialog box with no message, just an “OK” button for the user to close it.
  2. alert("hello world");
    • This line also calls the alert function but this time with a string argument "hello world". This will display a popup dialog box with the message “hello world”.
  3. console.log("hello world!");
    • This line uses the console.log method to print the string "hello world!" to the web browser’s console. This is a very useful tool for debugging, as it allows developers to see output and errors in the browser’s developer tools.
  4. document.write();
    • This line calls document.write with no arguments. This method writes directly to the HTML document. If called without arguments, it doesn’t alter the document but if called after the document has been fully loaded, it can overwrite the whole document.
  5. document.write("Welcome to my webpage");
    • This line uses document.write with the string "Welcome to my webpage" as an argument. It writes this string directly into the HTML document where the script is running. It’s generally recommended to manipulate the DOM using other methods like innerHTML or DOM manipulation functions, as document.write can have some undesirable effects, especially if used after the document has finished loading.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explain the following code written in Google Chrome Console:

alert("Hello, Thanks for Visiting!");
console.log("Hello from the Console");
document.write("<h1>Welcome to my page</h1>");
A

The code you’ve provided is a small script written in JavaScript, which can be executed in the Google Chrome Console. Here’s a breakdown of what each line does:

  1. alert("Hello, Thanks for Visiting!");
    This line of code creates a pop-up alert box in the browser with the message “Hello, Thanks for Visiting!”. The alert() function is a simple way to display information to the user and requires them to click ‘OK’ to proceed.
  2. console.log("Hello from the Console");
    This command prints the message “Hello from the Console” to the browser’s console. This is a tool mainly used by developers to log information for debugging purposes. The console is not visible to ordinary users unless they open the browser’s developer tools.
  3. document.write("<h1>Welcome to my page</h1>");
    This line uses the document.write() method to write a string of HTML directly into the HTML document. In this case, it’s adding an <h1> element with the text “Welcome to my page”. It’s important to note that using document.write() on a fully-loaded page will overwrite the current page content, which is why this method is not commonly used in modern web development.

When this script is run in the Google Chrome Console, it will first show an alert box, then print a message in the console, and finally write or overwrite the webpage content with the specified <h1> tag.

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

Folder: css/index.html contains:
~~~
<!DOCTYPE html>

<html>
<head>
<meta></meta>
<title>JavaScript Basics</title>
<link></link>



</head>
<body>
<main>
<h1>Hello, JavaScript!</h1>
<script>
alert("Another message from Index.html");
</script>

</main>
</body>
</html>
Folder: js/script.js contains:

alert(“Hey, you are back for more?”);
~~~

Now explain what happen in above code and how you can use js script within html or create a js script file and link it back to html file?

A

The provided code is an example of how to integrate JavaScript with an HTML file. Here’s a breakdown of what happens and how JavaScript is used within HTML:

HTML File (index.html)

  1. Doctype Declaration: <!DOCTYPE html> specifies the document type and version of HTML. Here, it declares HTML5.
  2. HTML Structure: Basic HTML structure is followed with <html>, <head>, and <body> tags.
  3. Character Set: <meta charset="utf-8"> sets the character encoding to UTF-8, which includes most characters from all known human languages.
  4. Title: <title>JavaScript Basics</title> sets the title of the web page.
  5. Linking CSS: <link href="css/style.css" rel="stylesheet"> links a CSS file (style.css) located in the css folder. This CSS file is used for styling the HTML content.
  6. Linking JavaScript File: <script src="js/script.js"></script> links an external JavaScript file (script.js) located in the js folder. This script will be executed when the HTML page is loaded.
  7. HTML Content: Within the <body>, there’s a <main> tag containing an <h1> header with the text “Hello, JavaScript!”.
  8. Inline JavaScript: Inside the <main> tag, there’s an inline <script> tag with JavaScript code alert("Another message from Index.html");. This script displays an alert dialog box when the HTML content of <main> is rendered.

JavaScript File (script.js)

  • Contains a single line of JavaScript: alert("Hey, you are back for more?");. This script displays an alert dialog box when the HTML page is loaded, as the script is linked in the HTML <head>.

Execution Flow

  1. When the HTML file is loaded in a browser, it parses the HTML structure.
  2. The browser encounters the linked CSS file and applies the styles defined in it.
  3. The browser then encounters the first <script> tag linking to script.js. It loads and executes this script, displaying the alert “Hey, you are back for more?”.
  4. The browser continues to parse the HTML, rendering the main content.
  5. Upon encountering the inline <script> tag, it executes that JavaScript, displaying the alert “Another message from Index.html”.

Using JavaScript in HTML

  1. Inline JavaScript: Directly write JavaScript code within <script> tags in the HTML file, as shown in the inline script in your index.html.
  2. External JavaScript File: Create a separate .js file (like script.js) and link it to your HTML file using <script src="path/to/script.js"></script>. This approach is cleaner and more manageable, especially for larger projects.

By using both methods, you can execute JavaScript when the page loads (external file) and in response to events or specific points in the page’s rendering (inline).

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

Code Challenge:
1. Display an alert dialog with the content: “Warning! This message will self-destruct in”.
2. Display a “3… 2… 1…” countdown using 3 alert dialog boxes.
3. This statement selects the <h1> element and replaces its text with “BOOM!”.
4. Log “Message destroyed!” to the console

A

Answer is:
~~~
// 1. Display an alert dialog with the content: “Warning! This message will self-destruct in”
alert(“Warning! This message will self-destruct in”);

// 2. Display a “3… 2… 1…” countdown using 3 alert dialog boxes
alert(“3…”);
alert(“2…”);
alert(“1…”);

// 3. This statement selects the <h1> element and replaces its text with “BOOM!”.
document.querySelector(“h1”).textContent = “🔥BOOM!🔥”;

// 4. Log “Message destroyed!” to the console
console.log(“Message destroyed!”);
~~~

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

Code Challenge 1: There are two files: index.html and app.js. To run the programming in app.js, you first need to load it into index.html. Add the required HTML to load the external JavaScript file into the web page. Make sure to add your code inside the <body> element.

index.html:
~~~
<!DOCTYPE HTML>

<html>
<head>
<meta></meta>
<title>JavaScript Basics</title>
</head>
<body>

</body>
</html>

~~~

app.js:
blank

Code Challenge 2: Next, in the app.js file, add the code required to print “Begin program” to the browser’s JavaScript console.

Code Challenge 3: Next, write the code for an alert dialog with the message “I am Programming!”.

Code Challenge 4: At the end of the script (after alert()), add the code required to print ‘End program’ to the browser’s JavaScript console.

A

Solution to 1:
index.html:
~~~
<!DOCTYPE HTML>

<html>
<head>
<meta></meta>
<title>JavaScript Basics</title>
</head>
<body>



</body>
</html>
**Solution to 2:**
app.js:

console.log(“Begin Program”);
~~~

Solution to 3:
app.js:
~~~
console.log(“Begin Program”);
alert(“I am Programming!”);
~~~

Solution to 4:
app.js:
~~~
console.log(“Begin Program”);
alert(“I am Programming!”);
console.log(“End program”);
~~~

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

Using the following code explain what is variable in javascript, how it is created and how a value is assigned to a variable and how a new value is re-assigned to a variable:

var message = "Hello!";
console.log(message);
message = "Hello from JavaScript Basics"
console.log(message);
A

In JavaScript, a variable is a storage location that holds data which can be changed during the execution of a program. The provided code snippet illustrates the creation, assignment, and re-assignment of a variable in JavaScript. Let’s break it down:

  1. Creating a Variable and Assigning a Value:
    javascript
    var message = "Hello!";

    • var: This keyword is used to declare a variable in JavaScript. It signals that the identifier that follows is a variable name.
    • message: This is the name of the variable. It’s an identifier chosen by the programmer to refer to the variable. In this case, the variable is named message.
    • =: This is the assignment operator in JavaScript. It is used to assign a value to a variable.
    • "Hello!": This is a string value assigned to the variable message. Strings are a series of characters enclosed in quotes in JavaScript.
  2. Using the Variable:
    javascript
    console.log(message);

    • console.log: This is a function in JavaScript used for printing or logging information to the console. Here, it’s used to output the value of the variable message.
    • message: When used inside console.log, it refers to the value stored in the variable message, which is "Hello!".
  3. Re-assigning a New Value to the Variable:
    javascript
    message = "Hello from JavaScript Basics";
    console.log(message);

    • message = "Hello from JavaScript Basics";: This line re-assigns a new value to the variable message. The old value "Hello!" is replaced with the new value "Hello from JavaScript Basics".
    • console.log(message);: This again prints the current value of message to the console, which is now "Hello from JavaScript Basics".

In summary, a variable in JavaScript is created using a declaration keyword like var, followed by a unique identifier. An initial value is assigned to it using the assignment operator =. The value of the variable can be changed or re-assigned at any point in the program, as shown in your example.

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

Code Challenge 1:
Create a variable named myName. Assign it your name between quotes (a string value).

A
var myName = "Urname";
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

JavaScript has unique words that you can’t use for a variable name, so if you encounter a syntax error when creating a variable, this might be the reason. Give the list of unique words that can’t be used as variable name?

A

In JavaScript, there are certain reserved words that cannot be used as variable names because they serve specific purposes in the language’s syntax or functionality. These reserved words include keywords and future reserved words, which may be used in future versions of JavaScript.

As of my last update in April 2023, here’s a list of these reserved words:

JavaScript Reserved Keywords:

  • abstract
  • arguments
  • await
  • boolean
  • break
  • byte
  • case
  • catch
  • char
  • class
  • const
  • continue
  • debugger
  • default
  • delete
  • do
  • double
  • else
  • enum
  • eval
  • export
  • extends
  • false
  • final
  • finally
  • float
  • for
  • function
  • goto
  • if
  • implements
  • import
  • in
  • instanceof
  • int
  • interface
  • let
  • long
  • native
  • new
  • null
  • package
  • private
  • protected
  • public
  • return
  • short
  • static
  • super
  • switch
  • synchronized
  • this
  • throw
  • throws
  • transient
  • true
  • try
  • typeof
  • var
  • void
  • volatile
  • while
  • with
  • yield

Future Reserved Keywords:

  • async (though now commonly used with async functions)
  • of (though now commonly used in for-of loops)

Please note that while some of these words might now be used in specific contexts (like async, await, and of), they are still reserved and cannot be used as variable names.

Also, JavaScript is continually evolving, and new versions might introduce new reserved words. It’s always a good practice to stay updated with the latest ECMAScript specifications for the most current list of reserved words.

17
Q

What are other rules of naming conveniton of a variable in javascript?

A

When naming variables in JavaScript, it’s important to follow certain rules and conventions to ensure that your code is readable, maintainable, and free from syntax errors. Here are the key rules and best practices for naming variables in JavaScript:

  1. Case Sensitivity: JavaScript is case-sensitive, which means that variableName, VariableName, and VARIABLENAME would be recognized as three different variables.
  2. Start with Letters, Dollar Sign, or Underscore: A variable name must start with a letter (either uppercase or lowercase), a dollar sign ($), or an underscore (_). It cannot start with a number.
  3. No Reserved Words: As previously mentioned, JavaScript reserved keywords cannot be used as variable names.
  4. Letters, Numbers, Dollar Signs, and Underscores Only: After the initial character, variable names can include any combination of letters, numbers, dollar signs ($), and underscores (_). No other characters, including spaces, are allowed.
  5. No Punctuation or Special Characters: Apart from the dollar sign and underscore, other special characters or punctuation marks are not allowed in variable names.
  6. Descriptive Names: Choose names that are descriptive and clearly convey the purpose of the variable. For example, userName or totalAmount are descriptive names, whereas x or y are not (unless used in a mathematical context where such names are conventional).
  7. Camel Case for Multiple Words: When a variable name consists of multiple words, JavaScript convention is to use camelCase. In camelCase, the first word is in lowercase, and each subsequent word starts with an uppercase letter, e.g., myVariableName.
  8. Avoid Abbreviations Unless Commonly Known: Avoid using abbreviations unless they are commonly understood. For example, httpReq is acceptable for an HTTP request, but avoid overly cryptic abbreviations that might confuse others or your future self.
  9. No Numerical Start: Variable names cannot begin with a number. For example, 1variable is invalid, but variable1 is valid.
  10. Avoid Overly Generic Names: Names like data, value, or info are overly generic and do not provide enough context about what the variable represents.
  11. Non-English Characters: While JavaScript supports using Unicode (including non-English characters) in variable names, it’s generally best to stick with the standard ASCII character set to ensure maximum compatibility and readability.

Following these rules and conventions can help make your code more readable and maintainable, and it can prevent syntax errors related to improper variable naming.

18
Q

Quiz

1.1 All of the variable names below are OK to use in a JavaScript program. However, which one is the best choice?

A. var m
B. var_ (underscore)
c. var message
d. var $_

2.2 Which of the following creates a variable named playerName and stores the name “Reggie” in it?

a. variable playerName = "Reggie";
b. var "playerName" = Reggie;
c. var playerName = "Reggie";
d. var playerName = Reggie;

3.3 Please fill in the correct answer in each blank provided below.
Finish the code below to create a variable named shipsLeft containing the number 10.
\_\_ shipsLeft = 10;

4.4 Which of the following is NOT a valid variable name in JavaScript?
a. time remaining
b. $form
c. t
d. var

5.5 Please fill in the correct answer in each blank provided below.
Add the code that logs the value stored in the greeting variable to the console:
~~~
var greeting = “Good morning”;
console.log(___ );
~~~

6.6 Which of the following is a valid variable name in JavaScript?
a. %remaining
b. var
c. $perPound
d. 2_to_go

A

Answer 1. C
Answer 2. C
Answer 3. var shipsLeft = 10;
Answer 4. D
Answer 5.
~~~
var greeting = “Good morning”;
console.log( greeting );
~~~
Answer 6. C

19
Q

Explain the following code in JS and how variable and operators are used in JS?

var score = 0;
score = score + 10;
console.log(score);

score += 5;
console.log(score);

var bonusPts = 100;
var finalScore = score + bonusPts;
console.log(finalScore);
A

This JavaScript code snippet demonstrates basic variable assignments and arithmetic operations. Here’s a breakdown of the code:

  1. var score = 0;
    • var is a keyword used to declare a variable in JavaScript.
    • score is the variable name.
    • 0 is the initial value assigned to the variable score.
    • After this line, score holds the value 0.
  2. score = score + 10;
    • This is an arithmetic operation. It adds 10 to the current value of score.
    • Initially, score is 0, so 0 + 10 equals 10.
    • The result (10) is then reassigned to the variable score.
    • After this line, score holds the value 10.
  3. console.log(score);
    • This line outputs the current value of score to the console.
    • It will display 10.
  4. score += 5;
    • This is a shorthand for score = score + 5.
    • It adds 5 to the current value of score, which is 10.
    • So, score now becomes 15.
  5. console.log(score);
    • This outputs the current value of score to the console, which is now 15.
  6. var bonusPts = 100;
    • A new variable bonusPts is declared and initialized with the value 100.
  7. var finalScore = score + bonusPts;
    • A new variable finalScore is declared.
    • It is initialized with the result of the addition of score and bonusPts.
    • Since score is 15 and bonusPts is 100, finalScore becomes 115.
  8. console.log(finalScore);
    • This outputs the value of finalScore to the console, which is 115.

In summary, this code demonstrates variable declaration (var), basic arithmetic operations (addition + and the addition assignment +=), and outputting values to the console (console.log). Variables score, bonusPts, and finalScore are used to store and manipulate numeric data, showcasing how variables and operators are used in JavaScript.

20
Q

Explain the let and const in JS and the following code:

let score = 5;
score += 5;
console.log(score);

const score = 5;
score += 10;
console.log(score);
A

In JavaScript, let and const are used to declare variables, but they have different characteristics.

  1. let:
    • Variables declared with let can be reassigned. This means you can change the value of a variable declared with let.
    • let is block-scoped, which means it’s only accessible within the block or statement where it is defined.
  2. const:
    • Variables declared with const are constant, meaning their values cannot be reassigned once they are set.
    • Like let, const is also block-scoped.

Now let’s break down the provided code:

```javascript
// Using let
let score = 5;
score += 5; // Adding 5 to the existing value of score
console.log(score); // Output: 10

// Using const
const score = 5;
score += 10; // This line will result in an error, as you are trying to modify the value of a constant variable
console.log(score); // This line will not be executed due to the error above
~~~

Explanation:

  1. In the first part using let, you declare a variable score with an initial value of 5. You then increment its value by 5 using the += operator. Finally, you print the result to the console, which is 10.
  2. In the second part using const, you declare a constant variable score with an initial value of 5. However, when you try to increment its value by 10, an error will occur because const variables cannot be reassigned. Therefore, the code after the attempt to modify the const variable will not be executed.
21
Q

What is the difference between let and var? Explain it with example.

A

The main difference between let and var in JavaScript lies in their scoping behavior.

  1. let:
    • Variables declared with let are block-scoped. This means that they are only accessible within the block or statement where they are defined.
    • If you declare a variable with let inside a function or a block (like an if statement or a loop), that variable will only be available within that specific block.
    • let was introduced in ECMAScript 6 (ES6).
  2. var:
    • Variables declared with var are function-scoped or globally-scoped. If a variable is declared with var inside a function, it is only accessible within that function. If it is declared outside any function, it becomes a global variable.
    • var declarations are hoisted to the top of their scope. This means that you can use a variable declared with var before it is actually declared in the code.

Here’s an example to illustrate the difference:

```javascript
// Using let
function exampleUsingLet() {
if (true) {
let x = 10;
console.log(x); // Output: 10
}
// Uncommenting the line below will result in an error because x is not defined here
// console.log(x); // Error: x is not defined
}

// Using var
function exampleUsingVar() {
if (true) {
var y = 20;
console.log(y); // Output: 20
}
// The variable y is accessible outside the block due to var’s function-scoping
console.log(y); // Output: 20
}

// Example invocations
exampleUsingLet();
exampleUsingVar();
~~~

In the exampleUsingLet function, the variable x is declared with let inside an if block. It is only accessible within that block, and attempting to access it outside the block will result in an error.

In the exampleUsingVar function, the variable y is declared with var inside an if block. It is accessible both inside and outside the block due to var’s function-scoping behavior.

22
Q

Code Challenge: Evaluate the code in app.js. The code currently produces a TypeError. Adjust the code so that the points variable holds the expected value.

const points = 100;
const bonusPts = 50;

points += bonusPts;
console.log(points);
A

Answer to Code Challenge:

let points = 100;
let bonusPts = 50;

points += bonusPts;
console.log(points);
23
Q

Explain strings in JS? And explain it using the following code:

const htmlsnippet = '<h1 class="headline">My Headline</h1>'
const message = "I'm a Programmer";
const message = 'I\'m a Programmer';
const multiline = "Hello, Students.\
Welcome to Javascript Basics.\
I hope you learn a lot!";

console.log(multiline);
A

In JavaScript, a string is a sequence of characters enclosed within single (‘ ‘), double (“ “), or backticks (` `) quotes. Strings are used to represent and manipulate textual data. Let’s go through the provided code to understand different aspects of strings in JavaScript:

  1. Single and Double Quotes:In JavaScript, you can use either single or double quotes to define strings. In your code, you have examples of both:
    javascript
    const message1 = "I'm a Programmer";
    const message2 = 'I\'m a Programmer';
    The first example uses double quotes to define a string containing an apostrophe. The second example uses single quotes, and the apostrophe inside the string is escaped using a backslash (\') to indicate that it’s part of the string and not the end of it.
  2. Multiline Strings:JavaScript allows multiline strings, and you can concatenate lines using a backslash (\) at the end of each line. In your code:
    javascript
    const multiline = "Hello, Students.\
    Welcome to Javascript Basics.\
    I hope you learn a lot!";
    The backslash at the end of each line indicates that the string continues on the next line. When you log this multiline string to the console:
    javascript
    console.log(multiline);
    It will output:
    Hello, Students.Welcome to Javascript Basics.I hope you learn a lot!
    Note that there are no line breaks in the output because the backslashes are used to escape the newline characters.
  3. HTML String:In your code, you also have an example of a string that contains HTML:
    javascript
    const htmlsnippet = '<h1 class="headline">My Headline</h1>';
    This string contains an HTML snippet enclosed in single quotes. It can be used to dynamically generate HTML content or be inserted into the DOM.

In summary, strings in JavaScript can be created using single or double quotes, and multiline strings can be formed by using a backslash to continue the string on the next line. Strings are versatile and are commonly used to represent textual data in JavaScript programs.

24
Q

What is property and methods in JS? Explain using the following code and method and property in it:

const passphrase = "High";
console.log(passphrase.length);
console.log("This is my string!".length);
console.log(passphrase.toUpperCase());
console.log(passphrase.toLowerCase());
A

In JavaScript, properties and methods are associated with objects, and they are fundamental concepts in object-oriented programming. Objects in JavaScript can have properties, which are like variables associated with the object, and methods, which are functions associated with the object.

Let’s break down your code and identify properties and methods:

```javascript
// Property: length
const passphrase = “High”;
console.log(passphrase.length); // Property of the string “High” - it gives the length of the string

// Property: length
console.log(“This is my string!”.length); // Property of the string “This is my string!” - it gives the length of the string

// Method: toUpperCase()
console.log(passphrase.toUpperCase()); // Method of the string “High” - it converts the string to uppercase

// Method: toLowerCase()
console.log(passphrase.toLowerCase()); // Method of the string “High” - it converts the string to lowercase
~~~

In this code:

  1. The length property is used to get the number of characters in a string. It is accessed using dot notation (string.length).
  2. The toUpperCase() method is a function associated with string objects. It converts all the characters in a string to uppercase.
  3. The toLowerCase() method is another function associated with string objects. It converts all the characters in a string to lowercase.

So, in summary:

  • length is a property that provides the length of a string.
  • toUpperCase() is a method that converts a string to uppercase.
  • toLowerCase() is a method that converts a string to lowercase.
25
Q

Explain prompt method and explain the following code:

const name = prompt("What is your name?");
alert(name);
A

The prompt method is a built-in function in JavaScript that displays a dialog box with a message, an optional input field, and buttons for the user to input data. It’s commonly used to interact with users by prompting them for information or input. The prompt method returns the value entered by the user as a string.

Now, let’s break down the provided code:

```javascript
const name = prompt(“What is your name?”);
alert(name);
~~~

  1. const name: This declares a constant variable named name. The const keyword is used to create a variable that cannot be reassigned after its initial value is set.
  2. prompt("What is your name?"): This line displays a dialog box with the message “What is your name?” and an input field. The user can enter their name, and the value entered will be assigned to the variable name. The prompt function returns the user’s input as a string.
  3. alert(name): This line uses the alert method to display an alert dialog box with the value of the name variable. In this case, it will show the name that the user entered in the prompt dialog.

So, when you run this code:

  1. The prompt dialog appears, asking the user to enter their name.
  2. The entered name is stored in the name variable.
  3. An alert dialog displays the entered name.

It’s a simple example of using user input through the prompt method and then displaying that input using the alert method. Note that the usage of prompt and alert dialogs can be limited, and more sophisticated user interfaces are often created using HTML, CSS, and JavaScript in combination.

26
Q

Explain the following code (in JS):

Code 1:
~~~
const name = prompt(“What is your name?”);
const message = “Hello “ + name + “. Welcome to my music site. “ +
“I’m so happy that you came by to visit, “ + name + “. Feel free to come again and listen to more music! “;

console.log(message);
~~~

Code 2:
~~~
const name = prompt(“What is your name?”);
let message = “Hello “ + name + “. Welcome to my music site. “;
message += “I’m so happy that you came by to visit, “;
message += name;
message += “. Feel free to come again and listen to more music!”

console.log(message);
~~~

A

Both Code 1 and Code 2 perform similar tasks but with a slight difference in the way the message is constructed. Let’s break down each code snippet:

Code 1:

```javascript
const name = prompt(“What is your name?”);
const message = “Hello “ + name + “. Welcome to my music site. “ +
“I’m so happy that you came by to visit, “ + name + “. Feel free to come again and listen to more music! “;

console.log(message);
~~~

  1. Prompt User Input:
    • It starts by using the prompt function to get the user’s name. The user is prompted with the question “What is your name?”.
  2. Concatenation:
    • The user’s input (name) is then concatenated with other strings to form a complete message.
    • The message includes a greeting, a welcome to a music site, an expression of happiness for the visit, and an invitation to come again.
  3. Logging:
    • The final message is logged to the console using console.log().

Code 2:

```javascript
const name = prompt(“What is your name?”);
let message = “Hello “ + name + “. Welcome to my music site. “;
message += “I’m so happy that you came by to visit, “;
message += name;
message += “. Feel free to come again and listen to more music!”

console.log(message);
~~~

  1. Prompt User Input:
    • Similar to Code 1, it prompts the user for their name.
  2. String Concatenation using ‘+=’:
    • Instead of a single string concatenation as in Code 1, this code uses the += operator to append strings to the message variable incrementally.
    • The message is built up by adding one string at a time, making it more step-by-step.
  3. Logging:
    • The final message is logged to the console using console.log().

Difference:
- The primary difference lies in the way the message is constructed. Code 1 uses a single string concatenation, while Code 2 builds the message incrementally using the += operator.

Both code snippets achieve the same end result – creating a personalized message based on user input and logging it to the console. The choice between the two approaches often depends on personal preference and coding style.

27
Q

Challenge Task 1:
Assign your first name to the variable firstName and your last name to lastName.

let firstName;
let lastName;
let role = 'developer';

Challenge Task 2:
Below role, create a new variable named msg that combines the firstName, lastName and role variables to create a string like “Carlos Salgado: developer”.

HINT: Pay close attention to the spaces in the string.

A

Answer:

let firstName = "Carlos"; 
let lastName = "Salgado";
let role = 'developer';

const msg = firstName + " " + lastName + ": " + role.toUpperCase();
28
Q

Explain template literals in JS and explain it using the following code?

const name = prompt('What is your name?');

const message = `Hello, ${name}. It's ${2 * 3} o'clock. Welcome to my Music Site. I am happy that you came by to visit, ${name}. Please come again and listen to more music!`;

console.log(message);
A

Template literals are a feature in JavaScript introduced with ECMAScript 6 (ES6) that allows for more convenient and readable string interpolation. They are enclosed by backticks (``) and can contain placeholders ${}, which are used to embed expressions within the string. When the template literal is evaluated, the placeholders are replaced with the actual values of the expressions.

In the given code:

```javascript
const name = prompt(‘What is your name?’);
~~~

This line prompts the user to enter their name and stores the input in the variable name.

```javascript
const message = Hello, ${name}. It's ${2 * 3} o'clock. Welcome to my Music Site. I am happy that you came by to visit, ${name}. Please come again and listen to more music!;
~~~

Here, a template literal is used to create a message string. The ${name} placeholder is used to embed the value of the name variable into the string. Similarly, the ${2 * 3} placeholder is used to embed the result of the expression 2 * 3 (which is 6) into the string. The final message string is a combination of fixed text and the dynamically inserted values.

```javascript
console.log(message);
~~~

Finally, the console.log() statement is used to print the message to the console.

For example, if the user enters “John” when prompted, the output would be something like:

Hello, John. It's 6 o'clock. Welcome to my Music Site. I am happy that you came by to visit, John. Please come again and listen to more music!
29
Q

Explain the following JS code and explain querySelector in JS:

const stringToShout = prompt("What do you want to shout?");
const shout = stringToShout.toUpperCase();
const shoutMessage = `<h2>The message to shout is: ${shout}!!</h2>`;

document.querySelector('main').innerHTML = shoutMessage;
A

Certainly! Let’s break down the JavaScript code step by step:

```javascript
// Prompt the user to enter a message and store it in the variable stringToShout
const stringToShout = prompt(“What do you want to shout?”);

// Convert the input message to uppercase and store it in the variable shout
const shout = stringToShout.toUpperCase();

// Create an HTML message using a template literal and include the uppercase shout message
const shoutMessage = <h2>The message to shout is: ${shout}!!</h2>;

// Use querySelector to select the first ‘main’ element in the HTML document
// and set its innerHTML to the shoutMessage, effectively updating the content
document.querySelector(‘main’).innerHTML = shoutMessage;
~~~

Explanation:

  1. prompt("What do you want to shout?");: This line prompts the user to enter a message. The entered message is then stored in the variable stringToShout.
  2. const shout = stringToShout.toUpperCase();: This line converts the user-entered message (stringToShout) to uppercase using the toUpperCase() method and stores the result in the variable shout.
  3. const shoutMessage = `<h2>The message to shout is: ${shout}!!</h2>`;: This line creates an HTML message using a template literal (${}) to include the uppercase shout message. The resulting HTML string is stored in the variable shoutMessage.
  4. document.querySelector('main').innerHTML = shoutMessage;: This line uses querySelector to select the first ‘main’ element in the HTML document. It then sets the innerHTML property of that ‘main’ element to the value of shoutMessage, effectively updating the content of the ‘main’ element with the shout message in uppercase.

querySelector in JavaScript:
document.querySelector(selector) is a method that returns the first element that matches the specified CSS selector(s) in the document. In the provided code, it selects the first ‘main’ element in the HTML document. Once the element is selected, the code sets its innerHTML property to the shoutMessage, inserting the formatted shout message into the ‘main’ element.

30
Q

Code Challenge: Create a program that retrieves user feedback and combines that feedback to create a string that displays on the page.

index.html:
~~~
<!DOCTYPE html>

<html>
<head>
<meta></meta>
<title>JavaScript Basics – Challenge</title>
<link></link>
</head>
<body>
<main></main>

   
</body>
</html>
story.js:

// 1. Declare variables and capture input.

// 2. Combine the input with other words to create a story.

// 3. Display the story as a <p> inside the <main> element.
~~~

A

story.js:

My answer:
~~~
// 1. Declare variables and capture input.

const adjective = prompt(“Enter an adjective!”);

// 2. Combine the input with other words to create a story.

const story = <p>There was a great miracle worker who loved ${adjective}!</p>;

// 3. Display the story as a <p> inside the <main> element.

document.querySelector(‘main’).innerHTML = story;
~~~

31
Q

Explain the following code:

// 1. Declare variables and capture input.

const adjective = prompt('Please type an adjective.');
const verb = prompt('Please type a verb.');
const noun = prompt('Please type a noun.');

// 2. Combine the input with other words to create a story.

const sentence = `<p>There once was a ${adjective} programmer who wanted to use Javascript to ${verb} the ${noun}.</p>`;

// 3. Display the story as a <p> inside the <main> element.

document.querySelector('main').innerHTML = sentence;
A

Certainly! This code is a simple JavaScript program that prompts the user for input, combines the input into a sentence, and then displays the sentence inside the <main> element of an HTML document.

Here’s a breakdown:

  1. Declare variables and capture input:
    • const adjective = prompt('Please type an adjective.');
    • const verb = prompt('Please type a verb.');
    • const noun = prompt('Please type a noun.');
    These lines declare three variables (adjective, verb, and noun) and use the prompt function to get input from the user. The prompt function displays a dialog box with the specified message and waits for the user to enter something.
  2. Combine the input with other words to create a story:
    • const sentence = <p>There once was a ${adjective} programmer who wanted to use Javascript to ${verb} the ${noun}.</p>;
    This line uses template literals to create a sentence by combining the user-inputted adjectives, verbs, and nouns into a string. The resulting sentence is wrapped in a <p> (paragraph) HTML tag.
  3. Display the story as a <p> inside the <main> element:
    • document.querySelector('main').innerHTML = sentence;
    This line uses document.querySelector('main') to select the <main> element in the HTML document, and then sets its innerHTML property to the generated sentence. This effectively inserts the sentence into the <main> element, displaying it on the web page.

In summary, this code creates a dynamic story based on user input and displays it on a web page. The use of prompt allows for interactive input, and the use of innerHTML injects the generated sentence into the HTML document.

32
Q

Challenge Task:
Convert the set of concatenated strings assigned to the drink variable to a template literal. The final string should be “Blueberry Smoothie: $4.99”.

const flavor = "Blueberry";
const type = "Smoothie";
const price = 4.99;

const drink = flavor + ' ' + type + ': ' + '$' + price;
A

The answer:

const flavor = "Blueberry";
const type = "Smoothie";
const price = 4.99;

const drink = `${flavor} ${type}: \$\${price}`;
33
Q

Explain the following JS Code:

const answer = prompt("Which planet is closest to the sun?");

if ( answer.toUpperCase() === "MERCURY" ) {
  console.log("That's correct!");
} else {
  console.log("Sorry, that's incorrect");
}
A

This JavaScript code prompts the user with a question and checks if the user’s input matches the correct answer.

Here’s a breakdown:

  1. const answer = prompt("Which planet is closest to the sun?");: This line prompts the user with a question displayed in a dialog box. The user can input their answer. The entered value is stored in the variable answer.
  2. if (answer.toUpperCase() === "MERCURY") { ... } else { ... }: This line checks if the user’s input, converted to uppercase using toUpperCase(), is equal to the string "MERCURY". If it is, the code inside the first block ({ ... }) is executed, indicating that the user’s answer is correct. Otherwise, the code inside the second block (else { ... }) is executed, indicating that the answer is incorrect.
  3. Inside the first block, console.log("That's correct!"); prints the message “That’s correct!” to the console if the user’s answer is “MERCURY”.
  4. Inside the second block, console.log("Sorry, that's incorrect"); prints the message “Sorry, that’s incorrect” to the console if the user’s answer is not “MERCURY”.

In summary, this code prompts the user to input the planet closest to the sun, checks if the answer is “MERCURY” (ignoring case), and provides feedback based on whether the answer is correct or not.