Web Development
Web Development
Web Development
Introduction
JavaScript Engine
Alerts and Prompts
Data Types
Variables
Strings
3
JavaScript
The programs in this language are called scripts. They can be written right in a
web page’s HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special
preparation or compilation to run.
In this aspect, JavaScript is very different from another language called Java.
4
JavaScript
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled
programming language with first-class functions.
null type
The null type has exactly one value: null. See null and Null for more details.
myVar; //null
“undefined” Type
A variable that has not been assigned a value has the value undefined.
The Number type is a double-precision 64-bit binary format IEEE 754 value
(numbers between -(2^53 − 1) and 2^53 − 1).
The number type has only one integer with two representations: 0 is represented
as both -0 and +0. (0 is an alias for +0.)
In practice, this has almost no impact. For example, +0 === -0 is true. However, you
are able to notice this when you divide by zero:
> 42 / +0 Infinity
> 42 / -0 -Infinity
BigInt Type
The BigInt type is a numeric primitive in JavaScript that can represent integers
with arbitrary precision. With BigInts, you can safely store and operate on large
integers even beyond the safe integer limit for Numbers.
const x = 2n ** 53n;
9007199254740992n
const y = x + 1n;
9007199254740993n
String Type
JavaScript's String type is used to represent textual data. Each element in the String occupies a
position in the String. The first element is at index 0, the next at index 1, and so on. The length of
a String is the number of elements in it.
Unlike some programming languages (such as C), JavaScript strings are immutable. This means
that once a string is created, it is not possible to modify it.
However, it is still possible to create another string based on an operation on the original string.
For example:
A Symbol is a unique and immutable primitive value and may be used as the
key of an Object property. In some programming languages, Symbols are
called "atoms".
The above code creates three new Symbols. Note that Symbol("foo")
does not coerce the string "foo" into a Symbol. It creates a new
Symbol each time.
Symbol Type
using var
using let
using const
using nothing
The scope is global when a var variable is declared outside a function. This means that
any variable that is declared with var outside a function block is available for use in the
whole window.
var is function scoped when it is declared within a function. This means that it is
available and can be accessed only within that function.
Example - Global Example - Local
var Declarations
var variables can be re-declared and updated.
This means that we can do this within the same scope and won't get
an error.
It is interpreted as this:
Problem with var
There's a weakness that comes with var. I'll use the example below to
explain:
So, since times > 3 returns true, greeter is redefined to "say Hello
instead". While this is not a problem if you knowingly want greeter to
be redefined, it becomes a problem when you do not realize that a
variable greeter has already been defined before.
Scope of let
let is now preferred for variable declaration. let is block scoped.
Just like var, a variable declared with let can be updated within its scope.
Unlike var, a let variable cannot be re-declared within its scope. So while
this will work:
Hoisting of let
Just like var, let declarations are hoisted to the top.
This means that the value of a variable declared with const remains the same
within its scope. It cannot be updated or re-declared. So if we declare a
variable with const, we can neither do this:
Scope of Const
Hoisting of const
Just like let, const declarations are hoisted to the top but are not
initialized.
So just in case you missed the differences, here they are:
var declarations are globally scoped or function scoped while let and
const are block scoped.
var variables can be updated and re-declared within its scope; let
variables can be updated but not re-declared; const variables can
neither be updated nor re-declared.
They are all hoisted to the top of their scope. But while var variables
are initialized with undefined, let and const variables are not
initialized.
While var and let can be declared without being initialized, const must
be initialized during declaration.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Expected Outcome:
654321
Numbers
Math Object
Math.property (Constants)
Randomization – Math.random()
Math.random();
Exercise
Exercise
Create a Dice Game, where two players roll the dice at the same time and
whoever gets the higher score in dice roll is declared winner.
Hints:
1. Use the Math.random and restrict the value between 1 and 6 (both
included).
2. Use comparator operator
Operators
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Operators
Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Operators
Comparator Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Operators
Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
Collection - Arrays
Arrays
An array is a special variable, which can hold more than one value:
const fruits= [“apple", “banana", “guava"];
Syntax:
const array_name = [item1, item2, ...];
The following example also creates an Array, and assigns values to it:
Example
const fruits= new Array(“apple", “banana", “guava");
Loops
Loops can execute a block of code a number of times.
JavaScript supports different kinds of loops:
** Strict Comparison
Switch cases use strict comparison (===).
The values must be of the same type to match.
Objects
Objects
There are multiple ways in which objects can be created in Javascript.
Method 1
Object Constructor
The simplest way to create an empty object is using the Object constructor.
Currently this approach is not recommended.
The object literal syntax (or object initializer), is a comma-separated set of name-
value pairs wrapped in curly braces.
var object = {
name: "Sudheer“,
age: 34
};
Function constructor:
Create any function and apply the new operator to create object instances,
function Person(name) {
this.name=name;
this.age=21;
}
var object = new Person("Sudheer");
function Person(){} Person.prototype.name = "Sudheer"; var object = new Person();
This is similar to function constructor but it uses prototype for their properties and
methods,
function Person() { }
Person.prototype.name = "Sudheer";
var object = new Person();
function Person(){} Person.prototype.name = "Sudheer"; var object = new Person();
class Person {
constructor(name) {
this.name = name;
}
}
Singleton pattern:
A Singleton is an object which can only be instantiated one time. Repeated calls to
its constructor return the same instance and this way one can ensure that they
don't accidentally create multiple instances.
Create the logic for your own Juke Box - Music Player App.
Expected Outcome
Declaring a Function
The syntax to declare a function is:
Different invocation patterns can produce vastly different results. Let us understand the four patterns, how to
use them and what to watch out for. The four invocation patterns are:
1. Method Invocation
2. Function Invocation
3. Constructor Invocation
Function Execution
JavaScript (like all languages these days) has the ability to modularize logic in functions which
can be invoked at any point within the execution.
The invocation operator is a pair of round brackets (), that can contain zero or more
expressions separated by a comma.
Boolean and Null Type
JavaScript Functions
Even though there is only one invocation operator (), there are four invocation patterns. Each pattern
differs in how the this parameter is initialized.
Method Invocation
When a function is part of an object, it is called a method. Method invocation is the pattern of invoking a
function that is part of an object.
Syntax
var obj = {
value : 0 ,
increment : function() {
this.value+=1;
}
};
myObject.fullName();
JavaScript Functions Boolean and Null Type
Function Invocation
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked.
myFunction(50, 60);
JavaScript Functions Boolean and Null Type
Constructor Invocation
It looks like you create a new function, but since JavaScript functions are objects you actually create a
new object.
A constructor invocation creates a new object. The new object inherits the properties and methods from its
constructor.
Example // This is a function constructor:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
The apply() method is similar to the call() method. With the apply() method, you can write a method that
can be used on different objects.
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
Function Borrowing
With the bind() method, an object can borrow a method from another object.
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
Anonymous Function is a function that does not have any name associated with it.
Normally we use the function keyword before the function name to define a function in JavaScript,
however, in anonymous functions in JavaScript, we use only the function keyword without the function
name.
An anonymous function is not accessible after its initial creation, it can only be accessed by a
variable it is stored in as a function as a value. An anonymous function can also have multiple
arguments, but only one expression.
Syntax
function() {
// Function Body
}
JavaScript Functions Boolean and Null Type
Anonymous Functions
Example:
console.log("Welcome to GeeksforGeeks!");
};
greet();
JavaScript Closures Boolean and Null Type
What is a closure?
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s
variables — a scope chain.
it has access to its own scope — variables defined between its curly brackets
In order to understand it better, please refer to the link below (one of best explanation):
https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4
JavaScript “this” Boolean and Null Type
What is “this”
When a web page is loaded, the browser creates a Document Object Model
of the page.
In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
DOM Boolean and Null Type
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
JavaScript can change all the HTML elements in the page
– Every Object in the DOM document tree has properties and methods
defined by the Node host object
Boolean and Null Type
Document Tree: Node
Boolean and Null Type
Document Tree: Node
The HTML DOM can be accessed with JavaScript (and with other programming languages).
A property is a value that you can get or set (like changing the content of an HTML element).
To do so, you have to find the elements first. There are several ways to do this: