JavaScript
• JavaScript is a programming language that allows you to create dynamic
and interactive web pages. It is the most popular programming
language.
• JavaScript is a case-sensitive language. This means that language
keywords, variables, function names, and any other identifiers must
always be typed with a consistent capitalization of letters.
• JavaScript is a programming language initially designed to interact with
elements of web pages
• JavaScript allows us to add interactivity to a web page. Typically, we use
JavaScript with HTML and CSS to enhance a web page’s functionality,
such as validating forms etc.
• The JavaScript engine is a program that executes JavaScript code. In the
beginning, JavaScript engines were implemented as interpreters.
• However, modern JavaScript engines are typically implemented as just-
in-time compilers that compile JavaScript code to bytecode for improved
performance.
Client-side vs. Server-side JavaScript
When JavaScript is used on a web page, it is executed in web browsers. In this
case, JavaScript works as a client-side language.
JavaScript can run on both web browsers and servers. A popular JavaScript
server-side environment is Node.js. Unlike client-side JavaScript, server-side
JavaScript executes on the server and allows you to access databases, file
systems, etc.
Initially when JS was invented by Brendan Eich in 1995, it was supposed to
function only as a scripting language on the client side for web development.
However, JS has evolved and diversified a lot in many other domains like -
Server side programming, Desktop application development, Mobile
Application development, Virtual Reality, Machine Learning etc. Here are few
Examples of different Technologies & Frameworks where JavaScript is used –
Node.JS: Used in server side programming - complete framework for server
side development.
React JS: It’s a front-end library developed by Facebook. Using React JS you
can create web as well as mobile applications.
React Native: It’s a JavaScript framework for writing real, natively rendering
mobile applications for iOS and Android.
AngularJS: It’s a JavaScript MVC framework to develop a dynamic web
application. Started by google but its open source.
Electron JS: It’s a framework used to build desktop apps with JavaScript,
HTML, and CSS
How to Add JavaScript to HTML
There are two ways to add JavaScript to HTML: the first is to embed inline JS
code into HTML, while the second requires us to create an external JS file.
Embed JavaScript code on an HTML page
Placing JavaScript code inside the <script> element directly is not
recommended and should be used only for proof of concept or testing
purposes.
The JavaScript code in the <script> element is interpreted from top to bottom.
For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
<script>
alert('Hello, World!');
</script>
</head>
<body>
</body>
</html>
Include an external JavaScript file
To include a JavaScript from an external file:
First, create a file whose extension is .js e.g., app.js and place it in the js
subfolder. Note that placing the JavaScript file in the js folder is not required
however it is a good practice.
Then, use the URL to the JavasScript source code file in the src attribute of the
<script> element.
The following shows the contents of the app.js file:
alert('Hello, World!');
Code language: JavaScript (javascript)
And the following shows the helloworld.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
<script src="js/app.js"></script>
</head>
<body>
</body>
Whitespace
Whitespace refers to characters that provide the space between other
characters. JavaScript has the following whitespace:
• Carriage return
• Space
• New Line
• tab
JavaScript engine ignores whitespace. However, you can use whitespace to
format the code to make it easy to read and maintain.
The following JavaScript code doesn’t use whitespace:
let formatted = true; if (formatted) {console.log('The code is easy to read');}
It is equivalent to the following code that uses whitespace. Hence, this code is
much easier to read:
let formatted = true;
if (formatted) {
console.log('The code is easy to read');
}
Note that JavaScript bundlers remove all whitespace from JavaScript files and
put them into a single file for deployment. By doing this, JavaScript bundlers
make the JavaScript code lighter and faster to load in web browsers.
Statements
A statement is a code that declares a variable or instructs the JavaScript engine
to do a task. A simple statement is terminated by a semicolon (;).
Although the semicolon (;) is optional; you should always use it to terminate a
statement. For example, the following declares a variable and shows it to the
console:
let message = "Welcome to JavaScript";
console.log(message);
Blocks
A block is a sequence of zero or more simple statements. A block is delimited
by a pair of curly brackets {}. For example:
if (condition) {
console.log(statement);
}
Comments
Comments allow you to add notes or hints to JavaScript code. When executing
the code, the JavaScript engine ignores the comments.
JavaScript supports single-line and block comments.
Single-line comments
A single-line comment starts with two forward-slashes characters (//). A single-
line comment makes all the text following the // on the same line into a
comment. For example:
// this is a single-line comment
Block comments
A delimited comment begins with a forward slash and asterisk /* and ends
with the opposite */ as in the following example:
/* This is a block comment
that can span multiple lines */
Expressions
An expression is a piece of code that evaluates to a value. For example:
2+1
The above expression returns three.
JavaScript Variables
A variable is a label that references a value like a number or string. Before
using a variable, we need to declare it.
Declare a variable
To declare a variable, we use the var keyword followed by the variable name
as follows:
var message;
A variable name can be any valid identifier. By default, the message variable
has a special value undefined if you have not assigned a value to it.
Variable names follow these rules:
• Variable names are case-sensitive. This means that the message and
Message are different variables.
• Variable names can only contain letters, numbers, underscores, or dollar
signs and cannot contain spaces. Also, variable names must begin with a
letter, an underscore (_) or a dollar sign ($).
• Variable names cannot use the reserved words.
By convention, variable names use camelcase like message, yourAge, and
myName.
JavaScript is a dynamically typed language. This means that we don’t need to
specify the variable’s type in the declaration like other static-typed languages
such as Java or C#.
Starting in ES6, we can use the let keyword to declare a variable like this:
let message;
It’s a good practice to use the let keyword to declare a variable.
Initialize a variable
Once we declared a variable, we can initialize it with a value. To initialize a
variable, we specify the variable name, followed by an equals sign (=) and a
value.
For example, The following declares the message variable and initializes it with
a literal string "Hello":
let message;
message = "Hello";
To declare and initialize a variable at the same time, we use the following
syntax:
let variableName = value;
For example, the following statement declares the message variable and
initializes it with the literal string "Hello":
let message = "Hello";
JavaScript allows us to declare two or more variables using a single statement.
To separate two variable declarations, you use a comma (,) like this:
let message = "Hello", counter = 100;
Since JavaScript is a dynamically typed language, we can assign a value of a
different type to a variable. Although, it is not recommended. For example:
let message = 'Hello';
message = 100;
Change a variable
Once you initialize a variable, you can change its value by assigning a different
value. For example:
let message = "Hello";
message = 'Bye';
Code language: JavaScript (javascript)
Undefined vs. undeclared variables
It’s important to distinguish between undefined and undeclared variables.
An undefined variable is a variable that has been declared but has not been
initialized with a value. For example:
let message;
console.log(message); // undefined
In this example, the message variable is declared but not initialized. Therefore,
the message variable is undefined.
In contrast, an undeclared variable is a variable that has not been declared. For
example:
console.log(counter);
Code language: JavaScript (javascript)
Output:
console.log(counter);
Constants
A constant holds a value that doesn’t change. To declare a constant, we use
the const keyword. When defining a constant, we need to initialize it with a
value. For example:
const workday = 5;
Once we define a constant, we cannot change its value.
The following example attempts to change the value of the workday constant
to 4 and causes an error:
workday = 2;
Error:
Uncaught TypeError: Assignment to constant variable.
JavaScript Data Types
JavaScript has the primitive data types:
1. null
2. undefined
3. boolean
4. number
5. string
6. symbol – available from ES2015
7. bigint – available from ES2020
JavaScript is a dynamically typed language. It means that a variable doesn’t
associate with a type. In other words, a variable can hold a value of different
types. For example:
let counter = 120; // counter is a number
counter = false; // counter is now a boolean
counter = "foo"; // counter is now a string
To get the current type of the value that the variable stores, we will use the
typeof operator:
let counter = 120;
console.log(typeof(counter)); // "number"
counter = false;
console.log(typeof(counter)); // "boolean"
counter = "Hi";
console.log(typeof(counter)); // "string"
The undefined type
The undefined type is a primitive type that has only one value undefined. By
default, when a variable is declared but not initialized, it is assigned the value
of undefined.
Consider the following example:
let counter;
console.log(counter); // undefined
console.log(typeof counter); // undefined
In this example, the counter is a variable. Since counter hasn’t been initialized,
it is assigned the value undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when
you call it on a variable that hasn’t been declared:
console.log(typeof undeclaredVar); // undefined
The null type
The null type is the second primitive data type that also has only one value
null. For example:
let obj = null;
console.log(typeof obj); // object
The typeof null returns object is a known bug in JavaScript. A proposal to fix
this was proposed but rejected. The reason was the that fix would break a lot
of existing sites.
JavaScript defines that null is equal to undefined as follows:
console.log(null == undefined); // true
Code language: JavaScript (javascript)
The number type
JavaScript uses the number type to represent both integer and floating-point
numbers.
The following statement declares a variable and initializes its value with an
integer:
let num = 100;
To represent a floating-point number, you include a decimal point followed by
at least one number. For example:
let price= 12.5;
let discount = 0.05;
Note that JavaScript automatically converts a floating-point number into an
integer number if the number appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-
point value uses twice as much memory as an integer value. For example:
let price = 200.00; // interpreted as an integer 200
To get the range of the number type, we use Number.MIN_VALUE and
Number.MAX_VALUE. For example:
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
Also, we can use Infinity and -Infinity to represent the infinite number. For
example:
console.log(Number.MAX_VALUE + Number.MAX_VALUE); // Infinity
console.log(-Number.MAX_VALUE - Number.MAX_VALUE); // -Infinity
NaN
NaN stands for Not a Number. It is a special numeric value that indicates an
invalid number. For example, the division of a string by a number returns NaN:.
console.log('a'/2); // NaN;
The NaN has two special characteristics:
Any operation with NaN returns NaN.
The NaN does not equal any value, including itself.
Here are some examples:
console.log(NaN/2); // NaN
console.log(NaN == NaN); // false
The string type
In JavaScript, a string is a sequence of zero or more characters. A string literal
begins and ends with either a single quote(') or a double quote (").
A string that begins with a double quote must end with a double quote.
Likewise, a string that begins with a single quote must also end with a single
quote:
let greeting = 'Hi';
let message = "Bye";
If we want to single quote or double quotes in a literal string, we need to use
the backslash to escape it. For example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')
JavaScript strings are immutable. This means that it cannot be modified once
created. However, we can create a new string from an existing string. For
example:
let str = 'JavaScript';
str = str + ' String';
In this example:
First, declare the str variable and initialize it to a string of 'JavaScript'.
Second, use the + operator to combine 'JavaScript' with ' String' to make its
value as 'Javascript String'.
Behind the scene, the JavaScript engine creates a new string that holds the
new string 'JavaScript String' and destroys the original strings 'JavaScript' and '
String'.
The following example attempts to change the first character of the string
JavaScript:
let s = 'JavaScript';
s[0] = 'j';
console.log(s)
The output is:
'JavaScript'
But not:
'javaScript'
The boolean type
The boolean type has two literal values: true and false in lowercase. The
following example declares two variables that hold the boolean values.
let inProgress = true;
let completed = false;
console.log(typeof completed); // boolean
JavaScript allows values of other types to be converted into boolean values of
true or false.
To convert a value of another data type into a boolean value, we use the
Boolean() function. The following table shows the conversion rules:
Type true false
string non-empty string empty string
number non-zero number and Infinity 0, NaN
objectnon-null object null
undefined undefined
For example:
console.log(Boolean('Hi'));// true
console.log(Boolean('')); // false
console.log(Boolean(20)); // true
console.log(Boolean(Infinity)); // true
console.log(Boolean(0)); // false
console.log(Boolean({foo: 100})); // true on non-empty object
console.log(Boolean(null));// false
The symbol type
JavaScript added a primitive type in ES6: the symbol. Different from other
primitive types, the symbol type does not have a literal form.
To create a symbol, we call the Symbol function as follows:
let s1 = Symbol();
The Symbol function creates a new unique value every time we call it.
console.log(Symbol() == Symbol()); // false
The bigint type
The bigint type represents the whole numbers that are larger than 253 – 1. To
form a bigint literal number, we can append the letter n at the end of the
number:
let pageView = 9007199254740991n;
console.log(typeof(pageView)); // 'bigint'
Console log()
All modern browsers have a web console for debugging. The console.log()
method is used to write messages to these consoles. For example,
let sum = 44;
console.log(sum); // 44
console.log() Syntax
Its syntax is:
console.log(message);
Here, the message refers to either a variable or a value.
Example 2: Print Values Stored in Variables
// program to print variables values
// storing values
const greet = 'Hello';
const name = 'Jack';
console.log(greet + ' ' + name);
HTML DOM Document write()
The write() method writes directly to an open (HTML) document stream.
Write some text directly to the HTML output:
document.write("Hello World!");
Write some HTML elements directly to the HTML output:
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
Identifier
An identifier is a sequence of characters in the code that identifies a variable,
function, or property. In most languages, identifiers are case-sensitive and not
quoted.
Rules for Naming JavaScript Identifiers
• In JavaScript, identifiers can contain letters(A-Z,a-z),$, _, and digits (0-9),
but may not start with a digit.
• Identifier names must start with either a letter, an underscore _, or the
dollar sign $.
• Identifier names cannot start with numbers. For example,
• JavaScript is case-sensitive. So y and Y are different identifiers.
• Identifiers cannot contain blank space
JavaScript Keywords
Keywords are reserved words that are part of the syntax in the programming
language.
• Keywords cannot be used as identifier names.
JavaScript Variables
To define a variable in JavaScript, you use var keyword. For example:
var x = 10;
var y = 20;
Code language: JavaScript (javascript)
ES6 added a new way to declare a variable with the let keyword:
let x = 10;
let y = 20;
There are differences between var and let. And it’s a good practice to use the
let keyword to declare variables.
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
• Automatically
• Using var
• Using let
• Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
z = x + y;
It is considered good programming practice to always declare variables before
use.
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Example using var
var x = 5;
var y = 6;
var z = x + y;
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.
Difference between var and let in JavaScript
In the early days of JavaScript, there was only one way of declaring variables
and that was using the var keyword. A variable declared with var is defined
throughout the program. One of the issues with using the var keyword was
redeclaring a variable inside a block will also redeclare the variable outside the
block. Latest JavaScript come with two more keywords, let and const came into
the picture. var and let are both used for variable declaration in JavaScript but
the difference between them is that var is function scoped and let is block
scoped.
Prefer not to use var because of issue in block scope and function scope
let accountState; // if we don’t define value of the variable then value is
undefined
Undefined Vs Null in JavaScript
Null in JavaScript means an empty value and is also a primitive type in
JavaScript. The variable which has been assigned as null contains no
value. Undefined, on the other hand, means the variable has been declared,
but its value has not been assigned. Null is an object
JavaScript typeof Operator
The typeof operator returns the type of variables and values. For example,
const a = 9;
console.log(typeof a); // number
console.log(typeof '9'); // string
console.log(typeof false); // boolean
let accountId=123
document.write(typeof accountId)
console.log(typeof null)
console.log(typeof(accountId)); //we can use as a typeof as method
Number
The Number constructor contains constants and methods for working with
numbers. Values of other types can be converted to numbers using the
Number() function.
When used as a function, Number(value) converts a string or other value to the
Number type. If the value can't be converted, it returns NaN (The NaN global
property is a value representing Not-A-Number.)
For example
let score="33"
console.log(typeof(score))
let valueInNumber=Number(score)
console.log(typeof(valueInNumber))
let num="3A"
let numinNumber=Number(num)
console.log(numinNumber)
The Boolean() Function
We can use the Boolean() function to find out if an expression (or a variable) is
true:
Everything With a "Value" is True
Examples
100
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
Everything Without a "Value" is False
The Boolean value of 0 (zero) is false:
let x = 0;
Boolean(x);
The Boolean value of -0 (minus zero) is false:
let x = -0;
Boolean(x);
The Boolean value of "" (empty string) is false:
let x = "";
Boolean(x);
The Boolean value of undefined is false:
let x;
Boolean(x);
The Boolean value of null is false:
let x = null;
Boolean(x);
The Boolean value of false is (you guessed it) false:
let x = false;
Boolean(x);
The Boolean value of NaN is false:
let x = 10 / "Hallo";
Boolean(x);
JavaScript switch Statement
The JavaScript switch statement is used in decision making.
The switch statement evaluates an expression and executes the corresponding
body that matches the expression's result.
The syntax of the switch statement is:
switch(expression) {
case value1:
// body of case 1