Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

JavaScript Intro

Script

Uploaded by

smangal1307
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JavaScript Intro

Script

Uploaded by

smangal1307
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JavaScript Introduction

JavaScript is a high-level, interpreted programming language commonly used to create dynamic


and interactive content on websites. It is one of the core technologies of the web, alongside
HTML and CSS, and plays a crucial role in front-end development.

Key Characteristics of JavaScript:

1. Client-Side Scripting: JavaScript runs directly in the web browser, allowing web pages
to respond to user interactions without reloading the entire page.
2. Interpreted Language: Unlike languages like C++ or Java, JavaScript is not compiled.
Instead, the browser interprets the code at runtime.
3. Event-Driven: JavaScript is often used to create dynamic responses to events, such as
mouse clicks, keypresses, or form submissions.
4. Loosely Typed: You don’t need to specify the data type of a variable in JavaScript. For
example, let x = 5; could later be changed to x = "Hello"; without causing an error.

How to Link JavaScript File in HTML?

JavaScript can be added to HTML file in two ways:

Internal JS: We can add JavaScript directly to our HTML file by writing the code inside
the <script> tag. The <script> tag can either be placed inside the <head> or the <body>
tag according to the requirement.

External JS: We can write JavaScript code in another files having an extension.js and
then link this file inside the <head> tag of the HTML file in which we want to add this
code.

Variables
In JavaScript, variables are used to store and manage data. You can declare variables
using three keywords: var, let, and const.

var

 Scope: var is function-scoped. This means that if a variable is declared with var inside a
function, it is not accessible outside that function. However, var is not block-scoped, so it
can be accessed outside a block.
 Hoisting: Variables declared with var are hoisted, meaning they are moved to the top of
their scope before code execution, but they are not initialized until the code is executed.

console.log(x); // Output: undefined


var x = 5;
console.log(x); // Output: 5
let
 Scope: let is block-scoped, which means it only exists within the block (e.g., inside an if
statement or a loop) where it is declared.
 Hoisting: Variables declared with let are also hoisted, but they are not accessible until
they are initialized, preventing errors caused by accessing variables before their
declaration (known as the "temporal dead zone").

console.log(y); // Reference Error: Cannot access 'y' before initialization


let y = 10;

const
 Scope: Like let, const is also block-scoped.
 Immutability: A variable declared with const cannot be reassigned after it is initialized.
However, if the variable holds an object or an array, the properties or elements of that
object/array can still be modified.
 Hoisting: Similar to let, const is hoisted but not accessible until initialized.

console.log(z); // Reference Error: Cannot access 'z' before initialization


const z = 20;

In JavaScript, the var keyword has been part of the language since its inception in 1995. It was
introduced in the first version of JavaScript (originally called LiveScript) by Netscape.

However, the introduction of var came with certain limitations and quirks, such as function-
scoping and hoisting, which led to unpredictable behavior in some cases. This is why newer
keywords like let and const were introduced in ES6 (ECMAScript 2015) to address some of the
issues associated with var:

 Block-scoping: let and const are block-scoped, unlike var, which is function-scoped.
 No re-declaration: Unlike var, let and const do not allow re-declaration of the same variable
within the same scope.
 Temporal Dead Zone (TDZ): let and const prevent access to variables before they are declared.

While var is still widely supported and can be used, modern JavaScript development largely
favors let and const for better predictability and scope control.

Obtaining User Input


In JavaScript, there are several ways to obtain user input depending on the context in which you
are working. Common methods include using the browser’s built-in prompt() function, capturing
input from HTML forms, or handling events like button clicks.
Using prompt()
The simplest way to get user input in JavaScript is by using the prompt() function, which
displays a dialog box asking the user to input some text.

let userName = prompt("Please enter your name:");


console.log("Hello, " + userName + "!");

 The prompt() function displays a dialog box with a message and a text field.
 The value entered by the user is returned and stored in the variable userName.

Getting Input from an HTML Form

A common way to collect user input on web pages is by using an HTML form and handling the
input using JavaScript.

<html>

<head>

<title>Get HTML Input in JavaScript</title>

<script>

function getFormData() {

// Get values from different form elements

const name = document.getElementById("name").value;

// This selects an HTML element with the id attribute set to "name"

//This line of code looks for an element in the HTML document with the id="name".

//.value: This property retrieves the current value of the selected element. In this case, it assumes
that the element is an input field (e.g., a text box), and .value will give you the text that the user has
entered.

const age = document.getElementById("age").value;

const gender = document.querySelector('input[name="gender"]:checked').value;

const feedback = document.getElementById("feedback").value;


// Display the values (you can also process these as needed)

document.getElementById("result").innerHTML =

`<p>Name: ${name}</p>

<p>Age: ${age}</p>

<p>Gender: ${gender}</p>

<p>Feedback: ${feedback}</p>`;

// The ${} syntax is used to insert JavaScript variables (e.g., name, age, gender, and feedback)
into the string.

 <p>Name: ${name}</p>: Inserts a paragraph (<p>) with the text "Name: " followed by
the value of the name variable.
 <p>Age: ${age}</p>: Inserts a paragraph with "Age: " followed by the value of the age
variable.
 <p>Gender: ${gender}</p>: Inserts a paragraph with "Gender: " followed by the value
of the gender variable.
 <p>Feedback: ${feedback}</p>: Inserts a paragraph with "Feedback: " followed by
the value of the feedback variable.

//  document.getElementById("result") finds the element with the ID result.

 .innerHTML gets or sets the HTML content inside that element.

 It is commonly used to dynamically update webpage content using JavaScript

</script>

</head>

<body>

<h1>User Feedback Form</h1>


<!-- User Input Form -->

<form id="userForm" onsubmit="event.preventDefault(); getFormData();">

//event.preventDefault() is a method that prevents the default action of the form submission. By
default, when a form is submitted, the browser performs an HTTP request (usually sending data and
reloading the page). Using event.preventDefault() stops the form from actually submitting and
reloading the page, allowing you to handle the data with JavaScript without the page refreshing.

//getFormData();-After preventing the default form submission, this part calls a JavaScript
function named getFormData(). This function is presumably defined elsewhere in your code
and is used to collect or process the form data (such as reading input values, validating them, or
sending them to a server via AJAX).

<!-- Name input -->

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<!-- Age input -->

<label for="age">Age:</label>

<input type="number" id="age" name="age" required><br><br>

<!-- Gender input (radio buttons) -->

<label>Gender:</label>

<input type="radio" id="male" name="gender" value="Male" required>

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="Female">

<label for="female">Female</label><br><br>

<!-- Feedback textarea -->

<label for="feedback">Feedback:</label><br>
<textarea id="feedback" name="feedback" rows="4" cols="50" placeholder="Enter your
feedback"></textarea><br><br>

<!-- Submit button -->

<input type="submit" value="Submit">

</form>

<!-- Display form data -->

<div id="result"></div>

</body>

</html>

You might also like