JavaScript Is The
JavaScript Is The
JavaScript is one of the top three core technologies of world wide web (www). The other two
are HTML & CSS.
As of 2022, 98% of websites use JavaScript on the client side for webpage behavior. (as per
w3techs)
JavaScript is a very free-form language compared to Java. You do not have to declare all
variables, classes, and methods.
Core JavaScript can be extended for a variety of purposes by supplementing it with
additional objects; for example:
1. (a) Client-side JavaScript extends the core language by supplying objects to control a browser
& its Document Object Model (DOM). For example, client-side extensions allow an
application to place elements on an HTML form and respond to user events such as mouse
clicks, form input, and page navigation.
2. (b) Server-side JavaScript extends the core language by supplying objects relevant to running
JavaScript on a server. For example, server-side extensions allow an application
to communicate with a database, provide continuity of information from one invocation to
another of the application, or perform file manipulations on a server.
What is JavaScript ?
first-class functions.
TERMINOLOGIES EXPLAINED
Programming Language :
1. (a) A programming language is any set of rules that converts strings, or graphical program
elements in the case of visual programming languages, to various kinds of machine code
output.
2. (b) Programming languages are one kind of computer language, and are used in computer
programming to implement algorithms.
1. (a) These are designed to have small memory footprint, are easy to implement (important
when porting a language to different computer systems)
2. (b) They have simple syntax and semantics, so one can learn them quickly and easily.
3. (c) Some lightweight languages : for Example - JavaScript, BASIC, Lisp, Forth, and Tcl
1. (a) just-in-time (JIT) compilation (also dynamic translation or run-time compilations) is a way
of executing computer code that involves compilation during execution of a program (at run
time) rather than before execution.
2. (b) This may consist of source code translation but is more commonly bytecode translation to
machine code, which is then executed directly.
1. (a) Are those where the interpreter assigns variables a type at runtime based on the variable's
value at the time.
2. (b) Most dynamic languages are also dynamically typed, but not all are. Dynamic languages are
frequently referred to as scripting languages.
3. (c) Popular dynamic programming languages include JavaScript, Python, Ruby, PHP, Lua and
Perl.
Prototype-based programming :
1. (a) Prototype-based programming is a style of object-oriented programming in which classes
are not explicitly defined, but rather derived by adding properties and methods to an
instance of another class or, less frequently, adding them to an empty object.
2. (b) In simple words: this type of style allows the creation of an object without first defining
its class.
1. (a) A programming language is said to have First-class functions when functions in that
language are treated like any other variable.
2. (b) For example, in such a language, a function can be passed as an argument to other
functions, can be returned by another function and can be assigned as a value to a variable.
Presentations
Flying Robots
1. (a) quadcopters come with a simple OS that makes it possible to install NodeJS.
2. (b) Which means, you can program a drone
Game development
History of JavaScript:
Brendan Eich created the JavaScript in 1995. At that time, web pages could only be
static, lacking the capability for dynamic behavior after the page was loaded in the browser.
JavaScript was called LiveScript earlier at Netscape corporation. It became very popular during
the dot-com boom.
ECMAScript standard
JavaScript Engines
JavaScript engine is a software component that executes JavaScript code and converts it into
computer understandable language. All relevant modern engines use just-in-time
compilation for improved performance. JavaScript engines are typically developed by web
browser vendors, and every major browser has one.
V8 from Google : is the most used JavaScript engine. Google Chrome and the many other
Chromium-based browsers use it.
SpiderMonkey : is developed by Mozilla for use in Firefox and its forks.
JavaScriptCore : is Apple's engine for its Safari browser. Other WebKit-based browsers
also use it.
Chakra : is the engine of the Internet Explorer browser.
Getting started with JavaScript is easy: all you need is a modern Web browser.
Install the either one of the prefered browsers like Google Chrome or Firefox Browser
Web Console
The Web Console tool built into browers like Google Chrome / Firefox is useful for
experimenting with JavaScript; you can use it in two modes: single-line input mode, and multi-
line input mode.
Single-line input in the Web Console : The Web Console shows you information about the
currently loaded Web page, and also includes a JavaScript interpreter that you can use to execute
JavaScript expressions in the current page. To open the Web Console (Ctrl + Shift + I on
Windows and Linux or Cmd-Option-K on Mac).
Multi-line input in the Web Console : The single-line input mode of the Web Console is
great for quick testing of JavaScript expressions, but although you can execute multiple lines, it's
not very convenient for that. If you want to write multiple lines of commands in the Chrome
console, first open the console (CMD + Shift + J on Mac / Ctrl + Shift + I on Windows). Now
while inside the Console, write any line of code, and then hold down Shift + Enter.
Syntax refers to the structure of the language, which is, what constitutes a correctly-formed
program.
/*
Invoking the function addNum()
and Printing the Output
*/
[Link](`The sum of ${value1} and ${value2} is ${addNum(value1, value2)}`)
OUTPUT
Enter the first number: 24
Enter the second number: 12
The sum of 24 and 12 is 36
This above script illustrates several of the important aspects of JavaScript syntax.
Let's walk through it and discuss some of the syntactical features of JavaScript.
Comments behave like whitespace, and are discarded during script execution.
Singleline Comments in JavaScript are indicated by two forward slash sign // and anything
on the line following the sign // is ignored by the interpreter.
This means, for example, that you can have stand-alone comments like the one just shown, as
well as inline comments that follow a statement. For example:
value1 = parseInt(prompt('Enter the first number: ')) // Input first number
JavaScript also has a syntax for multi-line comments, such as the /* */ syntax.
/*
Invoking the function addNum()
and Printing the Output
*/
This is an assignment operation, where a variable named total is assigned to sum of two
numbers num1 + num2
Notice that the end of this statement is simply marked by the end of the line. This is in
contrast to languages like C and C++, where every statement must end with a semicolon ;
Sometimes it can be useful to put multiple statements on a single line. This shows in the
example, how the semicolon ; familiar in C or Python Language, can be used optionally in
JavaScript to put two statements on a single line.
let value1 = 0
let value2 = 0
In addition, variables declared with let or const can belong to Block scope. This scope created
with a pair of curly braces { } (a block).
sumNumbers=12+34
sumNumbers = 12 + 34
sumNumbers = 12 + 34
Using whitespace effectively can lead to much more readable code, especially in cases where
operators follow each other - compare the following two expressions for exponentiating by a
negative number:
Observe that second version with spaces much is more easily readable at a single glance.
squareNumber=9**2
// Check the below with SPACES
squareNumber = 9 ** 2
Two major uses of parentheses. First, they can be used in the typical way to group statements
or mathematical operations:
12 * (34 + 56)
# 1080
Secondly, they can also be used to indicate that a function is being invoked (called).
In the below snippet, the addNum() is used to call the function with two arguments. The
function call is indicated by a pair of opening and closing parentheses, with the arguments to the
function contained within:
addNum(value1, value2)
Some functions can be called with no arguments at all, in which case the opening and closing
parentheses still must be used to indicate a function evaluation. An example of this is
the toUpperCase() method of string datatype.
The "()" after toUpperCase indicates that the function should be executed, and is required even
if no arguments are necessary.
// SKILLZAM
Inline JavaScript
Internal JavaScript
External JavaScript
Inline JavaScript
Inline JavaScript is used when we have to call a JavaScript method/function in the HTML
event attributes.
There are many events in which we have to add JavaScript code directly. Example
events: onmouseover, onclick, onchange etc.
There is no need to add the <script> tag in the HTML file.
For Example: The below HTML file contains a <button> tag, which has inline JavaScript
handler -
onclick="[Link]('You clicked the button!')"
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Add inline JavaScript to HTML</title>
</head>
<body>
</body>
</html>
OUTPUT
Click Me
Internal JavaScript
For Exmaple: In the below HTML code, the <script>...</script> tag inside
the <body> section, contains the JavaScript code to write a text (string) on the webpage:
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Add internal JavaScript to HTML</title>
</head>
<body>
</body>
</html>
OUTPUT
External JavaScript
For Example: the below mentioned HTML file contains External JavaScript file "[Link]",
which is added using <script> tag with src attribute.
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Add external JavaScript to HTML</title>
</head>
<body>
</body>
</html>
Below JavaScript code is added to external file [Link] without adding the <script> tag
OUTPUT
Display data in JavaScript
[Link]() : method shows an alert box with the defined message and an OK button in
an HTML document i.e. writing into an alert box.
[Link]() : method aims to display some particular content in the browser window
i.e. writing into the HTML output.
[Link]() : method outputs a message to the web console. The message may be a
single string (with optional substitution values), or it may be any one or more JavaScript objects.
innerHTML : property sets or returns the HTML content (inner HTML) of an element i.e.
writing into an HTML element.
NOTE: JavaScript does not have any print object or print methods. You cannot access output
devices from JavaScript.
// Using alert() method - alert box with a message
alert("Hello World - By alert() method");
JavaScript Statement
A JavaScript program is a list of programming statements.
JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and
Comments.
The statements are executed, one by one, in the same order as they are written.
Semicolons ( ; ) separate JavaScript statements.
JavaScript ignores multiple spaces & is a case-sensitive language.
// JavaScript Statement
let amount = 88 + 2;
[Link](amount)
OUTPUT
90
Variables
The syntax of a programming language refers to structure of the language, that is, what
constitutes a legal program.
The semantics of a programming language refers to the meaning of a legal program.
We will now understand the semantics of identifier keywords variables which are the main
ways you store, reference, and operate on data within a JavaScript code.
Identifiers
JavaScript Identifier is the name given to identify a variable, function, class, module or
other object.
That means, whenever we want to give an entity a name, that's called identifier.
An identifier is used to link a value with a name.
In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (_),
and dollar signs ($).
Identifiers are not allowed to start with numbers.
JavaScript identifiers are not only limited to ASCII — many Unicode codepoints are allowed
as well.
Identifiers with special meanings: A few identifiers have a special meaning in some
contexts without being reserved words of any kind. They
include: arguments, as, async, eval, from, get, of, set
Keywords
Keywords have a special meaning in a language, and are part of the syntax. Example:
Reserved Words : Some keywords are reserved, meaning that cannot be used as an
identifier for variable declarations, function declarations, etc.
NOTE: 16 reserved words in BOLD, have been removed from ECMAScript 5/6 standard.
Variables
1. - Using var
2. - Using let
3. - Using const
4. - Using nothing
[Link]($price)
[Link](PI)
[Link](premium)
[Link](deductible)
OUTPUT
12
3.142
12500.25
500
Naming Variable
OUTPUT
The value of total is: 11
OUTPUT
The total is: 10
OUTPUT
FIFA World Cup 2022
let salary;
[Link]("The salary amount is : " + salary)
OUTPUT
The salary amount is : undefined
const intNum = 3;
const str = "31"; // Numbers within quotes will be treated as
strings
let sumUp = str + intNum; // concatenation of number and string
[Link]("Result (sumUp) is : " + sumUp + " and the typeof is : " +
typeof(sumUp))
OUTPUT
Result (sumUp) is : 313 and the typeof is : string
User defined Variable names with more than one word can be difficult to read.
There are several ways you can use to make them more readable:
1. Camel Case
Variable names where each word, except the first, starts with a capital letter:
2. Snake Case
3. Pascal Case
1. - Using var
2. - Using let
3. - Using const
4. - Using nothing
Always declare a variable with const when you know that the value should not be changed.
Use const when you declare:
A new Array
A new Object
A new Function
A new Regex
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const
Variables declared inside a block "curly braces { }" cannot be accessed from outside the
block.
Variables defined with let or const have Block Scope.
Variables declared with the var cannot have block scope.
// JavaScript "let" Keyword to define variable
// Cannot redclare a block-scoped variable using (let)
OUTPUT
SyntaxError: Identifier 'favColor' has already been declared
Redeclaring Variables
Variables defined with let or const cannot be redeclared in the same block.
Redeclaring a variable with let, in another block, is allowed
Redeclaring a variable inside a block using the let keyword, will not redeclare the
variable outside the block.
Redeclaring a JavaScript variable with var is allowed anywhere in a program.
Redeclaring a variable inside a block using the var keyword, will also redeclare the
variable outside the block.
// JavaScript "var" Keyword to define variable
// Redeclaring a variable inside a block will also redeclare the variable
outside the block
// var has "NO" block scope
OUTPUT
Number of Goals scored : 2
OUTPUT
Within Block scope : 25
Outside the Block : 30
Reassigning Variables
try {
const PI = 3.141592653589793;
PI = 3.14; // TypeError
[Link](PI);
}
catch (err) {
[Link](err)
}
OUTPUT
TypeError: Assignment to constant variable.
JavaScript Hoisting
OUTPUT
ReferenceError: Cannot access 'countryName' before initialization
cityName = "Bengaluru";
const cityName; // SyntaxError
[Link]("City of residence : " + cityName)
OUTPUT
SyntaxError: Missing initializer in const declaration
JavaScript Operators
Now we'll dig into the semantics of the various operators included in JavaScript language.
1. Arithmetic Operators
22 / 7 // 3.142857142857143
22 / 0 // Infinity
31 % 2 // 1
2 ** 3 // 8
// Increment Operator
// Pre Increment
let i = 9
j = ++i
[Link]("i = " + i)
[Link]("j = " + j)
// Post Increment
let x = 9
y = x++
[Link]("x = " + x)
[Link]("y = " + y)
OUTPUT
i = 10
j = 10
x = 10
y = 9
// Decrement Operator
// Pre Decrement
let a = 9
b = --a
[Link]("a = " + a)
[Link]("b = " + b)
// Post Decrement
let p = 9
q = p--
[Link]("p = " + p)
[Link]("q = " + q)
OUTPUT
a = 8
b = 8
p = 8
q = 9
2. Bitwise Operators
let num = 8
[Link](2) // '1000'
// Bitwise AND
9 & 10 // 8
// 1001 (9 in Binary)
// & 1010 (10 in Binary)
//_______________________
// 1000 (8 in Binary)
// Bitwise OR
9 | 10 // 11
// 1001 (9 in Binary)
// | 1010 (10 in Binary)
//_______________________
// 1011 (11 in Binary)
// Bitwise XOR
9 ^ 10 // 3
// 1001 (9 in Binary)
// ^ 1010 (10 in Binary)
//_______________________
// 0011 (3 in Binary)
// Bitwise << 'Zero fill left shift'
4 << 1 // 8
// 0100 (4 in Binary)
// << 0001 (1 in Binary)
//_______________________
// 1000 (8 in Binary)
4 >> 1 // 2
// 0100 (4 in Binary)
// >> 0001 (1 in Binary)
//_______________________
// 0010 (2 in Binary)
4 >>> 1 // 2
// 0100 (4 in Binary)
// >>> 0001 (1 in Binary)
//_______________________
// 0010 (2 in Binary)
// Bitwise NOT
// JavaScript uses 32 bits signed integers, it will not return 10. It will
return -6.
// 00000000000000000000000000000101 (5)
// 11111111111111111111111111111010 (~5 = -6)
// A signed integer uses the leftmost bit as the minus sign
~5 // 10
// ~ 0101 (5 in Binary)
//_______________________
// 1010 (10 in Binary)
3. Assignment Operators
Assignment operator assigns a value to its left operand based on the value of its right
operand.
Simple assignment operator is = equal, which assigns the value of its right operand to its left
operand.
// Assignment Operator (=) equal
let assignNum = 66
[Link](assignNum)
// 66
We can use these variables in expressions with any of the operators mentioned earlier.
assignNum + 6
// 72
We might want to update the variable assignNum with this new value; in this case, we could
combine the addition and the assignment and write assignNum = assignNum + 6. Because this
type of combined operation and assignment is so common, JavaScript includes built-in update
operators for all of the arithmetic operations:
// Assignment Operator with addition (+=)
let assignNum = 66
assignNum += 6 // equivalent to assignNum = assignNum + 6
[Link](assignNum)
// 72
Each one is equivalent to the corresponding operation followed by assignment: that is, for any
operator "■" the expression a ■= b is equivalent to a = a ■ b with a slight catch.
// Demo the Add and Assignment Operators
let num1 = 6,
num2 = 2;
OUTPUT
Value of num1 = 8
let num1 = 6,
num2 = 2;
OUTPUT
Value of num1 = 4
let num1 = 6,
num2 = 2;
OUTPUT
Value of num1 = 12
OUTPUT
Value of num1 = 3.142857142857143
let num1 = 3,
num2 = 2;
num1 **= num2 // num1 = num1 ** num2
[Link]( "Value of num1 = " + num1)
OUTPUT
Value of num1 = 9
let num1 = 7,
num2 = 4;
OUTPUT
Value of num1 = 3
let num1 = 6,
num2 = 13;
// 0110 (6 in binary)
// & 1101 (13 in binary)
// ________
// 0100 = 4 (In decimal)
OUTPUT
Value of num1 = 4
let num1 = 6,
num2 = 13;
// 0110 (6 in binary)
// | 1101 (13 in binary)
// ________
// 1111 = 15 (In decimal)
OUTPUT
Value of num1 = 15
// Demo the Bitwise XOR Assignment Operator
let num1 = 9,
num2 = 10;
// 1001 (9 in Binary)
// ^ 1010 (10 in Binary)
//_______________________
// 0011 (3 in Binary)
OUTPUT
Value of num1 = 3
let num1 = 4,
num2 = 1;
// 0100 (4 in Binary)
// << 0001 (1 in Binary)
//_______________________
// 1000 (8 in Binary)
OUTPUT
Value of num1 = 8
let num1 = 4,
num2 = 1;
// 0100 (4 in Binary)
// >> 0001 (1 in Binary)
//_______________________
// 0010 (2 in Binary)
OUTPUT
Value of num1 = 2
// Demo the Logical AND assignment operator
let num1 = 9,
num2 = 10;
OUTPUT
Value of num1 = 10
let num1 = 9,
num2 = 10;
OUTPUT
Value of num1 = 9
OUTPUT
Value of num1 = 10
const player = {
sport : 'hockey',
country : 'India'
}
OUTPUT
Value of [Link] = Dhanraj Pillay
4. Comparison Operators
Comparison operators can be combined with the arithmetic and bitwise operators to express
a virtually limitless range of tests for the numbers.
For example, we can check if a number is odd by checking that the modulus with 2 returns 1:
// 13 is odd
13 % 2 == 1 // returns true
// 24 is even
24 % 2 == 0 // returns true
OUTPUT
true
false
false
let givenNum = 18
9 < givenNum < 19 // true
5. Logical Operators
Logical operators are typically used with Boolean (logical) values; when they are, they
return a Boolean value.
Logical operators are also used with non-Boolean values, they may return a the value of one
of the specified operands (non-Boolean value).
Logical operators are listed below:
Operator Usage Description
Returns a if it can be converted to false; otherwise, returns b. Thus, when
Logical a &&
used with Boolean values, && returns true if both operands are true;
AND b
otherwise, returns false.
Returns a if it can be converted to true; otherwise, returns b. Thus, when
Logical
a || b used with Boolean values, || returns true if either operand is true; if both
OR
are false, returns false.
Logical Returns false if its single operand that can be converted to true; otherwise,
!a
NOT returns true.
Boolean algebra aficionados might notice that the XOR operator is not included; this can of
course be constructed in several ways from a compound statement of the other operators.
Otherwise, a clever trick you can use for XOR of Boolean values is the following:
These sorts of Boolean operations will become extremely useful when we begin
discussing control flow statements such as conditionals and loops
6. Conditional Operators
Conditional operator is the only JavaScript operator that takes three operands.
The operator can have one of two values based on a condition.
Conditional operator is also know as “Question mark” or "Ternary" operator.
It is the simplified operator of if/else statement.
Conditional operator assigns a value to a variable based on some condition (true or false).
1. (a). Expression consists of three operands: the condition, valueOne and valueTwo.
2. (b). Evaluation of the condition should result in either true/false or a boolean value.
3. (c). The true value lies between “?” & “:” and is executed if the condition returns true.
Similarly, the false value lies after “:” and is executed if the condition returns false.
OUTPUT
Age of the citizen is 24 years.
Hence, citizen is eligible to vote!
typeof() Operator
typeof operator returns a string indicating the type of a variable or unevaluated operand.
Operand is the string, variable, keyword, or object for which the type is to be returned.
The parentheses are optional.
typeof operator has higher precedence than binary operators like addition (+).
SYNTAX :
typeof(operand)
typeof operand
Listed below are types returned from typeof operator :
// 'number'
// 'number'
// 'string'
// 'boolean'
let randNum;
typeof(randNum)
// 'undefined'
// typeof value returned from a 'null' operand
// 'object'
// 'bigint'
const player = {
fname: "Leo",
lname: "Messi",
position: "Forward"
};
// 'symbol'
function printVal () {
[Link]('Hello')
}
typeof printVal
// 'function'
// 'object'
const player = {
fname: "Leo",
lname: "Messi",
position: "Forward"
};
typeof player
// 'object'
Data Types
ECMAScript standard (ECMA-262) defines seven primitive data types.
To be able to operate on variables, it is important to know something about the type.
JavaScript has dynamic types. This means that the same variable can be used to hold
different data types.
All primitive datatype values are immutable i.e. whose content cannot be
changed without creating an entirely new value.
Using immutable datatypes has several benefits :
1. (1). To improve performance (no planning for the object's future changes)
2. (2). To reduce memory use (make object references instead of cloning the whole object)
3. (3). Thread-safety (multiple threads can reference the same object without interfering with one
other)
4. (4). Lower developer mental burden (the object's state won't change and its behavior is
always consistent)
Object wrapper
Each primitive type (except for the types of undefined and null) has a corresponding wrapper
class. The key purpose of these classes is to provide properties (mostly methods) for primitive
values.
Primitive Methods
JavaScript allows us to work with primitives (string, number, boolean, bigint, symbol) as
if they were objects. They also provide methods to call as such.
Objects are “heavier” than primitives. They require additional resources to support the
internal machinery.
primitive as an object:
For Example: There exists a string method slice() that returns a substring of a string.
OUTPUT
'Mum'
number
number is a built-in primitive data type in JavaScript.
number represents both integer and floating point numbers.
Numbers also includes Infinity, -Infinity and NaN (Not a Number).
Number is a numeric data type in the double-precision 64-bit floating point format.
Number are always stored as decimal numbers (floating point) in JavaScript.
Extra large or extra small numbers can be written with scientific (exponential) notation.
Integer Numbers i.e. numbers without a period or exponent notation are accurate up to 15
digits and maximum number of decimals is 17.
Number can also use underscore _ as the separator, which plays the role of the “syntactic
sugar”, it makes the number more readable. For Example: The
number 1_000_000_000 represents a million.
number is capable of safely storing integers in the range - (253-
1) (Number.MIN_SAFE_INTEGER) to 253- 1 (Number.MAX_SAFE_INTEGER).
number is capable of storing positive floating-point numbers between 2-
1074
(Number.MIN_VALUE) and 21024 (Number.MAX_VALUE)
Numerical values outside the range ± (2-1074 to 21024) are automatically converted:
const x = 5;
const y = 10.75;
const z = 0;
let value1 = x + y; // number datatype
let value2 = "string"/x; // NaN - Not a number
let value3 = x/z; // Infinity
[Link]("value1 = " + value1 + " and typeof(value1) is " + typeof(value1))
[Link]("value2 = " + value2 + " and typeof(value2) is " + typeof(value2))
[Link]("value3 = " + value3 + " and typeof(value3) is " + typeof(value3))
OUTPUT
value1 = 15.75 and typeof(value1) is number
value2 = NaN and typeof(value2) is number
value3 = Infinity and typeof(value3) is number
OUTPUT
123450000000000
Infinity
OUTPUT
addUp = Skillzam99 and typeof(addUp) is string
Infinity or -Infinity
[Link](Infinity); // Infinity
[Link](Infinity * 9); // Infinity
[Link]([Link](9, 999)); // Infinity
[Link]([Link](0)); // -Infinity
[Link](9 / Infinity); // 0
[Link](9 / 0); // Infinity
string
string is a built-in primitive data type in JavaScript.
string represents a collection of alphanumeric characters within a single quotes '...' or
double quotes "..." or Backticks `...`
Whenever you create a string by surrounding text with quotation marks, the string is called
a string literal.
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string.
For Example: 'Camel is called the "ship" of the desert'
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.
JavaScript strings are immutable. This means that once a string is created, it is not possible
to modify it.
Strings are encoded as a sequence of 16-bit unsigned integer values representing UTF-
16 code units.
String literals (denoted by double or single quotes) and strings returned from String() calls
in a non-constructor context (that is, called without using the new keyword) are primitive
strings.
String with new keyword returns a string wrapper object.
String primitives and String objects also give different results when using eval().
Primitives passed to eval() are treated as source code; String objects are treated as all other
objects are, by returning the object.
OUTPUT
Skillzam
OUTPUT
Learn without limits!
[Link](moreLine)
OUTPUT
A CURE platform:
- Cross-Skill
- Up-Skill
- Re-Skill
- Expert-Skill
OUTPUT
techHiring = [Link]
typeof(techHiring) is string
OUTPUT
playerType = Midfielder
typeof(playerType) is object
player = Ronaldinho is a Midfielder
typeof(player) is string
Under the hood the string Object wrapper "Midfielder" is of object type.
String {'Midfielder'}
0: "M"
1: "i"
2: "d"
3: "f"
4: "i"
5: "e"
6: "l"
7: "d"
8: "e"
9: "r"
length: 10
[[Prototype]]: String
[[PrimitiveValue]]: "Midfielder"
String Properties
Strings contain individual letters or symbols called characters and are immutable.
Strings have a length, defined as the number of characters the string contains.
Characters in a string appear in a sequence, which means that each character has a numbered
position in the string.
// String contains characters/symbols
OUTPUT
typeof strVar01 = string
typeof strVar02 = string
OUTPUT
Length of strVar03 = 12
OUTPUT
GATES
Escape Characters
OUTPUT
SyntaxError: Unexpected identifier 'ship'
OUTPUT
Camel is called the "ship" of the desert
Template literals
Multi-line Strings
[Link](multiLine)
OUTPUT
A CURE platform:
- Cross-Skill
- Up-Skill
- Re-Skill
- Expert-Skill
String Interpolation
Template literals are sometimes informally called template strings, because they are used
most commonly for string interpolation.
String Interpolation : It is the process of substituting values of variables or/and
expressions into placeholders in a string.
Placeholders : Template literals contains embedded expressions delimited by a dollar
sign $ and curly braces { } i.e. ${expression}.
// String interpolation using single variable placeholders
OUTPUT
Michael Phelps is called 'Flying Fish'!
[Link](txt)
OUTPUT
The Challenger Deep in the Mariana Trench, is the deepest part of the ocean.
const a = 1
const b = -8
const c = 15
const root1 = `Value of root1 = ${(-b + ((b**2 - 4*a*c)**0.5)) / (2*a)}`
const root2 = `Value of root2 = ${(-b - ((b**2 - 4*a*c)**0.5)) / (2*a)}`
OUTPUT
The roots of Quadratic Equation are :
Value of root1 = 5
Value of root2 = 3
Tagged Templates
A more advanced form of template literals are tagged templates.
Tags allow you to parse template literals with a function.
Tagged template is written like a function definition. However, do not pass
parentheses () when calling the literal.
The first argument of a tag function contains an array of string values. The remaining
arguments are related to the expressions.
// Template literals are also Tagged templates
if(isChampion) {
return `${str0}${champName}${str1}${champAge}${str2}`;
}
}
[Link](output);
OUTPUT
Garry Kasparov became the youngest ever undisputed World Chess Champion at 22.
String Concatenation
You can combine, or concatenate, two strings using the + operator or or concat() string
method.
let academy;
academy = 'Skill' + 'zam' // String Concatenation
[Link](academy)
OUTPUT
Skillzam
OUTPUT
Brendan Eich
String Indexing :
OUTPUT
undefined
OUTPUT
K
undefined
String Slicing :
You can extract a portion of a string, called a substring. This substring is called Slice
slice() method:
This string method returns part of the string from start to end(but not including).
If there is no second argument, then slice() goes till the end of the string.
slice() also allows for negative values for start and end arguments, which means the
position is counted from the string end (i.e. reverse indexing).
If end argument is omitted, undefined, or cannot be converted to a number
(using Number(end)), or if end >= [Link], slice() extracts to the end of the string.
It's important to note that, JavaScript won't raise an Error when you try to slice between
boundaries that fall outside the starting or ending boundaries of a string.
OUTPUT
'Mumbai'
when you try to get a slice in which the entire range is out of bounds, Instead of raising an
error, JavaScript returns the empty string ("").
OUTPUT
''
OUTPUT
'canã'
OUTPUT
Maracanã
String Methods
JavaScript allows us to work with primitives (string, number, boolean, bigint, symbol) as
if they were objects. They also provide methods to call as such.
In JavaScript these built-in methods / functions of these object, can perform actions or
commands on itself.
We call methods with a period and then method name. Methods are in the
form: [Link](parameters)
Here, parameters are extra arguments we can pass into the method.
JavaScript has many extremely useful string functions/methods; here are a few of them:
1. (1). slice() :
returns part of the string from start to end(but not including). If there is no second argument,
then slice() goes till the end of the string. slice() also allows for negative values
for start and end arguments, which means the position is counted from the string end (i.e.
reverse indexing).
If end parameter is omitted, undefined, or cannot be converted to a number
(using Number(end)), or if end >= [Link], slice() extracts to the end of the string.
OUTPUT
'Mum'
2. (2). substring() :
returns a new string containing characters of the calling string from (or between) the
specified index (or indices). The difference between slice() & substring() is
that start and end values less than 0 are treated as 0 in substring().
If end parameter is omitted, substring() extracts characters to the end of the string.
OUTPUT
'bai'
3. (3). substr() :
returns a portion of the string, starting at the specified index and extending for a given number
of characters (length) afterwards. The difference between slice() & substr() is that
the second parameter specifies the length of the extracted part.
If length is omitted or undefined, or if start + length >= [Link], substr() extracts
characters to the end of the string.
4. (4). replace() :
returns a new string with one, some, or all matches of a pattern replaced by a replacement.
The pattern can be a string or a RegExp, and the replacement can be a string or a
function called for each match. If pattern is a string, only the first occurrence will be
replaced. The original string is left unchanged. By default, the replace() method is case
sensitive.
OUTPUT
'Skillzam => Learn without limits!'
OUTPUT
Messi is the GOAT in football!
5. (5). replaceAll() :
OUTPUT
I love football. Most popular sport is "football".
let whatIfeel = 'I love cricket. Cricket is a team sport. Most popular sport
is "cricket".'
OUTPUT
I love football. Football is a team sport. Most popular sport is "football".
6. (6). toUpperCase() :
returns the calling string value converted to uppercase (the value will be converted to a string
if it isn't one). This method does not affect the value of the string itself since JavaScript strings
are immutable.
SYNTAX : toUpperCase()
OUTPUT
'SKILLZAM - LEARN WITHOUT LIMITS!'
7. (7). toLowerCase() :
returns the value of the string converted to lower case. toLowerCase() does not affect the
value of the original string itself.
SYNTAX : toLowerCase()
const pangram = "The quick brown FOX jumps over the lazy DOG."
const lowerPangram = [Link]()
[Link](lowerPangram)
OUTPUT
the quick brown fox jumps over the lazy dog.
removes whitespace from both sides of a string and returns a new string, without modifying
the original string. To return a new string with whitespace trimmed from just one end,
use trimStart() or trimEnd().
SYNTAX :
trim()
trimStart()
trimEnd()
let fastestBird = " Peregrine Falcon is the fastest bird in the world. "
OUTPUT
Peregrine Falcon is the fastest bird in the world.
Peregrine Falcon is the fastest bird in the world.
'Peregrine Falcon is the fastest bird in the world. '
pads the current string with another string (multiple times, if needed) until the resulting string
reaches the given length. In padStart(), padding is applied from the start of the current
string. In padEnd(), padding is applied from the end of the current string. The default value
for padString parameter is unicode "space" (" ") , character (U+0020).
SYNTAX :
padStart(targetLength [, padString])
padEnd(targetLength [, padString])
// Demo1 : padStart()
const numStart = '7';
[Link]([Link](3, '0')); // string output: 007
// Demo2 : padStart()
const cardNumber = '4321987612346789';
const lastFour = [Link](-4);
const cardMask = [Link]([Link], '*');
[Link](cardMask); // string output: ************6789
OUTPUT
007
************6789
// Demo1 : padEnd()
const numEnd = '7';
[Link]([Link](3, '0')); // string output: 700
// Demo2 : padEnd()
const cellNumber = '7173334444';
const firstThree = [Link](0,3);
const cellMask = [Link]([Link], '*');
[Link](cellMask); // string output: 717*******
OUTPUT
700
717*******
10. (10). at() :
returns the character at a specified index (position) in a string. This method allows for
positive and negative integers as parameters. Negative integers count back from the last string
character.
SYNTAX : at(index)
OUTPUT
Country Code is : 1
returns the unicode of the character at a specified index in a string. The return value is
a integer between 0 and 65535 representing the UTF-16 code unit
SYNTAX : charCodeAt(index)
OUTPUT
65
OUTPUT
['She', 'sells', 'seashells', 'on', 'the', 'seashore.']
seashells
OUTPUT
['S', 'h', 'e', ' ', 's', 'e', 'l', 'l', 's', ' ', 's', 'e', 'a', 's', 'h',
'e', 'l', 'l', 's', ' ', 'o', 'n', ' ', 't', 'h', 'e', ' ', 's', 'e', 'a',
's', 'h', 'o', 'r', 'e', '.']
h
OUTPUT
['She sells seashells on the seashore.']
13. (13). indexOf(), lastIndexOf() :
searches the entire calling string, and returns the index of the first occurrence of the specified
substring. If the searchString not found, then the method returns -1. The second
argument position is a number, the method returns the first occurrence of the specified
substring at an index greater than or equal to the specified number.
The difference between search() and indexOf() is search() does not have
second position argument whereas indexOf() cannot take regular expressions as search
values.
SYNTAX :
indexOf(searchString [, position])
lastIndexOf(searchString [, position])
OUTPUT
Index position where 'indigo' was found is 7
Index position where 'brown' was found is -1
let searchWhale = "The biggest whale in the world is Antarctic blue whale."
OUTPUT
Index position where 'whale' was found is 12
Index position where 'whale' was found is 49
let searchWhale = "The biggest whale in the world is Antarctic blue whale."
OUTPUT
Index position of last occurance of 'whale' is 49
executes a search for a match between a regular expression and String object i.e. this
method searches a string or a regular expression in a String Object and returns the position
of the match. If not match found, then the method will return -1.
The difference between search() and indexOf() is search() does not have
second position argument whereas indexOf() cannot take regular expressions as search
values.
SYNTAX :
search(searchString)
search(regex)
OUTPUT
The first match for searchString occurs at index position 11
OUTPUT
The first match for character "-" is at index position 9
performs a case-sensitive search to determine whether one string may be found within another
string, returning boolean values true or false as appropriate.
const rhyme = "Baa, baa, black sheep, have you any wool?"
const isExists = [Link]('baa') // 'baa' exits and returns true
[Link](isExists)
OUTPUT
true
const rhyme = "Baa, baa, black sheep, have you any wool?"
OUTPUT
false
16. (15). startsWith() :
determines whether a string begins with the characters of a specified string, returning boolean
values of either true or false as appropriate. If the position argument is not specified, then it
will default to 0
OUTPUT
true
OUTPUT
false
determines whether a string ends with the characters of a specified string, returning boolean
values of either true or false as appropriate. If the position argument is not specified, then it
will default to 0
OUTPUT
true
static method is a tag function of template literals. This is similar to the r prefix in Python, or
the @ prefix in C# for string literals. It's used to get the raw string form of template literals —
that is, substitutions (e.g. ${amount}) are processed, but escape sequences (e.g. \n) are not.
SYNTAX :
raw(strings, ...substitutions)
raw`templateString`
OUTPUT
C:[Link]
JavaScript file is located at C:\Users\Skillzam\Desktop\code\[Link]
Notice the first argument is an object with a raw property, whose value is an array-like object
(with a length property and integer indexes) representing the separated strings in the template
literal. The rest of the arguments are the substitutions. Since the raw value can be any array-like
object, it can even be a string!
For example, 'ABCD' is treated as ['A', 'B', 'C', 'D']. The following is equivalent to
`A${0}B${1}C${2}D`
OUTPUT
A0B1C2D
constructs and returns a new string which contains the specified number of copies of the
string on which it was called, concatenated together. The argument count indicating the number
of times to repeat the string.
SYNTAX : repeat(count)
OUTPUT
buzzzzzz
OUTPUT
[Link]
OUTPUT
Skillzam Skillzam Skillzam
SYNTAX : toString()
OUTPUT
String {'Skillzam'}
Skillzam
SYNTAX : valueOf()
OUTPUT
String {'JavaScript is everywhere.'}
JavaScript is everywhere.
22. (21). match() :
method retrieves the result of matching a string against a regular expression i.e it returns
an array containing the results of matching a string against a string or a regular
expression. If a regular expression does not include the g modifier (global
search), match() will return only the first match in the string.
SYNTAX :
match(searchString)
match(regex)
OUTPUT
['butter']
OUTPUT
['butter', 'butter', 'butter', 'butter']
OUTPUT
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
returns an iterator of all results matching a string against a "string or regular expression"
including capturing groups. If the parameter is a regular expression, the global flag g must be
set, otherwise a TypeError is thrown.
SYNTAX :
matchAll(searchString)
matchAll(regex)
OUTPUT
[object RegExp String Iterator]
[['butter'], ['butter'], ['butter'], ['butter']]
boolean
boolean is a built-in primitive data type in JavaScript.
Booleans represent one of two values: true or false.
When you compare two values, the expression is evaluated and JavaScript returns
the Boolean answer
Booleans can also be constructed using the Boolean() object constructor.
Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean
value — use Boolean as a function or a double NOT !! instead.
Booleans are often used in conditional testing.
Any numeric type is false if equal to zero or null, and true otherwise:
// Boolean values numeric type
Boolean(2017) // true
Boolean(-123) // true
Boolean(2.728281) // true
Boolean(Infinity) // true
Boolean(-Infinity) // true
Boolean(0) // false
Boolean(NaN) // false
For strings, Boolean() is false for empty strings and true otherwise:
// Boolean values for string type
Boolean("Workzam") // true
Boolean("2023") // true
Boolean('') // false
Boolean(true) // true
Boolean([12,24,36]) // true
Boolean({name: 'Brendan'}) // true
Boolean([]) // true
Boolean({}) // true
Boolean() // false
Boolean(false) // false
Boolean(null) // false
Boolean(undefined) // false
1. ➤ false
2. ➤ 0 (zero)
3. ➤ NaN
4. ➤ '' (empty string)
5. ➤ null
6. ➤ undefined
In JavaScript, a nullish value is the value which is either null or undefined. Nullish
values are always falsy.
// Falsy values
Boolean(false) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
Boolean(null) // false
Boolean(undefined) // false
Boolean Methods
1. (1). toString() :
returns a string of either true or false depending upon the value of the object.
SYNTAX : toString()
OUTPUT
Boolean {true}
true
string
2. (2). valueOf() :
SYNTAX : valueOf()
OUTPUT
Boolean {true}
true
boolean
undefined
undefined is a built-in primitive data type in JavaScript.
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
It is a property of the global object. That is, it is a variable in global scope.
Any variable can be emptied, by setting the value to undefined.
An empty value has nothing to do with undefined. An empty string has both a legal value
and a type string
Boolean value of undefinedis false.
// undefined datatype
let studentCount;
typeof(studentCount)
OUTPUT
'undefined'
let btc
Boolean(btc)
OUTPUT
false
let premium;
if (typeof(premium) === "undefined") {
[Link]("Premium value not assigned.")
}
typeof(premium)
OUTPUT
Premium value not assigned.
'undefined'
OUTPUT
Premium value not assigned.
'undefined'
null
null is a built-in primitive data type in JavaScript.
null is a special value which represents “nothing”, “empty” or “value unknown”.
null is not the same as 0, false, or an empty string. null is a data type of its own.
null value represents the intentional absence of any object value. It is treated as falsy for
boolean operations.
null is not an identifier for a property of the global object, like undefined can be.
Instead, null expresses a lack of identification, indicating that a variable points to no
object.
// null Datatype
OUTPUT
null
object
false
bigint
bigint is a built-in primitive data type in JavaScript.
bigint values represent numeric values which are too large to be represented by
the number primitive.
bigint is created by appending n to the end of an integer literal, or by calling
the BigInt() function (without the new operator) and giving it an integer value or string value.
bigint variables can also be created using the BigInt() object constructor method. BigInt()
can only be called without new. Attempting to construct it with new throws a TypeError.
Syntax : BigInt(value)
bigint value cannot be used with methods in the built-in Math object like
the number datatype.
bigint value cannot be mixed with a number value in operations.
0n is falsy, everything else is truthy.
bigint value is not strictly equal to a number value. Example : 1n !== 1 , this is true
bigint values and number values may be mixed in arrays and sorted.
bigint value follows the same conversion rules as number when:
// typeof Operator
typeof(999n) === 'bigint' // true
typeof(Object(999n)) === 'object' // true
// Operators
let bigNum = BigInt(9007199254740992) // BigInt() : 9007199254740992n
const bigNumPlus = bigNum + 7n // Addition : 9007199254740999n
const bigNumMinus = bigNum - 7n // Substract : 9007199254740992n
const bigNumProd = bigNum * 2n // Multiply : 18014398509481984n
const bigNumBy = 10n / 3n // Divide : 3n (decimal places are
truncated)
const bigNumMod = bigNum % 10n // Mod : 2n
const bigNumPow = 2n ** 53n // Power : 9007199254740992n
// Comparisons
9n === 9 // false
9n == 9 // true
9n > 99 // false
9n <= 9 // true
// Conditionals
!9n // false
!0n // true
// Array
mixedArray = [8, 2n, 0, -6n, 10, 0n] // BigInt & Number values may be mixed
Bigint Methods
1. (1). toString() :
returns a string representing this BigInt value in the specified radix (base).
SYNTAX : toString(radix)
OUTPUT
hugeNumber value is 1.2345678901234568e+39 and datatype is number
bigintNumObj value is 1234567890123456846996462118072609669120 and datatype is
bigint
largeNumber value is 1234567890123456846996462118072609669120 and datatype is
string
1. (2). valueOf() :
SYNTAX : [Link]()
[Link](largeNumValue) //
1234567890123456789012345678901234567890n
[Link](typeof(largeNumValue)) // bigint
[Link](bigNumValue) // 9007199254740992n
[Link](typeof(bigNumValue)) // bigint
OUTPUT
1234567890123456789012345678901234567890n
bigint
9007199254740992n
bigint
symbol
symbol is a built-in primitive data type in JavaScript.
symbol represents a unique "hidden" identifier that no other code can accidentally access.
All seven primitive types contain only a single value, whereas object are used to store
collections of data. The symbol type is used to create unique identifiers for objects.
symbol type doesn't have a literal form. To create a new symbol, you use the
global Symbol() method/[Link]() function creates a new unique value each time you
call it. The function accepts a description as an optional argument.
The description argument will make your symbol more descriptive. Attempting to construct it
with new throws a TypeError.
Syntax : Symbol(description)
// symbol DataType creation using Symbol() method
// with 'description' argument as 'pid'
const player = {
fname: "Leo",
lname: "Messi",
position: "Forward" }
OUTPUT
Player pid using Symbol: 98765
typeof(pid) is symbol
Player pid using Object: undefined
Shared Symbols in global registry
In the above example using the Symbol() function will create a Symbol pid whose value
(98765) remains unique throughout the lifetime of the program.
ECMAScript provides you with a global symbol registry that allows you to share symbols
globally.
Note that the "global Symbol registry" is only a fictitious concept and may not correspond
to any internal data structurein the JavaScript engine — and even if such a registry exists, its
content is not available to the JavaScript code, except through the for() and keyFor() methods.
[Link](key)
1. (1). [Link](key) method takes a string key as argument and returns a symbol
value from the registry.
2. (2). To create a symbol that will be shared, use the [Link]() method instead of calling
the Symbol() function.
3. (3). [Link](key) method accepts a single parameter that can be used for symbol's
description.
4. (4). [Link](key) method first searches for the symbol with the key in the global symbol
registry. It returns the existing symbol if there is one. Otherwise,
the [Link](key) method creates a new symbol, registers it to the global symbol registry
with the specified key, and returns the symbol.
[Link](symbol)
// [Link]() method
[Link](aadhar) // Symbol(aadhar)
[Link](citizenID) // Symbol(aadhar)
[Link](aadhar === citizenID) // true
[Link](typeof aadhar) // symbol
[Link](typeof citizenID) // symbol
// [Link]() method
let keyAadhar = [Link](aadhar)
let keyCitizenID = [Link](citizenID)
[Link](keyAadhar) // aadhar
[Link](keyCitizenID) // aadhar
Symbol Methods
1. (1). toString() :
SYNTAX : toString()
Symbol('skill').toString() // "Symbol(skill)"
[Link]() // "Symbol([Link])
[Link]('zam').toString() // "Symbol(zam)"
1. (2). valueOf() :
SYNTAX : valueOf()
Arrays
Arrays are simple data structures.
Arrays are Ordered collections of values.
Arrays are generally described as "list-like objects"; they are basically single objects that
contain multiple values stored in a list.
It is a common practice to declare arrays with the const keyword. It does NOT define a
constant array. It defines a constant reference to an array.
Arrays are mutable by default i.e. their properties and elements can be changed without
reassigning a new value.
Arrays are resizable and can contain a mix of different data types.
Arrays are zero-indexed i.e. the first element of an array is at index 0, the second is at
index 1, and so on .
the length property will determine the length of an array.
Arrays have no fixed size, meaning we don't have to specify how big a array will be.
SYNTAX:
const arrayName = [item1, item2, item2, ...];
OUTPUT
type of academy array is object
Length of academy array is 8
The element at the '0' index is S
// Create array of English Vowels (string)
// using array literals
OUTPUT
['a', 'e', 'i', 'o', 'u']
OUTPUT
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[Link](mixData)
OUTPUT
['One', 2, 'Three', [4, 'five', 6], 7.8, {key: 9}]
Creating array
Using a pair of square brackets to denote the empty array and then add items by indexing: [ ]
Using array literals i.e. square brackets, separating items with commas: [a], [a, b, c]
Using a string method split(): 'SKILLZAM'.split('') returns ['S', 'K', 'I', 'L',
'L', 'Z', 'A', 'M']
Using the array constructor function Array(item1, item2,
item2,...) or Array(arrayLength)
Array() can be called with or without new keyword. Both create a new Array instance.
The constructor builds a array whose items are the same and in the same order as iterable's items.
For example
Array('a','b','c') returns ['a', 'b', 'c']
If the only argument passed to the Array() constructor, is an integer between 0 and 232 - 1
(inclusive), this returns a new JavaScript array with its length property.
Array(3) returns [,,]
[Link](arrayOne)
OUTPUT
[6, 28, 496, 8128]
OUTPUT
[[1],[2,3],[4,5,6]]
['WORKZAM']
[,,,,,,,,]
['ಅ', 'ಆ', 'ಇ', 'ಈ']
OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'honey']
OUTPUT
['tea', 'coffee', 'milk', 'eggs', 'bread']
OUTPUT
['tea', 'coffee', 'milk', 'eggs']
undefined
5
OUTPUT
A,B,C1,2,3
type of 'result' is string
Nested array
OUTPUT
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrixOne[0]
OUTPUT
[1, 2, 3]
matrixOne[0][0]
OUTPUT
1
(1) pop()
removes (pops) the last element from an array and returns that element.
pop() is a mutating method i.e. it changes length of the array.
SYNTAX : pop()
OUTPUT
Rahul
['Sachin', 'Dhoni', 'Virat', 'Zaheer']
(2) push()
OUTPUT
4
['NewDelhi', 'NewYork', 'London', 'Istanbul']
OUTPUT
7
[12, 24, 45, 67, 78, 89, 91]
(3) shift()
removes first element from an array & returns the removed element.
pop() method has similar behavior to shift(), but applied to the last element in an array.
shift() is a mutating method i.e. it changes length of the array.
shift() method is often used in condition inside while loop.
SYNTAX : shift()
OUTPUT
Sachin
['Dhoni', 'Virat', 'Zaheer', 'Rahul']
// every iteration will remove next element from an array, until it is empty
while (typeof (player = [Link]()) !== "undefined") {
[Link](player)
}
OUTPUT
Messi
Neymar
Ronaldo
Benzema
The 'players' array contains []
(4) unshift()
unshift() adds one or more elements to the beginning of an array and returns the new
length of an array.
If multiple elements are passed as arguments, they are inserted in the exact same order they
were passed.
OUTPUT
6
['Spinach', 'Kale', 'Collard', 'Avocado', 'Kiwi', 'Moringa']
(5) includes()
OUTPUT
true
OUTPUT
true
(6) indexOf()
returns the first index at which a given element can be found in the array, or -1 if it is not
present.
indexOf() method compares element to items of the array using strict equality ===.
The optional argument fromIndex will specify from which index position should the
search start.
For NaN values in the array, the indexOf() method will return -1.
OUTPUT
0
OUTPUT
4
(7) concat()
OUTPUT
symThree = ['INR', 'USD', 'EUR', 'JPY', 'CNY']
symOne = ['INR', 'USD', 'EUR']
symTwo = ['JPY', 'CNY']
OUTPUT
array3 = [2, 4, 6, 1, 3, 5, 7, 8]
array1 = [2, 4, 6]
array2 = [1, 3, 5]
// concat() merge two or more arrays and returns a new array
// concat() with no arguments
OUTPUT
newArray = ['apples', 'oranges', 'kiwi']
(8) join()
returns a new string by concatenating all of the elements in an array (or an array-like
object), separated by commas or a specified separator string.
If the array has only one item, then that item will be returned without using the separator.
The optional argument separator specifies a string to separate each pair of adjacent
elements of the array. The separator is converted to a string if necessary. If omitted, the array
elements are separated with a comma ,.
SYNTAX : join([separator])
[Link]() // 'Tea,Milk,Sugar'
[Link](", ") // 'Tea, Milk, Sugar'
[Link](" + ") // 'Tea + Milk + Sugar'
[Link]("") // 'TeaMilkSugar'
(9) reverse()
method reverses an array in place and returns the reference to the same array.
The elements order in the array will be turned towards the direction opposite to that
previously stated.
reverse() method does not have any arguments.
reverse() is a mutating method i.e. it changes order of the array. reverse() method returns
reference to the original array, so mutating the returned array will mutate the original array
as well.
In case you want reverse() to NOT mutate the original array, but return a shallow copy
array, then before calling reverse(), using the spread(...) operator syntax or [Link]()
SYNTAX : reverse()
OUTPUT
['cyan', 'orange', 'blue', 'green', 'red']
OUTPUT
newFibo = [80, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
newFibo = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
fibonacci = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
(10) slice()
slice() method returns a shallow copy of a portion of the original array into a new array
object.
slice() method will NOT modifiy the original array.
The two optional arguments start and end will specify the starting and
ending (end index not included), index position of the array.
If start is ommited, then it will default to 0 value.
If end argument is ommitted, then [Link] is used, which means all elements until the
end of array, to be extracted.
OUTPUT
['Spinosaurus', 'Tyrannosaurus']
OUTPUT
['Brachiosaurus', 'Patagosaurus']
OUTPUT
['Brachiosaurus', 'Patagosaurus', 'Spinosaurus', 'Tyrannosaurus']
(11) splice()
OUTPUT
['Ape', 'Cat', 'Cow', 'Dog', 'Fox']
OUTPUT
['Ape', 'Cow', 'Dog', 'Elk', 'Kob', 'Yak']
OUTPUT
['Ape', 'Cow', 'Dog']
Objects
Object is a complex datatypes in JavaScript.
Objects are variables too. But objects can contain many values.
JavaScript objects are containers for named values called properties.
Objects are collections of properties. Object properties can be defined within curly
brackets { } and have a comma-separated key : value pairs (key and value separated by a
colon : ).
It is a common practice to declare objects with the const keyword.
The values in object properties can be of any data type.
Objects does not allow duplicate properties.
Objects are utable. They are addressed by reference, not by value.
const playersBio = {
name: "Leo Messi",
team: "Paris Saint-Germain",
position: "Forward",
height: 170,
weight: 159,
birthdate: "24/6/1987",
age: 35,
nationality: "Argentina",
careerHistory: ["Barcelona","PSG","Argentina"],
isRetired: false
}
OUTPUT
{Keyone: 2, Keythree: 3}
const students = {
fName: "Jasmine",
lName: "Dsouza",
gender: "Female", // value is string DataType
age: 20, // value is number(integer) DataType
isGraduate: true, // value is boolean DataType
cgpa: 8.4, // value is number(decimal) DataType
favSub: ["Physics","Computers"] // value is array
}
[Link](students)
OUTPUT
{fName: 'Jasmine', lName: 'Dsouza', gender: 'Female', age: 20, isGraduate:
true, cgpa: 8.4, favSub: ['Physics', 'Computers', 'History']}
Creating Object
Object Literal: use a comma-separated list of key : value pairs within braces.
Example: { uid: 4098, name: 'Ravi Patil' }
Using the new keyword with in-built Object constructor function. Example: const cars =
new Object()
Using new with user-defined constructor function.
Using [Link]() to create new objects.
Using [Link]() to create new objects.
Using ES6 class to create objects
// Creating Object: 'Object Literal'
OUTPUT
{apples: 123, oranges: 456}
[Link](car)
OUTPUT
{year: 2022, make: 'Mahindra', model: 'XUV700'}
OUTPUT
Cricketer {fullName: 'Virat Kohli', runsScored: 183}
183
// Object 'biography'
const biography = {
name: "Cristiano Ronaldo",
team: "Manchester United",
position: "Forward",
height: 187,
weight: 183,
birthdate: "5/2/1985",
age: 37
}
// Object 'playerHist'
const playerHist = {
nationality: "Portugal",
careerHistory: ["ManU","Juventus","Real Madrid"],
isRetired: false
}
[Link](PlayerBio)
[Link]([Link])
OUTPUT
{name: 'Cristiano Ronaldo', team: 'Manchester United', position: 'Forward',
height: 187, weight: 183, birthdate: "5/2/1985", age: 37, nationality:
"Portugal", careerHistory: ["ManU","Juventus","Real Madrid"], isRetired: false
}
Cristiano Ronaldo
[Link]([Link])
[Link]([Link])
[Link](empOne)
OUTPUT
Fred Silva
Rio de Janeiro
Employee {fullname: 'Fred Silva', city: 'Rio de Janeiro'}
Almost "everything" is an object in JavaScript. All values, except primitives, are objects.
Access the properties of an object by referring to its key, inside square brackets.
const students = {
fName: "Jasmine",
lName: "Dsouza",
gender: "Female",
age: 20,
isGraduate: true,
cgpa: 8.4,
favSub: ["Physics","Computers","History"]
}
firstname = students['fName']
favSubject = students['favSub'][0]
[Link](firstname + ' loves ' + favSubject + '!')
OUTPUT
Jasmine loves Physics!
firstname = [Link]
scoreCGPA = [Link]
[Link](firstname + ' scored ' + scoreCGPA + '!')
OUTPUT
Jasmine scored 8.4!
const vehicle = {
year: 2021,
make: 'Mahindra'
}
OUTPUT
{year: 2021, make: 'Mahindra', model: 'XUV700'}
Change/Modify the value of a specific property of an object, by referring to its key name.
const users = {
fname: 'Guido',
lname: 'van Rossum',
email: 'guido@[Link]'
}
// Change 'email' property value
users['email'] = 'guido@[Link]'
[Link](users)
OUTPUT
{fname: 'Guido', lname: 'van Rossum', email: 'guido@[Link]'}
const mobile = {
[brand]: 25000, // 'Samsung' property key is taken from variable 'brand'
year: 2022
}
[Link](mobile)
OUTPUT
{Samsung: 25000, year: 2022}
const vehicle = {
year: 2021,
make: 'Mahindra',
model: 'XUV700'
}
OUTPUT
{year: 2021, make: 'Mahindra'}
in Keyword is used to determine, if a specified key is present in an object. For any a non-
existing property, in operator just returns undefined.
const users = {
fname: 'Guido',
lname: 'van Rossum',
email: 'guido@[Link]'
}
OUTPUT
true
[Link]() returns an array containing all of the [key, value] pairs of a given
object's own enumerable string properties.
[Link]() returns an array containing the key names of all of the given object's own
enumerable string properties.
[Link]() returns an array containing the values that correspond to all of a given
object's own enumerable string properties.
// Object - static methods
// [Link](), [Link](), [Link]()
const employee = {
empName: "Javid Khan",
designation: "Software Developer",
city: "Paris",
zip: 70123
}
OUTPUT
[['empName', 'Javid Khan'], ['designation', 'Software Developer'], ['city',
'Paris'], ['zip', 70123] ]
['empName', 'designation', 'city', 'zip']
['Javid Khan', 'Software Developer', 'Paris', 70123]
Nested Objects
JavaScript data structures support nesting. This means we can have data structures within data
structures. For object, property values in an object can be another object. You can access nested
objects using the dot (.) notation or the bracket [] notation
For example: An object containing another object.
const team = {
player1: {
name: 'Leo Messi',
position: 'Forward'
},
player2: {
name: 'Andres Iniesta',
position: 'Midfield'
},
player3: {
name: 'Xavi Hernandez',
position: 'Midfield'
}
}
team['player1']['name']
OUTPUT
'Leo Messi'
const player1 = {
name: 'Leo Messi',
position: 'Forward'
}
const player2 = {
name: 'Andres Iniesta',
position: 'Midfield'
}
const player3 = {
name: 'Xavi Hernandez',
position: 'Midfield'
}
const team = {
player1 : player1,
player2 : player2,
player3 : player3
}
team['player1']
OUTPUT
{name: 'Leo Messi', position: 'Forward'}
Object Methods
1. (1). hasOwnProperty() :
method returns a boolean indicating whether the object has the specified property as its own
property, as opposed to inheriting it.
The argument property is the String name or Symbol of the property to test.
SYNTAX : hasOwnProperty(property)
const player = {
name: 'Leo Messi',
position: 'Forward'
}
OUTPUT
true
2. (2). toString() :
SYNTAX : toString()
// toString() returns string representing the object
[Link]([Link]())
OUTPUT
Leo Messi plays as Forward
3. (3). valueOf() :
method of Object converts the this value to an object. This method is meant to be overridden
by derived objects for custom type conversion logic.
SYNTAX : valueOf()
// valueOf() methods
// Example : Area of a circle
function SquareRad(num) {
[Link] = num * num
}
[Link] = function() {
return [Link];
}
OUTPUT
Area of circle = 78.55
1. [1]. if statement
2. [2]. else if statement
3. [3]. else statement
4. [4]. switch statement
Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided.
JavaScript adopts the if, else if and else statements. In these conditional clauses, else
if and else blocks are optional; additionally, you can optinally include as few or as many else
if statements as you would like.
Simple if statement
OUTPUT
num1(24) is greater than num2(12)
if...else statement
The if statement alone tells us that, if a condition is true, it will execute a block of
statements and if the condition is false it won't.
But what if we want to do something else, if the condition is false. Here comes
the else statement.
We can use the else statement with if statement to execute a block of code when the
condition is false.
// 'if...else' statement
OUTPUT
num1(36) is lesser than num2(48)
Nested if statement
let ranNum = 28
OUTPUT
ranNum is smaller than 30
OUTPUT
givenNum is 100
switch statement
const billRate = 40
switch (billRate) {
case 25:
[Link]("Salary paid per month = 80000");
break;
case 40:
case 45:
[Link]("Salary paid per month = 125000");
break;
case 60:
[Link]("Salary paid per month = 190000");
break;
case 90:
[Link]("Salary paid per month = 300000");
break;
default:
[Link]("He/She is unbillable resource.");
}
OUTPUT
Salary paid per month = 125000
Shorthand if statement
If you have only one statement to execute, you can put it on the same line as
the if statement, without curly brackets.
// Shorthand "if" statement
OUTPUT
weightOne is heavier
***End of Code***
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line, without curly brackets.
This technique is known as Ternary Operators, or Conditional Operators.
// Shorthand "if...else" statement
// “Question mark” or "Ternary" operator
OUTPUT
num2 is largest
Loops in JavaScript
Loops are basically a simple set of instructions that gets repeated until a condition is met.
The various loop mechanisms offer different ways to determine the start and end points of
the loop.
In JavaScript, we have different kind of looping statements:
1. (1). while loops through a block of code while a specified condition is true
2. (2). do while also loops through a block of code while a specified condition is true
3. (3). for loops through a block of code a number of times
4. (4). for...of loops through the values of an iterable object
5. (5). for...in loops through the properties of an object
[1]. while Loop
while loop is used to execute a block of statements repeatedly until a given condition is
satisfied (true).
When the condition becomes false, the line immediately after the loop in the program is
executed.
while loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn't specified explicitly in advance.
When a while loop is executed, expression is first evaluated in a Boolean context and if it
is true, the loop body is executed. Then the expression is checked again, if it is still true then
the body is executed again and this continues until the expression becomes false.
If you forget to increase the variable used in the condition, the loop will never end.
A nested while loop is a while loop inside a while loop.
// while loop to print numbers : 1 to 5
let i = 1
while (i < 6) {
[Link](i)
i += 1 // remember to increment i, or else loop will continue forever
}
OUTPUT
0
1
2
3
4
5
let j = 0,
i = 1,
str = '';
while (i <= 5) {
j = 1
while (j <= i) {
str += (j + ' ')
j += 1
}
str += "\n";
i += 1
}
[Link](str)
OUTPUT
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
do while also loops through a block of code while a specified condition is true.
Unlike the while loop, the do while loop always executes the statement at least
once before evaluating the expression.
In the below Syntax of do while loop :
SYNTAX:
do {
// Block of code to be executed
}
while (condition);
let counter = 1
do {
[Link](counter)
counter++
} while (counter <= 3)
OUTPUT
1
2
3
for loop repeats until a specified condition evaluates to false. The JavaScript for loop is
similar to the Java and C for loop.
A nested for loop is a for loop inside a for loop.
In the below Syntax of for loop :
o expression1 = initial Expression Eg: let i = 0;
o expression2 = Condition Eg: i <= 10;
o expression3 = increment Expression Eg: i++
SYNTAX:
1. (1). Initializing expression expression1, if any, is executed. This expression usually initializes
one or more loop counters, but the syntax allows an expression of any degree of complexity.
This expression can also declare variables.
2. (2). Condition expression expression2 is evaluated. If the value of condition is true, the loop
statements execute. Otherwise, the for loop terminates. (If the condition expression
is omitted entirely, the condition is assumed to be true.)
3. (3). Block of code within curly braces {} executes multiple statements.
4. (4). Increment expression expression3, if any, is executed.
5. (5). Control returns to Step (2) i.e. condition expression expression2 is evaluated.
// for loop
// Example : Adding all single digit numbers as elements of an array
/****************************************************/
// Tracing 'for' loop in the above example
//
// 1st: singleDigit=0; true; o/p: 0 added to the array
// 2nd: singleDigit=1; true; o/p: 1 added to the array
// 3rd: singleDigit=2; true; o/p: 2 added to the array
// ....
// .... continue adding to the array
// ....
// 9th: singleDigit=8; true; o/p: 8 added to the array
// 10th:singleDigit=9; true: o/p: 9 added to the array
// 11th:singleDigit=10; false; exit the for loop
//
// The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
/*****************************************************/
OUTPUT
The "numArray" contains = [0,1,2,3,4,5,6,7,8,9]
// for loop
// Example : Find sum of all number in an array
/*****************************************************/
// Tracing 'for' loop in the above example
//
// 1st: x = 0; true; sumNum = 0 + 22 = 22
// 2nd: x = 1; true; sumNum = 22 + 44 = 66
// 3rd: x = 2; true; sumNum = 66 + 66 = 132
// 4th: x = 3; false; Exit the 'for' loop
//
// Sum of all the number in an array = 132
/*****************************************************/
OUTPUT
Sum of all the number in an array = 132
/*****************************************************/
// Tracing Nested 'for' loop in the above example
//
// Outer for loop - 1st of p: p = 1; true; o/p: p is:1
// 1st of q: q = 1; true; o/p: q is:1
// 2nd of q: q = 2; true; o/p: q is:2
// 3rd of q: q = 3; true; o/p: q is:3
// 4th of q: q = 4; false; Exit the inner q loop
// Outer for loop - 2nd of p: p = 2; true; o/p: p is:2
// 1st of q: q = 1; true; o/p: q is:1
// 2nd of q: q = 2; true; o/p: q is:2
// 3rd of q: q = 3; true; o/p: q is:3
// 4th of q: q = 4; false; Exit the inner q loop
// Outer for loop - 3rd of p: p = 3; false; Exit the outer p loop
//
/*****************************************************/
OUTPUT
p is: 1
q is: 1
q is: 2
q is: 3
p is: 2
q is: 1
q is: 2
q is: 3
const arrFlags = [
["INDIA","Orange","White","Green"],
["GERMANY","Black","Red","Yellow"],
["RUSSIA","White","Red","Blue"],
["COLOMBIA","Yellow","Blue","Red"],
["EGYPT","Red","White","Black"]
]
/*****************************************************/
// Tracing nested 'for' loop in the above example
//
// Outer for loop - 1st of a: a = 0; true; flagRow =
["INDIA","Orange","White","Green"] ; O/P: INDIA Flag Colors
// 1st of b: b = 1; true : O/P: Orange
// 2nd of b: b = 2; true : O/P: White
// 3rd of b: b = 3; true : O/P: Green
// 4th of b: b = 4; false Exit the inner b loop
// Outer for loop - 2nd of a: a = 1; true; flagRow =
["GERMANY","Black","Red","Yellow"] ; O/P: GERMANY Flag Colors
// 1st of b: b = 1; true : O/P: Black
// 2nd of b: b = 2; true : O/P: Red
// 3rd of b: b = 3; true : O/P: Yellow
// 4th of b: b = 4; false Exit the inner b loop
// ... continue
//
/*****************************************************/
OUTPUT
INDIA Flag Colors
Orange
White
Green
GERMANY Flag Colors
Black
Red
Yellow
RUSSIA Flag Colors
White
Red
Blue
COLOMBIA Flag Colors
Yellow
Blue
Red
EGYPT Flag Colors
Red
White
Black
for...of statement loops through the values of an iterable objects such as arrays, strings,
maps, NodeLists etc.
In the below Syntax of for...of loop :
o variable : For every iteration the value of the next property is assigned to the variable.
Variable can be declared with const, let, or var.
o iterable : An object that has iterable properties.
o Block of code within curly braces {} executes multiple statements.
SYNTAX:
let total = 0;
let arrayNum = [10, 20, 30, 40]
/*****************************************************/
// Tracing 'for...of' loop in the above example
//
// 1st : n = 10; total = 0 + 10 = 10
// 2nd : n = 20; total = 10 + 20 = 30
// 3rd : n = 30; total = 30 + 30 = 60
// 4th : n = 40; total = 60 + 40 = 100
// No more values in the array, hence exit the for loop
//
// Sum of all the number in an array = 100
/*****************************************************/
OUTPUT
Sum of all the number in an array = 100
const charArray = []
let charIndex = 0
/******************************************************/
// Tracing 'for...of' loop in the above example
//
// 1st: singleChar = S; o/p: S is added to the array
// 2nd: singleChar = K; o/p: K is added to the array
// 3rd: singleChar = I; o/p: I is added to the array
// 4th: singleChar = L; o/p: L is added to the array
// 5th: singleChar = L; o/p: L is added to the array
// 6th: singleChar = Z; o/p: Z is added to the array
// 7th: singleChar = A; o/p: A is added to the array
// 8th: singleChar = M; o/p: M is added to the array
// No more charaters in the string "SKILLZAM",
// hence exit the for loop
//
// The "charArray" contains = [S,K,I,L,L,Z,A,M]
/*****************************************************/
OUTPUT
The "charArray" contains = [S,K,I,L,L,Z,A,M]
// "for .. of" loop iterating Object
// Example : Iterate values in Object - turn data into an array
let gTotal = 0
const goalScores = {
Messi: 44,
Ronaldo: 43,
Diogo: 43,
Robert: 39,
Turpel: 37,
Suarez: 36,
Salah: 35,
Griezmann: 35,
Cifuente: 34,
Kane: 33
}
// goals = [44,43,43,39,37,36,35,35,34,33]
for (let goal of goals) {
gTotal += goal;
}
OUTPUT
The array of object values is = [44,43,43,39,37,36,35,35,34,33]
Total goals scored by top 10 players in the year 2018: 379
SYNTAX:
for (key in object) {
// Block of code to be executed
}
const car = {
year: 2022,
make: 'Mahindra',
model: 'XUV700'
}
[Link](str)
OUTPUT
2022 Mahindra XUV700
const bioMessi = {
name: "Leo Messi",
team: "PSG",
position: "Forward",
height: 170,
weight: 159,
birthdate: "24/6/1987",
age: 35,
country: "Argentina",
careerHist: ["PSG","FCB","Argentina"],
isRetired: false
}
/
******************************************************************************
********************/
// Tracing for loop
//
// 1st: bio = name; bioMessi[bio] = Leo Messi; o/p: NAME is Leo Messi
// 2nd: bio = team; bioMessi[bio] = PSG; o/p: TEAM is PSG
// 3rd: bio = position; bioMessi[bio] = Forward; o/p: POSITION is Forward
// 4th: bio = height; bioMessi[bio] = 170; o/p: HEIGHT is 170
// 5th: bio = weight; bioMessi[bio] = 159; o/p: WEIGHT is 159
// 6th: bio = birthdate; bioMessi[bio] = 24/6/1987; o/p: BIRTHDATE is
24/6/1987
// 7th: bio = age; bioMessi[bio] = 35; o/p: AGE is 35
// 8th: bio = country; bioMessi[bio] = Argentina; o/p: COUNTRY is
Argentina
// 9th: bio = careerHist; bioMessi[bio] = PSG,FCB,Argentina; o/p: CAREERHIST
is PSG,FCB,Argentina
// 10th: bio = isRetired; bioMessi[bio] = false; o/p: ISRETIRED is false
// No more name:value pair exists in the object literal, hence exit the for
loop
//
/
******************************************************************************
********************/
OUTPUT
NAME is Leo Messi
TEAM is PSG
POSITION is Forward
HEIGHT is 170
WEIGHT is 159
BIRTHDATE is 24/6/1987
AGE is 35
COUNTRY is Argentina
CAREERHIST is PSG,Barcelona,Argentina
ISRETIRED is false
Examples:
break statement
continue statement
break statement
Example of using break statement for a less trivial task. This loop will fill a list with all
Fibonacci numbers up to a certain value:
let a = 0,
b = 1,
n,
maxNum = 100,
index = 0;
const listFibo = [];
while (true) {
listFibo[index] = a;
index++;
n = a + b;
a = b;
b = n;
if (a > maxNum) {
break; // usuage of break statement to exit the loop
}
}
[Link](listFibo)
OUTPUT
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
continue statement
continue statement: The continue statement skips the remainder of the current loop,
and goes to the next iteration.
continue statement breaks one iteration (in the loop).
With the continue statement we can stop the current iteration of the for or while loop, and
continue with the next.
Example of using continue to print a string of odd numbers. In this case, the result could be
accomplished just as well with an if...else statement, but sometimes the continue statement
can be a more convenient way to express the idea you have in mind:
OUTPUT
1 3 5 7 9
label statement
label provides a statement with an identifier that lets you refer to it elsewhere in your
program.
To label JavaScript statements you precede the statements with a label name and a
colon :
With a label reference, the break statement can be used to jump out of any code block.
label names can not be a reserved words.
SYNTAX:
label:
statements
let total = 0,
i = 1;
OUTPUT
total = 1
total = 3
Functions in JavaScript
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
One way to organize our JavaScript code and to make it more readable and reusable is to
factor-out useful pieces into reusable function.
The function will allow you to call the same block of code without having to write it
multiple times. This in turn will allow you to create more complex scripts.
To use a function, you must define it somewhere in the scope from which you wish to call
it.
Function definition
For example, the following code defines a simple function named createFullName :
function createFullName() {
let fname = "Brendan",
lname = "Eich",
fullname = fname + " " + lname;
[Link](fullname)
}
Function invoking
Defining a function does not execute it. Defining it names the function and specifies what to
do when the function is called.
[Link](fullname)
}
OUTPUT
Brendan Eich
The return keyword allows you to actually save the result of the output of a function as a
variable.
The [Link]() function simply displays the output to web console, but doesn't save it for
future use. [Link]() doesn't return any value, as it returns undefined
// function Parameters & Arguments
OUTPUT
Brendan Eich
Default parameters
The most useful form is to specify a default value for one or more parameter.
Defaulting parameter values will creates a function that can be called with fewer arguments
than it is defined to allow.
If we call the function without argument, it uses the default value.
// Default function Parameter values
playerClub("Barcelona")
playerClub() // default parameter is set
playerClub("Al-Nassr")
OUTPUT
I play for Barcelona.
I play for no one.
I play for Al-Nassr.
1. [a]. giving only the mandatory argument: ask_ok('Enter the capital city: ')
2. [b]. giving one of the optional arguments: ask_ok('Enter the capital city: ', 2)
3. [c]. or even giving all arguments: ask_ok('Enter the capital city: ', 2, 'Just asked
to enter city name!')
OUTPUT
Enter the capital city: Hyderabad
true
Recursion Function
0! = 1
1! = 1 x 0! = 1 x 1 = 1
2! = 2 x 1! = 2 x 1 = 2
3! = 3 x 2! = 3 x 2 = 6
4! = 4 x 3! = 4 x 6 = 24
5! = 5 x 4! = 5 x 24 = 120
// Function recursion example
function factorial(num) {
let result = 0;
if (num === 1) {
return 1;
} else {
result = num * factorial(num-1);
return result;
}
}
let randNum = 5,
funcRtn = factorial(randNum);
OUTPUT
The factorial of 5 is 120
Nested Function
function indiaWorldCup() {
const runScored = [317,350,322,301];
function announceScores() {
let matchNum = 1;
function scoreBoard() {
for (let run of runScored) {
[Link](`${matchNum} : Team India scored ${run} runs.`);
matchNum++;
}
}
scoreBoard();
}
announceScores();
}
indiaWorldCup();
OUTPUT
1 : Team India scored 317 runs.
2 : Team India scored 350 runs.
3 : Team India scored 322 runs.
4 : Team India scored 301 runs.
JavaScript Examples
JavaScript Notes contains many examples for your understanding. With our online editor, you
can edit and test each example yourself.
JavaScript is a programming language that is used primarily to add interactivity and dynamic
behavior to websites. JavaScript code can be embedded directly into HTML web pages or
included in external script files, and it can be used to manipulate HTML and CSS, handle user
input, and interact with web servers through APIs. JavaScript is a crucial component of modern
web development, and it is used extensively in frameworks and libraries such as React, Angular,
and Vue.
null and undefined are both used to represent absence of a value, but they have slightly different
meanings. Undefined is a value that is assigned to a variable that has not been initialized, or to a
function parameter that has not been passed a value. Null, on the other hand, is a value that is
explicitly assigned to a variable or object property to represent the absence of a value. In
practice, null is often used as a default value when an object property is expected to be set later,
while undefined is typically used to represent a programming error or oversight.
Hoisting in JavaScript is a feature that allows variables and functions to be declared after they
are used in a program. This is possible because JavaScript uses two passes to interpret code: the
first pass scans the code for variable and function declarations and "hoists" them to the top of
their respective scopes, and the second pass executes the code. This means that a variable or
function can be used before it is declared, as long as it is declared somewhere in the same scope.
However, hoisted variables and functions are not initialized until their declaration statements are
reached, so they may have the value "undefined" until they are explicitly assigned a value.
What are the differences between JavaScript and other programming languages
like Java and Python?
There are several differences between JavaScript and other programming languages like Java and
Python:
JavaScript is a scripting language, while Java and Python are compiled languages.
JavaScript is mainly used for web development, while Java and Python are used for a variety
of applications, including web development, mobile app development, and data analysis.
JavaScript has a loose type system, while Java and Python have strict type systems.
JavaScript uses prototype-based inheritance, while Java and Python use class-based
inheritance.
JavaScript is single-threaded, while Java and Python can support multithreading.
There are many types of events in JavaScript, including mouse events (such as click, mouseover,
and mouseout), keyboard events (such as keypress and keydown), form events (such as submit
and change), and document and window events (such as load and resize).
What is the difference between a primitive data type and an object data type in
JavaScript?
A primitive data type is a value that is not an object and has no methods. Examples of primitive
data types in JavaScript include numbers, strings, booleans, null, and undefined. An object data
type, on the other hand, is a complex data type that can contain properties and methods.
Examples of object data types in JavaScript include arrays, functions, and objects.
A callback function is a function that is passed as an argument to another function and is then
executed when the parent function completes. Callback functions are commonly used in
JavaScript for asynchronous programming tasks, such as handling events or making API calls.
The event loop in JavaScript is a mechanism that allows for asynchronous execution of code in a
single-threaded environment. When an asynchronous operation is initiated, such as a network
request or a timer, the operation is placed in a queue and the program continues to execute.
When the operation is completed, a callback function is added to another queue. The event loop
constantly checks the callback queue and executes any functions that are waiting, in the order
they were added. This allows JavaScript to handle multiple asynchronous operations
simultaneously, without blocking the main thread.
let and const are block-scoped declarations, while var is function-scoped. Variables declared
with let and const cannot be redeclared in the same block, while var allows for redeclaration.
Additionally, variables declared with const cannot be reassigned a new value, while let and var
can be. Let and const are relatively new features of JavaScript that were introduced in ES6, while
var has been part of the language since its inception.
The double equals (==) operator in JavaScript compares two values for equality, allowing for
type coercion if necessary. For example, the expression "5" == 5 would evaluate to true, because
the string "5" is coerced into the number 5 for comparison. The triple equals (===) operator, on
the other hand, compares two values for equality without type coercion, so the expression "5"
=== 5 would evaluate to false, because the types are different.
JavaScript has several primitive data types, including number, string, boolean, null, undefined,
bigint and symbol. Additionally, JavaScript has a complex data type called object, which can
store collections of key-value pairs and functions. Arrays are a special type of object that can
store collections of values, and functions are a type of object that can be called like a regular
function.
A promise in JavaScript is an object that represents a value that may not be available yet, but will
be resolved at some point in the future. Promises are used to handle asynchronous operations,
such as network requests or database queries, and allow the program to continue executing while
the operation is in progress. Promises have three states: pending, fulfilled, and rejected. When a
promise is fulfilled, it means that the value is available and the promise's then() method is called
with the value as an argument. When a promise is rejected, it means that an error occurred and
the promise's catch() method is called with the error as an argument.
Both call() and apply() are methods in JavaScript that allow a function to be called with a
specific value for the "this" keyword, and with arguments passed in as an array-like object. The
main difference between call() and apply() is in how the arguments are passed in. With call(), the
arguments are passed in as a comma-separated list, while with apply(), the arguments are passed
in as an array. This means that apply() is useful when the number of arguments is not known
ahead of time, or when the arguments are already in an array-like object.
You can declare a variable in JavaScript using the var, let, or const keyword, like this:
A closure in JavaScript is a function that has access to variables and functions defined in its outer
scope, even after the outer function has returned. A callback function, on the other hand, is a
function that is passed as an argument to another function and is called at a later time, usually
after some asynchronous operation has completed. While both closures and callbacks are used to
handle asynchronous operations in JavaScript, closures are used to maintain access to variables
and functions in the outer scope, while callbacks are used to execute a function after an operation
has completed.
The main difference between let and var in JavaScript is in their scoping. Variables declared with
let are block-scoped, meaning they are only accessible within the block in which they are
declared. Variables declared with var, on the other hand, are function-scoped, meaning they are
accessible throughout the entire function in which they are declared. Additionally, variables
declared with let cannot be redeclared in the same block, while var allows for redeclaration.
In JavaScript, every object has a prototype property, which is a reference to another object. This
prototype object contains methods and properties that are inherited by the object.
When a property or method is accessed on an object, JavaScript first looks for that property or
method on the object itself. If the property or method is not found on the object, JavaScript then
looks for it on the object's prototype. If the property or method is still not found, JavaScript
continues the search up the prototype chain until it reaches the top level, which is typically the
[Link] object.
In other words, the prototype is a way to implement inheritance in JavaScript, allowing objects to
inherit properties and methods from other objects. This can help simplify code and make it more
efficient, by allowing objects to share common functionality without having to recreate it for
each object. To create a new object with a specific prototype, you can use the [Link]()
method, passing in the desired prototype object as an argument.
What is event bubbling in JavaScript?
Event bubbling is a mechanism in JavaScript where events propagate from the innermost to the
outermost elements in the HTML DOM. When an event is triggered on an element, it is first
handled by that element's event listener. If the event listener does not stop the event from
propagating, the event then bubbles up to the element's parent, and so on until it reaches the top-
level element.
Event bubbling can be useful for handling events on multiple elements with a common ancestor.
However, it can also cause unintended consequences if not handled properly. To stop event
bubbling, you can call the [Link]() method within the event listener.
The main difference between let and const in JavaScript is in their mutability. Variables declared
with let can be reassigned a new value, while variables declared with const cannot be reassigned.
Additionally, variables declared with const must be initialized with a value at the time of
declaration, while variables declared with let can be initialized later. Both let and const are
block-scoped, meaning they are only accessible within the block in which they are declared.
What is the difference between a for loop and a forEach loop in JavaScript?
A for loop in JavaScript is a traditional loop structure that iterates over a set of values using a
counter variable. A forEach loop, on the other hand, is a method on the Array object that allows
you to iterate over each element in an array and perform an action on each element. The main
difference between the two is that a for loop is more flexible and can be used for iterating over
any set of values, while a forEach loop is specifically designed for iterating over arrays.
Additionally, a forEach loop cannot be interrupted or stopped in the middle, while a for loop can
be exited using a break statement.
The main difference between a regular function and an arrow function in JavaScript is in their
syntax and the way they handle the this keyword. Arrow functions have a shorter syntax than
regular functions, and they do not bind their own this keyword. Instead, the this keyword in an
arrow function refers to the value of this in the context in which the arrow function was defined.
This can be useful for avoiding the common "this" pitfalls that can arise with regular functions.
The innerHTML property in JavaScript allows for the manipulation of the HTML content inside
an element, including tags and attributes. The textContent property, on the other hand, only
returns the text content of an element, without any HTML tags or attributes. It is generally
recommended to use textContent when dealing with text-only content, and innerHTML when
dealing with HTML content that may contain tags and attributes.
The "use strict" directive in JavaScript enables strict mode, which is a set of rules that must be
followed in order to write secure and efficient JavaScript code. In strict mode, certain JavaScript
features that are considered error-prone or dangerous are disabled, and stricter rules are enforced
for variable declaration, function invocation, and other aspects of the language. Using strict
mode can help to prevent common coding mistakes and improve the overall quality of JavaScript
code.
What is the difference between the spread operator (...) and the rest operator (...)
in JavaScript?
The spread operator (...) in JavaScript is used to expand an iterable (such as an array or a string)
into individual elements. It is often used to pass the contents of an array or an object as
arguments to a function or to concatenate arrays. The rest operator (...), on the other hand, is used
to capture a variable number of arguments passed to a function into an array. It is often used in
function declarations to allow for a variable number of arguments to be passed to the function.
The "this" keyword refers to the current execution context, which is typically the object that the
function is a method of. It is often used to access or manipulate properties of the current object
within a method, or to bind a function to a specific object. The behavior of the "this" keyword
can be affected by the way in which a function is called, such as with the "call" or "apply"
methods, or by using arrow functions, which bind the "this" keyword to the lexical scope of the
function.
The "use strict" directive in JavaScript is a feature introduced in ECMAScript 5 that enables
strict mode, which is a stricter version of JavaScript that eliminates some silent errors and
enforces stricter coding standards. In strict mode, certain actions that were previously ignored or
silently failed will now throw errors, making it easier to write more reliable and secure code. The
"use strict" directive is typically placed at the beginning of a JavaScript file or function to enable
strict mode for that scope.
A generator function in JavaScript is a special type of function that can be paused and resumed,
allowing for the generation of a sequence of values on demand. Generator functions are declared
using the "function*" syntax and use the "yield" keyword to produce a value and pause
execution. They can also receive input values when resumed using the "next" method.
You can define a function in JavaScript using the function keyword, like this:
An event in JavaScript is an action that occurs on a web page, such as a mouse click or a key
press.
What is the DOM in JavaScript?
You can access an element in the DOM using JavaScript using methods such as
[Link](), [Link](), or [Link]().
AJAX (Asynchronous JavaScript and XML) in JavaScript is a technique used to update parts of
a web page without reloading the entire page.
A constructor function in JavaScript is a function that is used to create and initialize an object.