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

Wk 6 JavaScript Part I

The document provides an overview of JavaScript, detailing its history, characteristics, and usage in web development. It explains JavaScript as a weakly-typed, dynamically typed, first-class function language that is primarily used for client-side scripting. Additionally, it covers how to embed JavaScript in HTML and outlines variable declaration rules and naming conventions.

Uploaded by

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

Wk 6 JavaScript Part I

The document provides an overview of JavaScript, detailing its history, characteristics, and usage in web development. It explains JavaScript as a weakly-typed, dynamically typed, first-class function language that is primarily used for client-side scripting. Additionally, it covers how to embed JavaScript in HTML and outlines variable declaration rules and naming conventions.

Uploaded by

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

Web Technology

JavaScript

Dr. Navanath Saharia


Indian Institute of Information Technology Senapati, Manipur
nsaharia@iiitmanipur.ac.in

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 1 / 23
Introduction About JavaScript

About JavaScript
❂ JavaScript is not Java
✍ The original name for JavaScript was Mocha then LiveScript
✍ It carries the functionality of Scheme language, the object-orientation of Self language, and the
syntax is similar to C and Java. However, JavaScript is a complete, and full-featured language.
✍ Developed by Brendan Eich in 1995, while he was working in Netscape.
✍ The developer later co-founded Mozilla and Brave Software

❂ JavaScript is seldom used to write complete programs


✍ Instead, small bits of JavaScript are used to add functionality to HTML pages
✍ JavaScript is often used in conjunction with HTML forms

❂ JavaScript is a weakly-typed or loosely-typed, dynamic, first-class function or function first,


Just-in-time, high level, platform-independent programming language
❂ JavaScript engine, a component of web browser are used to translate JavaScript source code.
Example: V8 (Chrome, node.js, Microsoft Edge), JavaScriptCore (Safari), SpiderMonkey (Mozilla),
Chakra (Internet Explorer)
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 2 / 23
Introduction About JavaScript

JavaScript: Weakly-typed Language


❂ JavaScript is a weakly-typed or loosely-typed, dynamic, first-class function or function first,
Just-in-time, high level programming language
❂ Weakly-typed languages: Set of languages, where data type declaration and type casting/conversions
are often performed implicitly as opposed to strongly typed languages. In strongly typed languages,
type of a value does not change in an unexpected way.

/* JavaScipt */ /* C */

let abc = 1, bcd = '001'; int main() {


console.log(typeof abc); //number int abc = 1;
console.log(typeof bcd); //string char bcd[] = "abc";
console.log(typeof(abc + bcd));//string printf("%d", (abc + bcd));
return 0;
}
warning: format ‘%d’ expects argument of
!→ type ‘int’, but argument 2 has type
!→ ‘char *’ [-Wformat=]
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 3 / 23
Introduction About JavaScript

JavaScript: Dynamically Typed Language

❂ A Set of languages, where the translator program assigns a type to a variable at runtime based on the
variable’s value at that time.
❂ Data-type is associated with value rather than a variable, giving freedom to the developers to modify
the data type of a variable. Example: JavaScript, Python, Ruby, PHP, Erlang and Perl.
❂ In static typed languages, once the data type of a variable is set, it is not allowed to change.

/* JavaScipt */ /* C */

let abc = 1; int main() {


console.log(typeof abc); //number int abc = 4;
abc = "111"; char abc[] = "abc";
console.log(typeof abc);//string printf("%s", abc);
}
error: conflicting types for 'abc'; have 'char[]'
note: previous definition of 'abc' with type 'int'
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 4 / 23
Introduction About JavaScript

JavaScript: First-class Function Language


❂ Function first languages: A set of language, that supports passing functions as arguments to other
functions, returning them as the values from other functions, and assigning them to variables or
storing them in data structures.
❂ First-class functions are a necessity for the functional programming paradigm, where functions are
treated as first-class citizens. Example: JavaScipt, Erlang, and Scheme
// Assigning a function to a variable
var abc = function (a, b, c) {return a + b + c;};
console.log(abc(1, 1.1, '1')); // Output: 2.11

// Passing a function as an argument


var bcd = function (pqr, x, y, z) {return pqr(x, y, z);};
console.log(bcd(abc, 1, 2, 3)); // Output: 6

// Returning a function from another function


var cde = function (factor) {return function (a) { return a * factor;};};
var def = cde(2);
console.log(def(5)); // Output: 10 . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 5 / 23
Introduction About JavaScript

JavaScript: Just-in-time compilation (JIT)


❂ Compilation done during execution of a program (at run time) rather than prior to execution
❂ JIT creates and runs some new executable code which was not part of the program when it was
stored on disk.
❂ Thus, it is a hybrid technique of creating machine code from source code and executing them in
run-time that combines best aspects of interpretation (such as, flexibility) and compilation (such as,
speed of compiled code) to enhance the performance. The intermediate forms/state of the translation
process are generally kept in primary memory, and not saved to the file system.
Ahead of Time Compilation
Just in Time
Combination
Compilation
Interpretation

❂ AKA Dynamic translation, Dynamic compilation or Run-time compilations.


❂ Concept was first introduced by John McCarthy on LISP in 1960 in his article Recursive functions of
symbolic expressions and their computation by machine . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 6 / 23
Introduction About JavaScript

JavaScript: Client-side Scripting Language


❂ A set of light-weight languages that is used to manipulate, customize, and automate the facilities of
an existing system. Interpreted execution, high-level abstractions to simplify programming tasks,
dynamic typing, and embeddability are primary characteristics of a scripting Language.
❂ Usually interpreted from source code or bytecode
✍ Bytecode is an intermediate representation (low-level, platform-independent set of instructions
that can be efficiently executed by a virtual machine) of source code that is typically used in the
context of interpreted or JIT-compiled languages.
❂ JavaScript is widely used as a client-side scripting language, especially in the context of web
development. As a client-side language, JavaScript
✍ Runs in the user’s web browser and is responsible for enhancing the interactivity and
functionality of web pages by dynamically updating and modifying HTML elements and
interfaces.
✍ Enables the handling of user interactions and events, such as clicks, key-presses, and form
submissions.
✍ Facilitates asynchronous communication with a server, allowing for data retrieval and updates
without requiring a full page reload. Technologies like AJAX (Asynchronous JavaScript and
XML) and the Fetch API are commonly used for making asynchronous . . . requests.
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 7 / 23
Introduction Embedding JavaScript in HTML

How to use JavaScript with HTML

❂ JavaScript can be included in an HTML document in three ways


inline, internal and external
❂ Inline JavaScript: This is the type of JavaScript that is included directly in an HTML element, using
the onclick, onload, or other event attributes. For example:

<button onclick="alert('Hello, world!')">Click me</button>

❂ While inline JavaScript can be quick and easy to use, it is generally not recommended, as it can make
your HTML code harder to read and maintain.
❂ Internal JavaScript: This is the type of JavaScript that is included within the HTML document,
using the <script> tag in the <head> or <body> section of the HTML document. For example:

<script type="text/javascript">
var abc = "Hello World!";
document.write(abd)
</script>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 8 / 23
Introduction Embedding JavaScript in HTML

How to use JavaScript with HTML

❂ Internal JavaScript is a better option than inline JavaScript, as it keeps your JavaScript code
separate from your HTML code, making it easier to read and maintain.

❂ External JavaScript: This is the type of JavaScript that is included in a separate file with a .js
extension, and then linked to the HTML document using the <script> tag with the src attribute.
For example:

<head>
<script src="myScript.js"></script>
</head>

❂ External JavaScript is the best option for larger projects, as it keeps your JavaScript code separate
from your HTML code, and also allows you to reuse the same JavaScript file across multiple HTML
documents.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 9 / 23
Data types Primitive data types

Primitive data types

❂ JavaScript has three primitive data types: number, string, and boolean. Everything else is an object

❂ JavaScript is a loosely typed language. That is, explicite declaration of variable types are not
necessary in JavaScript
❂ let abc= "abc"; abc = 123; bcd = 123;

❂ Numbers are always stored as floating-point values. Hexadecimal no. begin with 0x. Some platforms
treat 0123 as octal, others treat it as decimal
❂ let a=123, b=0123, c=0x123; console.log("a="+a+"\nb="+b+"\nc="+c);

❂ Strings may be enclosed in single quotes or double quotes

❂ Booleans are either true or false. 0, ‘0’, empty strings, undefined, null, and NaN are considered as
false, other values are true
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 10 / 23
Data types First JavaScript Program

My First JavaScript Program

1 <!DOCTYPE html>
2 <html>

3 <head>
4 <title>First JavaScript Program</title>
5 </head>

6 <body onload="confirm(Date())">

7 </body>
8 </html>

Change Line no. 6 to <body onload="alert(Date())">


and check the output
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 11 / 23
Data types First JavaScript Program

Example-1
1 <!DOCTYPE html>
2 <html>
3 <head>

4 <script>
5 function myFunction() {
6 let nm = prompt("Enter your name: ");
7 document.getElementById("pID").innerHTML =
8 "Dear " + nm + ", Welcome to the world of JavaScript ";}
9 </script> Dear User, Welcome to the world of
10 </head> JavaScript

11 <body onload="myFunction()"> ❂ Change line no. 6 to


12 <p id="pID"></p> let nm = prompt
13 </body> ("Enter name: ", "defaultUser");
14 </html> and check the output
❂ Change color . . of
. the
. . . .text
. . . to
. . blue
. . . and
. . . . .

display the. .final


.
text in center
. . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 12 / 23
Variable and Constants Variable

Variable Declaration
❂ Using the keyword var
var abc = "abc", bcd, efg;
for(var i = 0; i < 10; i++ ){};
❂ Using the keyword let
let abc = "abc", bcd, efg;
for(let i = 0; i < 10; i++ ){};
❂ What will be the output of the following statement?
let abc; console.log(abc);
❂ Value of the variable is considered as undefined, if it is not initialized, not even a null
❂ null refers the absence of a value. The variable bcd, in the following example does not have any
value, but it will have later on.
let abc = null; console.log(abc);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 13 / 23
Variable and Constants Naming convention

Rules associated with variable naming


❂ Permissible characters in variable name: [a-z0-9_ $].
❂ Variable names must start with a letter, $, or _.
❂ Variable names cannot start with a number.
❂ Variable names cannot contain spaces or hyphen
❂ Variable names cannot be a
✍ JavaScript researved word such as var, let, const, if, try
✍ JavaScript built-in-object, property and method name, such as, isNaN, name, String, function,
valueOf etc.
✍ HTML event handlers such as onclick, onsubmit, onload;
✍ HTML reserved words such as textarea, frame, option, document etc.
✍ Java objects and properties as JavaScript identifier such as java, JavaObject, and getClass
❂ Example:
JavaScript = 1.1; null = 1.1;
console.log(JavaScript);
console.log(null);
SyntaxError: Invalid left-hand side in assignment . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 14 / 23
Variable and Constants Naming convention

null ̸= NaN ̸= undefined


var abc = 1, bcd = 'ab', cde = true;
var def = '', efg=null, fgh;
console.log(abc === bcd);
console.log(abc == cde);
console.log(typeof abc);
console.log(abc === def);
console.log(typeof bcd);
console.log(abc === efg);
console.log(typeof cde);
console.log(abc === fgh);
console.log(typeof def);
console.log(efg === def);
console.log(typeof efg);
console.log(efg === fgh);
console.log(typeof fgh);
console.log(bcd === def);
console.log(abc + bcd);
console.log(null === undefined);
console.log(bcd + " test");
console.log(NaN === undefined);
console.log(efg + " test");
console.log('\0' === null);
console.log('\0' === NaN);
var abc = ''
console.log(abc + bcd + def); . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 15 / 23
Variable and Constants Differences between null and undefined

Differences between null and undefined

❂ The type of null variable is object whereas the type of undefined variable is undefined.
let abc= null, bcd; console.log(typeof abc); console.log(typeof bcd);

❂ null variable treated as 0 in an numeric expression whereas undefined variable will be NaN.
let abc= null, bcd;
console.log(abc + 10); console.log(bcd + 10)

[Homework] What will be the output for the following code segments?
function abc(){ function abc(){
console.log("Hello world"); return("Hello world");
} }
console.log(abc()); console.log(abc());
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 16 / 23
Variable and Constants Differences between var and let

Differences between var and let

Scope of variable defined using var is the function, where it is defined, whereas, the scope
of variable defined using let is the block, where it is defined.

function abc{ function abc{


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

The let keyword is actually coming from ES6 (ECMAScript) environment. Thus, the
concept of block-scope is new to JavaScript introduced in 2015.

A variable is said to be in temporal dead zone from the start of the block until initializa-
tion.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 17 / 23
Variable and Constants Scope of variables

Accessibility of variables

Variables declared with var are accessible in their scope even before they are declared,
whereas, let variables are not initialized until their definition is evaluated. Accessing them
before the initialization will result ReferenceError in case of let and undefined in case of
var.

function abc() { function abc() {


console.log(abc); console.log(abc);
var abc = "abc"; let abc = "abc";
console.log(abc); console.log(abc);
} }
abc(); abc();

Accessibility of a variable even before it is declared is known as hoisting


. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 18 / 23
Variable and Constants Re-declaration

Re-declaration
❂ Variables declared using var can be re-declared within the scope of declaration, whereas, variables
declared using let can not-be re-declared.

let abc = "abc";


var abc = "abc"; let abc = 1.1;
var abc = 1.1; SyntaxError: Identifier 'abc' has already
!→ been declared
❂ Without let and var also a variable can be declared [c.f abc variable inside function fun()]. The
scope of the variable in such case will be global.
var abc = "abc"; console.log(abc); //abc

fun(); console.log(abc); //testing


function fun(){abc = "testing";}

var abc = 1.1; console.log(abc); //1.1


. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 19 / 23
Variable and Constants Constant

Constant

❂ const keyword is used to declare a constant.


❂ The value of the constant can not be changed and needs to initialize during declaration itself.
const PI = 3.14;

PI = 3.14159;
TypeError: Assignment to constant variable.

const PI;
SyntaxError: Missing initializer in const declaration
❂ The value of a constant can not be changed but the content of the value can be changed. For
example, if an object is assigned to a constant, the underlying value of that object can be changed.
const ORG = { name: 'IIIT'}; ORG.name = "NIT"; console.log(ORG.name);

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 20 / 23
Variable and Constants Type conversion

Type Conversion: Explicit

❂ Number to string

✍ Using global method String(). let num = 1; console.log(String(num));


✍ Concatenate the number with an empty string.
let num = 1; let str = "" + num; console.log(typeof(str));
✍ Using tostring let num = 1; let str = num.toString(); console.log(typeof(str));
✍ Using base with tostring(base)
let num = 10; let str = num.toString(8); console.log(typeof(str));

❂ String to a number using in-built functions

✍ Using unary + operator let str = "1.11"; let num = + str;


✍ let str = "1.11"; let num = parseInt(str); console.log(typeof(num));
✍ let str = "1.11"; let num = parseInt(str); console.log(typeof(num));
✍ let str = "1.0px"; let num = parseFloat(str); console.log(typeof(num));
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 21 / 23
Variable and Constants Type conversion

Type Conversion: Explicit

❂ Float to an integer using in-built functions

✍ let flt = 1.11; let num = parseInt(flt); console.log(num);

✍ let flt = 1.11; let num = Math.round(flt); console.log(num);

✍ let flt = 1.11; let num = Math.ceil(flt); console.log(num);

✍ let flt = 1.11; let num = Math.floor(flt); console.log(num);

❂ Homework: console.log(typeof(num)); will give number. Define functions to compute sub-types of


number, such as, float, and integer.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 22 / 23
Variable and Constants Type conversion

Comments

❂ Comments are similar to C, C++ or Java programming language:

✍ Between // and the end of the line

✍ Between /* and */

✍ Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments; they have
no special meaning in JavaScript

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in JavaScript 23 / 23

You might also like