Introduction to Javascript

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which statement accurately describes the role of JavaScript in web development?

  • It is used for styling web pages, handling layout and visual design.
  • It primarily handles server-side logic and database interactions.
  • It defines the structure and content of web pages.
  • It adds interactivity to HTML pages and is executed on the client's machine. (correct)

How does JavaScript handle different web browsers?

  • It requires extensive testing across different browsers due to potential compatibility issues. (correct)
  • It relies on the web server to perform adaptations for different browsers.
  • It is compiled into different versions for each browser to ensure compatibility.
  • It automatically adjusts its code to run identically on all browsers without the need for specific testing.

Where in an HTML document can you embed JavaScript code?

  • Embedded within `<script>` tags either in the `<head>` or `<body>` sections. (correct)
  • Only in external files linked via the `<footer>` tag.
  • Only in the `<body>` section of the HTML document.
  • Only in the `<head>` section of the HTML document.

Which statement best describes the use of async and defer attributes in the <script> tag?

<p><code>async</code> scripts download and execute asynchronously without blocking HTML parsing, while <code>defer</code> scripts download asynchronously but execute after HTML parsing is complete. (C)</p> Signup and view all the answers

Which of the following commands is used for displaying information in the console for debugging purposes?

<p><code>console.log()</code> (A)</p> Signup and view all the answers

How would you declare a variable named counter in JavaScript using the var keyword?

<p><code>var counter;</code> (D)</p> Signup and view all the answers

What is the primary difference between variables declared using let and const?

<p><code>let</code> allows reassignment of the variable, while <code>const</code> does not. (D)</p> Signup and view all the answers

Which of these is NOT a primitive data type in JavaScript?

<p>Object (B)</p> Signup and view all the answers

How do you determine the number of elements in an array named myArray?

<p><code>myArray.length</code> (A)</p> Signup and view all the answers

If myArray is ['apple', 'banana', 'cherry'], what will myArray[1] return?

<p><code>'banana'</code> (D)</p> Signup and view all the answers

What does the push() method do in JavaScript arrays?

<p>Adds one or more elements to the end of the array and returns the new length of the array. (A)</p> Signup and view all the answers

What does the slice() method do when applied to an array?

<p>It returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). The original array will not be modified. (D)</p> Signup and view all the answers

How do you define a function named multiply that takes two parameters, a and b, and returns their product?

<p>All of the above (D)</p> Signup and view all the answers

What keyword is used to send a value back from a JavaScript function?

<p><code>return</code> (D)</p> Signup and view all the answers

Which method is used to find an HTML element by its ID in JavaScript?

<p><code>document.getElementById()</code> (C)</p> Signup and view all the answers

What does the term 'event' refer to in the context of JavaScript and web browsers?

<p>A message issued by the browser in response to user actions or system occurrences. (A)</p> Signup and view all the answers

Which event is triggered when a user clicks an HTML element?

<p><code>onclick</code> (B)</p> Signup and view all the answers

What is an event handler in JavaScript?

<p>A function that executes in response to a specific event. (D)</p> Signup and view all the answers

What does DOM stand for in JavaScript?

<p>Document Object Model (D)</p> Signup and view all the answers

How can JavaScript manipulate the DOM?

<p>By adding, updating, or removing HTML elements; changing HTML attributes; changing CSS styles, and reacting to events. (D)</p> Signup and view all the answers

What is a JavaScript Promise?

<p>An object representing the eventual completion (or failure) of an asynchronous operation. (B)</p> Signup and view all the answers

Which state indicates that a Promise has been successfully completed?

<p><code>fulfilled</code> (A)</p> Signup and view all the answers

What are .then() and .catch() methods used for with Promises?

<p><code>.then()</code> is used to handle fulfillment, and <code>.catch()</code> is used to handle rejections. (B)</p> Signup and view all the answers

What is the purpose of the async keyword when defining a JavaScript function?

<p>It allows the function to use <code>await</code> inside, making it asynchronous and ensuring it returns a Promise. (A)</p> Signup and view all the answers

What is the primary use of the await keyword inside an async function?

<p>To pause the execution of the <code>async</code> function until a Promise is resolved. (B)</p> Signup and view all the answers

What is the role of CCXT library in JavaScript?

<p>It is a library specifically designed for trading in multiple cryptocurrency exchanges. (C)</p> Signup and view all the answers

How can you add the CCXT library to your JavaScript code?

<p>Both B and C (C)</p> Signup and view all the answers

What is meant by 'dynamic HTML' in the context of web development?

<p>HTML that is modified using JavaScript after it has been loaded and rendered in the browser. (C)</p> Signup and view all the answers

What is the primary purpose of conditional statements in JavaScript?

<p>To execute different code blocks based on specified conditions. (C)</p> Signup and view all the answers

Which of the following is an example of a conditional statement in JavaScript?

<p><code>if (a &gt; b) { console.log('a is greater'); }</code> (B)</p> Signup and view all the answers

What is the purpose of including <script> tags in an HTML document?

<p>To embed or link JavaScript code to the HTML document. (D)</p> Signup and view all the answers

What is the best way to manipulate HTML elements in a web page using JavaScript?

<p>Using the DOM (Document Object Model). (A)</p> Signup and view all the answers

How does JavaScript enhance user experience on websites?

<p>By adding interactivity, controlling page behavior, and creating animations. (A)</p> Signup and view all the answers

Which method is most appropriate for retrieving multiple HTML elements with the same class name?

<p><code>document.getElementsByClassName()</code> (A)</p> Signup and view all the answers

Consider the array: myArray = [10, 20, 30, 40];. What would myArray.slice(1, 3) return?

<p><code>[20, 30]</code> (B)</p> Signup and view all the answers

In the context of asynchronous Javascript, what does 'pending' describe?

<p>The initial state, neither fulfilled nor rejected (C)</p> Signup and view all the answers

What is the output of the following code?

console.log(typeof null);

<p><code>'object'</code> (D)</p> Signup and view all the answers

What is the potential drawback of visible code in JavaScript?

<p>Potential security vulnerabilities (C)</p> Signup and view all the answers

Flashcards

What is Javascript?

A client-side scripting language that runs on the client machine. It adds interactivity to HTML pages.

Benefits of JavaScript

Enhances user experience and enables functions to control page behavior, create pop-ups, transitions, scrolling animations and autocomplete.

console.log()

Using the Javascript function to display data or output to the console.

var keyword

Used to declare variables in JavaScript.

Signup and view all the flashcards

let keyword

Declares a variable with block scope, can be re-assigned.

Signup and view all the flashcards

const keyword

Declares a block-scoped, read-only named constant.

Signup and view all the flashcards

What is an array?

Arrays are used to store multiple values in a single variable.

Signup and view all the flashcards

Array.length

Returns the number of elements in the array.

Signup and view all the flashcards

Array index

Refers to the position of an element within the array. The first element has an index of 0.

Signup and view all the flashcards

Array.push()

Adds elements to the end of an array.

Signup and view all the flashcards

Array.shift()

Removes the first element from an array.

Signup and view all the flashcards

Array.pop()

Removes the last element from an array.

Signup and view all the flashcards

Array.slice()

Returns a new array containing the selected elements.

Signup and view all the flashcards

What is a function?

A block of code designed to perform a particular task.

Signup and view all the flashcards

return

Used to return a value from a function. Ends function execution.

Signup and view all the flashcards

What are events?

An action or occurrence recognized by software. Examples include onclick, onmouseover, onkeydown, and onload.

Signup and view all the flashcards

Event handler

A function that is called when an event occurs.

Signup and view all the flashcards

Event

A message issued by the browser.

Signup and view all the flashcards

Document Object Model (DOM)

A web browser creates a DOM of a webpage when it is loaded.

Signup and view all the flashcards

DOM Manipulations

Can change HTML elements/attributes, CSS styles, and react to events.

Signup and view all the flashcards

Dynamic HTML

Web pages are changed after they are loaded and rendered in the browser

Signup and view all the flashcards

What is a Promise?

A JavaScript object that links producing code with consuming code. Used for asynchronous operations.

Signup and view all the flashcards

Promise state: pending

Initial state for a promise, neither fulfilled nor rejected.

Signup and view all the flashcards

Promise state: fulfilled

The operation was completed successfully with the promise.

Signup and view all the flashcards

Promise state: rejected

The operation failed in the promose.

Signup and view all the flashcards

.then() and .catch()

Methods that return promises, so they can be chained.

Signup and view all the flashcards

async function

A function that makes the function run asynchronously. Functions will then return a promise

Signup and view all the flashcards

Study Notes

Introduction to Javascript

  • Javascript is implemented during the implementation phase of the SDLC

Javascript - What it is

  • Javascript is a client-side scripting language
  • Javascript runs on the client machine
  • Javascript interacts with a copy of the webpage loaded into a web browser on the client's machine
  • Javascript adds interactivity to HTML pages
  • Javascript is case sensitive

Benefits of Javascript

  • Javascript improves user experience
  • Javascript Functions control the behavior of the page
  • Javascript is used to create pop-ups, transitions, scrolling animations
  • Javascript has autocomplete with inbuilt functions
  • Node.js can be used for backend development
  • Javascript can be used for full stack development

Javascript - Disadvantages

  • Javascript depends on the browser type, which requires more testing
  • Javascript code is visible to anyone
  • Some browsers disable Javascript content as harmful

Inspect in Chrome

  • The Chrome console can be used to interact with code and print output
  • Access the console by right-clicking and selecting "Inspect - Developer Tools"

How to Write Javascript

  • Javascript is similar to CSS
  • Embed Javascript within <script> tags in the HTML: <script> ... </script>
  • Use a separate file with a .js extension in the head of the HTML
  • The <script> tag can also be placed just before the end of the body

Async Defer in <script>

  • Without Async/Defer, parsing stops, the script downloads and executes, then parsing continues
  • With Async, the script downloads asynchronously, parsing stops, the script executes, then parsing continues
  • With Defer, the script downloads asynchronously then executes after parsing is complete

Debugging

  • console.log("message") is similar to print statements
  • alert("message") displays a pop-up message and pauses execution until the user acknowledges

Other Important Console Methods

  • console.log() displays a general log message
  • console.error() displays an error message
  • console.warn() displays a warning message
  • console.assert() displays an error message if the assertion is false
  • console.clear() clears the console

Variables

  • The var keyword declares variables
  • Example: var a = 5; var b = 6; console.log(a, b)
    • This would output: 5 6

Variable Scope

  • Javascript uses the keywords const and let

Variable keywords:

  • var: Declares a variable, optionally initializing it to a value
  • let: Declares a block-scoped, local variable, optionally initializing it to a value
  • const: Declares a block-scoped, read-only named constant
  • let and const are block scoped within curly brackets {}

Data Types

  • Primitive:

    • Number
    • String
    • Boolean
    • Values (Null, Undefined)
    • BigInt for larger numbers
  • Object collection of properties:

    • Objects (name: value)
    • Arrays (list of values)
    • Symbol: It serves as non-string property names, everytime returns a unique value

Arrays

  • Arrays are a list of values
  • Arrays can be created in two ways:
    • Using square brackets: var myArray = [value1, value2]
      • Square brackets [] mark the start and end of the array
      • Elements are separated by commas and can be of any data type.
    • Using the new Array() constructor: var myArray = new Array()

Length of Array

  • The length of an array is the number of elements in the array
  • You can get the length of an array using .length such as myArray.length

Index of an Array

  • The index of an array refers to the position of the element within the array
  • The first element has an index of 0
  • To retrieve the third element use myArray[2]

Array example

> myArray = ["This", "is", "BT3103"]
< (3) ['This', 'is', 'BT3103']
> myArray.length
< 3
> myArray[0]
< "This"
> myArray[1]
< "is"
> myArray[3]
< undefined

Add elements to Array

  • Assign values using square brackets, e.g., myArray[3] = "Class"
    • If the element already exists, it is overwritten
    • Otherwise, a new element is added

Appending and Removing Array Elements

  • You can add elements to an array using the .push() method; this adds elements to the end of the array

  • You can remove elements from an array using:

    • .shift() to removes the first array element
    • .pop() to removes the last array element

Slice for multiple elements

  • Slice(n): This slices all values after the index position n

  • Slice(a,b): This slices values from index a (including) to index b (excluding)

Functions

  • Function Definition:
function functionName(param1, param2) { 
  statement1; 
  statement2; 
}
  • Example:
function displayMsg(userName) { 
  alert("Hello " + userName); 
  }

Invoke Functions

  • Invoke a function using the function name followed by parenthesis () which pass the function paramaters

Return from Functions

  • The return keyword is used to return a value from a function after processing
  • return (functionResult);

Use in Websites - Interactive DOM

  • Access elements in Javascript for dynamic websites:
    • CSS:
      • .class{}
      • #id{}
    • Javascript:
      • document.getElementsByClassName
      • document.getElementById

getElementbyId

  • document.getElementById("idName") the name of the element retrievable using Javascript

getElementsByClassName

  • document.getElementsByClassName("className") is used to retrieve elements that are accessible through javascript by their main class

Events

  • An event is a message issued by the browser
  • Web pages issue events in response to conditions and user actions
  • An event always has a type, which indicates the nature of the event

Common Events

  • onchange: When an HTML element has been changed
  • onclick: When the user clicks an HTML element
  • onmouseover: When the user moves the mouse over an HTML element
  • onmouseout: When the user moves the mouse away from an HTML element
  • onkeydown: When the user pushes a keyboard key
  • onload: When the browser finishes loading the page

Listening to Events

  • In order to respond to an event, we need to write code that listens for the event occurring
  • This code is the event listener
  • The event listener detects the event and evaluates the expression that performs some action in response to the event

Event Handlers

  • When an event listener is triggered, the expression it executes is a function or a method call
  • The function or method call is the event handler
  • Example: <button onclick="myFunction()">Click me</button> - In this example: - Onclick is the Event - myFunction() is the method to be called when the event occurs

Document Object Model (DOM)

  • The web browser creates a DOM of a webpage when it loads

  • The DOM model is created as a tree of objects

  • With DOM, JavaScript can add new elements, update existing elements and react to events

DOM Manipulations

  • Javascript changes in the HTML elements of the page
  • Javascript changes in the HTML attributes in the page
  • Javascript changes in the CSS styles in the page

Example Methods to Manipulate HTML Elements

  • getElementById(): Finding HTML elements by id
  • getElementsByTagName(): Finding HTML elements by tag name
  • getElementsByClassName(): Finding HTML elements by class

Dynamic HTML

  • Web pages changed as they are loaded and rendered in the browser

  • Such changes are immediately rendered on the screen.

Conditional Statement

  • Conditional statements help to display user-specific content

Promises

  • Promises are a Javascript object that links producing code and consuming code

Asynchronous

  • A task should be performed alongside the original task, without waiting
  • Promises have one of these states: -pending: initial state, neither fulfilled or rejected -fulfilled: the operation completed successfully -rejected: the operation failed

Resolving promise methods | .then() and .catch()

  • Both Promise.prototype.then() and Promise.prototype.catch() return promises that can be chained
  • CCXT (CryptoCurrency eXchange Trading Library)*
  • CCXT is a library that provides tools for trading in multiple cryptocurrency exchanges
  • All exchanges are derived from the base Exchange class with common methods
  • The API's are well bundled in the library CCXT
    • Adding the below to a script grants access to ccxt in code

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ccxt.browser.js"></script>

Retrieving Cryptocurrency Data with CCXT (Illustrative Example)

  • To resolve returns the result, a Javascript .then() is used on the promise
  • To retrieve the last value:
    • Assign z.then((x) => {} a variable
      • Call the variable index

To implement CCXT with Async/Await:

  • Writing async in front of a function makes it asynchronous, it guarantees that the function will then return a promise
    • If data is not returned, await may not have been enabled

Real Time price tracker

  • Design cryptocurrency tracker for 5 crypto coins, using CCXT, you are free to use any CSS and prices should be in real time.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Client-Side Scripting Mastery
5 questions
JavaScript in Web Development
12 questions
JavaScript Overview and Basics
19 questions

JavaScript Overview and Basics

InstructiveNephrite4861 avatar
InstructiveNephrite4861
Use Quizgecko on...
Browser
Browser