Javascript Basics Flashcards
*
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"> `;
This JavaScript code consists of three main parts. Let’s break it down:
-
Variable Declaration and Initialization:
javascript var name = "Sethu";
Here, a variablename
is declared using thevar
keyword and initialized with the string value"Sethu"
. This variable is used to store the name that will be used later in the code. -
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 thename
variable within the string. So, the message in the alert will be: “Hi, Sethu. Want to see something cool?”. -
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 itsinnerHTML
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).
- An
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.
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"> `;
This JavaScript code interacts with the user and then dynamically updates the content of the web page. Let’s break down its functionality:
-
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 variablename
. If the user enters their name, it will be saved in this variable. If the user cancels the prompt,name
will benull
. -
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?”. Ifname
isnull
, the message will be “Hi, . Want to see something cool?”. -
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 itsinnerHTML
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).
- An
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.
What is the short-cut key to open console in Mac to run javascript code on web-browser?
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 pressF12
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.).
What is Syntax (in Javascript)?
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:
-
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. - Operators: Using arithmetic, comparison, logical, assignment, and other types of operators.
-
Control Structures: Includes
if...else
statements,switch
cases, loops likefor
,while
,do...while
. - Functions: Defining and invoking functions, function expressions, arrow functions, and understanding scope and closures.
- Objects and Arrays: Syntax for creating objects and arrays, accessing and modifying their elements, methods for iteration and manipulation.
- Classes and Modules: Modern JavaScript supports class-based object-oriented programming and modules for code organization.
-
Exception Handling: Using
try...catch
blocks for error handling. -
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.
What does “syntax” mean?
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.
*
Can you use JavaScript on a web server?
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:
- Server-Side Scripting: You can write server-side code in JavaScript to handle tasks like database operations, file manipulation, and server logic.
- 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.
- 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.
- 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.
- 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.
- Framework Support: There are numerous frameworks, like Express.js, Koa.js, and Hapi, which simplify the process of developing web applications and APIs.
- Streaming Data: Node.js can handle streaming data, making it a good choice for applications like video streaming services.
- 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.
A quick way to run JavaScript is in the web browser’s developer tools, using a tool called:
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:
-
Accessing the Console:
- In Google Chrome, Mozilla Firefox, or Microsoft Edge, you can open the Console by pressing
Ctrl
+Shift
+J
(on Windows/Linux) orCmd
+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
.
- In Google Chrome, Mozilla Firefox, or Microsoft Edge, you can open the Console by pressing
-
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.
Explain the following line of codes in JS:
alert(); alert("hello world"); console.log("hello world!"); document.write(); document.write("Welcome to my webpage");
Sure, let’s break down these lines of JavaScript code:
-
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.
- This line calls the
-
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”.
- This line also calls the
-
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.
- This line uses the
-
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.
- This line calls
-
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 likeinnerHTML
or DOM manipulation functions, asdocument.write
can have some undesirable effects, especially if used after the document has finished loading.
- This line uses
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>");
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:
-
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!”. Thealert()
function is a simple way to display information to the user and requires them to click ‘OK’ to proceed. -
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. -
document.write("<h1>Welcome to my page</h1>");
This line uses thedocument.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 usingdocument.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.
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?
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
)
-
Doctype Declaration:
<!DOCTYPE html>
specifies the document type and version of HTML. Here, it declares HTML5. -
HTML Structure: Basic HTML structure is followed with
<html>
,<head>
, and<body>
tags. -
Character Set:
<meta charset="utf-8">
sets the character encoding to UTF-8, which includes most characters from all known human languages. -
Title:
<title>JavaScript Basics</title>
sets the title of the web page. -
Linking CSS:
<link href="css/style.css" rel="stylesheet">
links a CSS file (style.css
) located in thecss
folder. This CSS file is used for styling the HTML content. -
Linking JavaScript File:
<script src="js/script.js"></script>
links an external JavaScript file (script.js
) located in thejs
folder. This script will be executed when the HTML page is loaded. -
HTML Content: Within the
<body>
, there’s a<main>
tag containing an<h1>
header with the text “Hello, JavaScript!”. -
Inline JavaScript: Inside the
<main>
tag, there’s an inline<script>
tag with JavaScript codealert("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
- When the HTML file is loaded in a browser, it parses the HTML structure.
- The browser encounters the linked CSS file and applies the styles defined in it.
- The browser then encounters the first
<script>
tag linking toscript.js
. It loads and executes this script, displaying the alert “Hey, you are back for more?”. - The browser continues to parse the HTML, rendering the main content.
- Upon encountering the inline
<script>
tag, it executes that JavaScript, displaying the alert “Another message from Index.html”.
Using JavaScript in HTML
-
Inline JavaScript: Directly write JavaScript code within
<script>
tags in the HTML file, as shown in the inline script in yourindex.html
. -
External JavaScript File: Create a separate
.js
file (likescript.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).
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
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!”);
~~~
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.
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”);
~~~
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);
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:
-
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 namedmessage
. -
=
: 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 variablemessage
. Strings are a series of characters enclosed in quotes in JavaScript.
-
-
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 variablemessage
. -
message
: When used insideconsole.log
, it refers to the value stored in the variablemessage
, which is"Hello!"
.
-
-
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 variablemessage
. The old value"Hello!"
is replaced with the new value"Hello from JavaScript Basics"
. -
console.log(message);
: This again prints the current value ofmessage
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.
Code Challenge 1:
Create a variable named myName. Assign it your name between quotes (a string value).
var myName = "Urname";