Javascript code preferred line length by most programmers is upto 80 characters.
The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.
document.getElementById("Codolearn").innerHTML = "Hello Codolearners";
KeyWords
Keywords are reserved words and cannot be used as variable name.
A Javascript keyword tells about what kind of operation it will perform.
Some commonly used keywords are:
- break: This is used to terminate a loop or switch.
- continue: This is used to skip a particular iteration in a loop and
move to
next iteration.
- do…. while: In this the statements written within do block are
executed
till the condition in while is true.
- for: It helps in executing a block of statements till the condition
is
true.
- function: This keyword is used to declare a function.
- return: This keyword is used to exit a function.
- var: This keyword is used to declare a variable.
- switch: This helps in executing a block of codes depending on
different
cases.
Syntax of Js
JavaScript is the lightweight and dynamic computer programming language. It is used to create client
side dynamic pages. It is open source and cross-platform language.
Basic Syntax
var = "Codolearn";
var="Codolearn";
JavaScript Variables: A JavaScript variable is the simple name of storage location where data to be
stored. There are two types of variables in JavaScript which are listed below:
- Local variables: Declare a variable inside of block or function.
- Global variables: Declare a variable outside function or with window object.
JavaScript Operator: JavaScript operators are symbols that are used to compute the value or in other
word we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute
the value and Assignment operator ( =, +=, %= ) are used to assign the values to variables.
var x, y, sum;
x = 80;
y = 32;
sum = x + y;
document.write(sum);
122
JavaScript Variables: A JavaScript variable is the simple name of storage location where data to be
stored. There are two types of variables in JavaScript which are listed below:
- Local variables: Declare a variable inside of block or function.
- Global variables: Declare a variable outside function or with window object.
JavaScript Operator: JavaScript operators are symbols that are used to compute the value or in other
word we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute
the value and Assignment operator ( =, +=, %= ) are used to assign the values to variables.
JavaScript Expression: Expression is the combination of values, operators and variables. It is used
to compute the values.
JavaScript Keyword: The keywords are the reserved words that have special meaning in JavaScript.
JavaScript Comments: The comments are ignored by JavaScript compiler. It increase the readability of
code. It adds suggestions, Information and warning of code. Anything written after double slashes //
(single line comment) or between /* and */ (multi line comment) is treated as comment and ignored by
JavaScript compiler.
// this is a js comment
JavaScript Data Types: JavaScript provides different datatype to hold different values on variable.
JavaScript is a dynamic programming language, it means do not need to specify the type of variable.
There are two types of data types in JavaScript.
- Primitive data type
- Non-primitive (reference) data type
JavaScript Functions: JavaScript functions are the blocks of code used to perform some particular
operations. JavaScript function is executed when something call it. It calls many times so the
function is reusable.
function functionName( par1, par2, ....., parn ) {
// code
}
Js Output:
JavaScript Output defines the ways to display the output of a given code. The output can be display
by using four different ways which are listed below:
- innerHTML: It is used to access an element. It defines the HTML content.
Syntax:
document.writeElementById(id)
document.write(): It is used for testing purpose
document.write(text);
window.alert():It displays the content using an alert box
window.write(text);
console.log(): It is used for debugging purposes.
console.log('text');
You should write comments to explain what your code does. they hepl make your code easier to read and
understand . this can hepl you and other who read y
our code
there are two types of comment in js :
- single-line comment
- multi-line comment
single-line comment :
in an single-line comment Anything that follows the two forward slash characters // on that line will
not be proccesed by the javascript interpreter . single-line
comment are often used for short description of what the code is doing .
multi-line comments
to write a comment that strecthes over more than one line you use a multi-line comment . starting
with the */ character Anything b/w these character is not
proccesed by the javascript interpreter .
DataTypes In JS
JavaScript distingush b/w number , string and true or false vakues know as boolean.
Numeric DataTypes
the numeric datatype handles
0.75
for task that involve counting or calculating sums you will use numbers 0-9 . for example five
thousand two hundread and seventy two be written 5272 .
you can also have nagative numbers .
String DataType
The string DataType consist of letters and other characters .
'Hi string'
Note how the string datatype is enclosed within the pair of quotes . these can be single or double
quotes but the opening quotes must match the closing
quotes Strings can be used when working with any kind of text
Boolean datatype
The Boolean datatype can have one or two value : true or false.
True
The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are
Primitive(predefined).
- Numbers: 5, 6.5, 7 etc.
- String: “Hello codolearn” etc.
- Boolean: Represent a logical entity and can have two values: true or false.
- Null: This type has only one value : null.
- Undefined: A variable that has not been assigned a value is undefined.
- Object: It is the most important data-type and forms the building blocks for
modern JavaScript. We will learn about these data types in details in further articles.
Variables Of Js
Variables in JavaScript are containers which hold reusable data. It is the basic unit of storage in a
program.
-
The value stored in a variable can be changed during program execution.
- A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
- In JavaScript, all the variables must be declared before they can be used.
Syntax:
var var_name;
var x;
The var_name is the name of the variable which should be defined by the user and should be unique.
These type of names are also known as identifiers. The rules for creating an identifier in
JavaScript
are, the name of the identifier should not be any pre-defined word(known as keywords), the first
character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be
any
letter or digit or an underscore or dollar sign.
Notice in the above code sample, we didn’t assign any values to the variables.We are only saying
they
exist.If you were to look at the value of each variable in the above code sample,it would be
undefined.
We can initialize the variables either at the time of declaration or also later when we want to use
them. Below are some examples of declaring and initializing variables in JavaScript:
// declaring single variable
var name;
// declaring multiple variables
var name, title, num;
// initializng variables
var name = "Harsh";
name = "Rakesh";
Javascript is also known as untyped language. This means, that once a variable is created in
javascript using the keyword var, we can store any type of value in this variable supported by
javascript
Const is another variable type assigned to data whose value cannot and will not change throught the
script.
Variable Scope in Javascript
Scope of a variable is the part of the program from where the variable may directly be accessible.
In JavaScript, there are two types of scopes:
- Global Scope – Scope outside the outermost function attached to Window.
- Local Scope – Inside the function being executed.
Global and Local variables in JavaScript
Variables: It holds the data or information which can be changed anytime. JavaScript use reserved
keyword var to declare variables. In JavaScript, there are two types of variable and also it tells
you
where in your program you are allowed to use the variables and functions that you’ve defined.
- Local Variable: When you use JavaScript, local variables are variables that are defined
within functions.
They have local scope, which means that they can only be used within the functions that define
them.
- Global Variable:
In contrast, global variables are variables that are defined outside of functions. These
variables
have global scope, so they can be used by any function without passing them to the function as
parameters.
Local Variable: Since local variables are defined inside the function so variables with the same name
can be used in different functions.
Global Variable: Since global variables are defined outside there function so variables with the same
name can not be used in different functions. All the scripts and functions on a web page can access
it.
<html>
<body>
<center>
<h1 style="color:green;">
Codolearn</h1>
<p>
A GLOBAL variable can be accessed from any script or function.</p>
<p id="codolearn">
</p>
<p id="codolearn">
</p>
<script>
var petName = "Rocky";//global variable myFunction(); function myFunction() { document.getElementById("codolearn").innerHTML = typeof petName + "- " + "My pet name is " + petName; } document.getElementById("codolearn").innerHTML = typeof petName + "- " + "My pet name is " + petName; </script>
</center>
</body>
</html>
Where to use which variables:
- Although it may seem easier to use global variables than to pass data to a function and return
data from it, global variables often create problems. That’s because any function can modify a
global variable, and it’s all too easy to misspell a variable name or modify the wrong variable,
especially in large applications. That, in turn, can create debugging problems.
- In contrast, the use of local variables reduces the likelihood of naming conflicts. For
instance,
two different functions can use the same names for local variables without causing conflicts.
That
of course, means fewer errors and debugging problems. With just a few exceptions, then, all of
the
code in your applications should be in functions so all of the variables are local.
- If you misspell the name of a variable that you’ve already declared, it will be treated as a new
global variable. With this in mind, be sure to include the keyword when you declare new
variables
and always declare a variable before you refer to it in your code.
How to use variables:
- The scope of a variable or function determines what code has access to it.
- Variables that are created inside a function are local variables, and local variables, and local
variables can only be referred to by the code within the function.
- Variables created outside of functions are global variables, and the code in all functions have
access to all global variables.
- If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes
that the variable is global. This can cause debugging problems.
- In general, it’s better to pass local variables from one function to another as parameters than
it
is to use global variables. That will make your code easier to understand with less chance for
errors.
JavaScript Let
ECMAScript 2015
ES2015 introduced two important new JavaScript keywords: let
and
const
.
These two keywords provide Block Scope variables (and
constants) in JavaScript.
Before ES2015, JavaScript had only two types of scope: Global Scope
and Function Scope.
Global Scope
Variables declared Globally (outside any function) have
Global Scope.
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Global variables can be accessed from anywhere in a JavaScript program.
Function Scope
Variables declared Locally (inside a function) have
Function Scope.
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
Local variables can only be accessed from inside the function where they are
declared.
JavaScript Block Scope
Variables declared with the var
keyword cannot have
Block
Scope.
Variables declared inside a block {} can be accessed from
outside the block.
{
var x = 2;
}
// x CAN be used here
Before ES2015 JavaScript did not have Block Scope.
Variables declared with the let
keyword can have Block Scope.
Variables declared inside a block {} cannot be accessed
from outside the block:
{
let x = 2;
}
// x can NOT be used here
Redeclaring Variables
Redeclaring a variable using the var
keyword can impose
problems.
Redeclaring a variable inside a block will also redeclare the variable
outside the block:
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let
keyword can solve this
problem.
Redeclaring a variable inside a block will not redeclare the variable outside
the block:
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Browser Support
The let
keyword is not fully supported in Internet Explorer 11
or
earlier.
The following table defines the first browser versions with full support for the let
keyword:
|
|
|
|
|
Chrome 49 |
Edge 12 |
Firefox 44 |
Safari 11 |
Opera 36 |
Mar, 2016 |
Jul, 2015 |
Jan, 2015 |
Sep, 2017 |
Mar, 2016 |
Loop Scope
Using var
in a loop:
var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
// Here i is 10
Using let
in a loop:
Example
let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
// Here i is 5
In the first example, using var
, the variable declared in
the loop redeclares the variable outside the loop.
In the second example, using let
, the variable declared in
the loop does not redeclare the variable outside the loop.
When let
is used to declare the i variable in a loop, the i
variable will only be visible within the loop.
Function Scope
Variables declared with var
and let
are
quite similar when declared inside a function.
They will both have Function Scope:
function myFunction() {
var carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
Global Scope
Variables declared with var
and let
are
quite similar when declared outside a block.
They will both have Global Scope:
var x = 2; // Global scope
let x = 2; // Global scope
Global Variables in HTML
With JavaScript, the global scope is the JavaScript environment.
In HTML, the global scope is the window object.
Global variables defined with the var
keyword belong to the
window
object:
var carName = "Volvo";
// code here can use window.carName
Global variables defined with the let
keyword do not belong to
the
window object:
let carName = "Volvo";
// code here cannot use window.carName
Redeclaring
Redeclaring a JavaScript variable with var
is allowed
anywhere in a program:
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
Redeclaring a var
variable with let
, in the same scope, or in
the same block, is not allowed:
var x = 2; // Allowed
let x = 3; // Not allowed
{
var x = 4; // Allowed
let x = 5 // Not allowed
}
Redeclaring a let
variable with let
, in the same scope, or in
the same block, is not allowed:
let x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 4; // Allowed
let x = 5; // Not allowed
}
Redeclaring a let
variable with var
, in the same scope, or in
the same block, is not allowed:
let x = 2; // Allowed
var x = 3; // Not allowed
{
let x = 4; // Allowed
var x = 5; // Not allowed
}
Redeclaring a variable with let
, in another scope, or in
another block, is allowed:
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
Hoisting
Variables defined with var
are hoisted to the
top
and can be initialized at any time .
Meaning: You can use the variable before it is declared:
carName = "Volvo";
alert(carName);
var carName;
Variables defined with let
are hoisted to the top
of the block, but not initialized.
Meaning: The block of code is aware of the
variable, but it cannot be used until it has been declared.
Using a let
variable before it is declared will result in a
ReferenceError
.
The variable is in a "temporal dead zone" from the start
of the block until it is declared:
carName = "Volvo";
let carName;
JavaScript Const
ECMAScript 2015
ES2015 introduced two important new JavaScript keywords: let
and
const
.
Variables defined with const
behave like let
variables, except they
cannot be reassigned:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Try it Yourself
»
Block Scope
Declaring a variable with const
is similar to let
when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared outside the
block:
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Assigned when Declared
JavaScript const
variables must be assigned a value when they
are
declared:
const PI;
PI = 3.14159265359;
Correct
const PI = 3.14159265359;
Not Real Constants
The keyword const
is a little misleading.
It does NOT define a constant value. It defines a constant reference to a value.
Because of this, we cannot change constant primitive values, but we can change the properties of
constant objects.
Primitive Values
If we assign a primitive value to a constant, we cannot change the
primitive value:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Try it Yourself
»
Constant Objects can Change
You can change the properties of a constant object:
Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
Try it Yourself
»
But you can NOT reassign a constant object:
Example
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Try it Yourself
»
Constant Arrays can Change
You can change the elements of a constant array:
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Toyota";
// You can add an element:
cars.push("Audi");
Try it Yourself
»
But you can NOT reassign a constant array:
Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
Try it Yourself
»
Redeclaring
Redeclaring a JavaScript var
variable is allowed
anywhere in a program:
Example
var x = 2; // Allowed
var x = 3; // Allowed
x = 4; // Allowed
Redeclaring or reassigning an existing var
or let
variable to const
, in the
same
scope, or in
the same block, is not allowed:
Example
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
Redeclaring or reassigning an existing const
variable, in the
same
scope, or in
the same block, is not allowed:
Example
const x = 2; // Allowed
const x = 3; // Not allowed
x = 3; // Not allowed
var x = 3; // Not allowed
let x = 3; // Not allowed
{
const x = 2; // Allowed
const x = 3; // Not allowed
x = 3; // Not allowed
var x = 3; // Not allowed
let x = 3; // Not allowed
}
Redeclaring a variable with const
, in another scope, or in
another
block, is allowed:
Example
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
Hoisting
Variables defined with var
are hoisted to the
top
and can be initialized at any time (if you don't know what Hoisting is, read our
Hoisting Chapter).
Meaning: You can use the variable before it is declared:
Example
This is OK:
carName = "Volvo";
alert(carName);
var carName;
Try it Yourself
»
Variables defined with const
are hoisted to the top
of the block, but not initialized.
Meaning: The block of code is aware of the
variable, but it cannot be used until it has been declared.
The variable is in a "temporal dead zone" from the start
of the block until it is declared.
Using a const
variable before it is declared, is a syntax
errror,
so the code will simply not run.
JavaScript | Numbers
JavaScript numbers are always stored as double-precision 64-bit binary format IEEE 754.
This format stores numbers in 64 bits,
- 0-51 bit stores value(fraction)
- 52-62 bit stores exponent
- 63-bit stores sign
The types of number literals You can use decimal, binary, octal, and hexadecimal.
- Decimal Numbers:
JavaScript Numbers does not have different types of numbers(ex: int, float, long, short) which
other
programming languages do.
It has only one type of number and it can hold both with or without decimal values.
- If the number starts with 0 and the following number is smaller than 8. It will be parsed as an
Octal Number.
Integers are accurate up to 15 digits:
- The floating point is not 100% accurate. The maximum number of decimals is up to 17.
- Binary Numbers
They start with 0b or 0B followed by 0’s and 1’s.
- Octal Numbers
They start with 0 followed by a number of ranges from 0-7. If any number is used it will be
taken as
a decimal number.
- Hexadecimal Numbers
They start with 0x or 0X followed by any digit belonging (0123456789ABCDEF)
Functions in JavaScript
A function is a set of statements that take inputs, do some specific computation, and produces
output. Basically, a function is a set of statements that performs some tasks or does some
computation
and then return the result to the user.
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead
of writing the same code again and again for different inputs, we can call that function.
Like other programming languages, JavaScript also supports the use of functions. You must already
have
seen some commonly used functions in JavaScript like alert(), this is a built-in function in
JavaScript. But JavaScript allows us to create user-defined functions also.
We can create functions in JavaScript using the keyword function. The basic syntax to create a
function in JavaScript is shown below.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the above
syntax to create a function in JavaScript. A function definition is sometimes also termed as
function
declaration or function statement.
Below are the rules for creating a function in JavaScript:
- Every function should begin with the keyword function followed by,
- A user defined function name which should be unique,
- A list of parameters enclosed within parenthesis and separated by commas,
- A list of statement composing the body of the function enclosed within curly braces {}.
Function Parameters
Till now we have heard a lot about function parameters but haven\’t discussed them in detail.
Parameters are additional information passed to a function. For example, in the above example, the
task of the function calcAddition is to calculate addition of two numbers. These two numbers on
which
we want to perform the addition operation are passed to this function as parameters. The parameters
are passed to the function within parentheses after the function name and separated by commas. A
function in JavaScript can have any number of parameters and also at the same time a function in
JavaScript can not have a single parameter.
Calling Functions: After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the value of parameters
enclosed between parenthesis and a semicolon at the end. Below syntax shows how to call functions in
JavaScript:
functionName( Value1, Value2, ..);
Return Statement: There are some situations when we want to return some values from a function after
performing some operations. In such cases, we can make use of the return statement in JavaScript.
This
is an optional statement and most of the times the last statement in a JavaScript function. Look at
our first example with the function named as calcAddition. This function is calculating two numbers
and then returning the result. The most basic syntax of using the return statement is:
return value;
Objects in Javascript
Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String,
Boolean, null, undefined and symbol) in the sense that while these primitive data-types all store a
single value each (depending on their types).
- Objects are more complex and each object may contain any combination of these primitive
data-types
as well as reference data-types.
- An object, is a reference data type. Variables that are assigned a reference value are given a
reference or a pointer to that value. That reference or pointer points to the location in memory
where the object is stored. The variables don’t actually store the value.
- Loosely speaking, objects in JavaScript may be defined as an unordered collection of
related data, of primitive or reference types, in the form of “key: value” pairs.
These
keys can be variables or functions and are called properties and methods, respectively, in the
context of an object.
An object can be created with figure brackets {…} with an optional list of properties. A property is
a “key: value” pair, where a key is a string (also called a “property name”), and value can be
anything.
To understand this rather abstract definition, let us look at an example of a JavaScript Object :
let school = {
name : "Vivekananda School",
location : "Delhi",
established : "1971"
}
In the above example “name”, “location”, “established” are all “keys” and “Vivekananda School”,
“Delhi” and 1971 are values of these keys respectively.
Each of these keys is referred to as properties of the object. An object in JavaScript may also have
a
function as a member, in which case it will be known as a method of that object.
Properties of JavaScript Object
The property names can be strings or numbers. In case the property names are numbers, they must be
accessed using the “bracket notation” like this :
let school = {
name: 'Vivekananda School',
location : 'Delhi',
established : '1971',
50 : 1000,
displayInfo : function(){
console.log(`The value of the key 50 is ${school['50']}`);
}
} school.displayInfo();
Output:
But more on the bracket notation later.
Property names can also be strings with more than one space separated words. In which case, these
property names must be enclosed in quotes :
Inherited Properties
Inherited properties of an object are those properties which have been inherited from the object’s
prototype, as opposed to being defined for the object itself, which is known as the object’s Own
property. To verify if a property is an objects Own property, we can use the hasOwnProperty method.
Property Attributes
- value: The property’s value.
- writable: When true, the property’s value can be changed
- enumerable: When true, the property can be iterated over by “for-in”
enumeration.
Otherwise, the property is said to be non-enumerable.
- configurable:If false, attempts to delete the property, change the property to
be
an access-or property, or change its attributes (other than [[Value]], or changing [[Writable]]
to
false) will fail.
// hasOwnProperty code in js
const object1 = new Object();
object1.property1 = 52;
console.log(object1.hasOwnProperty('property1')); // true
Creating Objects
There are several ways or syntax’s to create objects. One of which, known as the Object literal
syntax, we have already used. Besides the object literal syntax, objects in JavaScript may also be
created using the constructors, Object Constructor or the prototype pattern.
- Using the Object literal syntax : Object literal syntax uses the {…} notation to initialize an
object an its methods/properties directly.
var obj = {
member1 : value1,
member2 : value2,
};
These members can be anything – strings, numbers, functions, arrays or even other objects. An object
like this is referred to as an object literal. This is different from other methods of object creation
which involve using constructors and classes or prototypes, which have been discussed below.
- Object Constructor : Another way to create objects in JavaScript involves using the “Object”
constructor. The Object constructor creates an object wrapper for the given value. This, used in
conjunction with the “new” keyword allows us to initialize new objects.
Example :
const school = new Object();
school.name = 'School Name';
school.location = 'Mumbai';
school.established = 1991;
school.displayInfo = function(){
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
school.displayInfo();
Output:
The two methods mentioned above are not well suited to programs that require the creation of multiple
objects of the same kind, as it would involve repeatedly writing the above lines of code for each such
object. To deal with this problem, we can make use of two other methods of object creation in
JavaScript that reduces this burden significantly, as mentioned below:
- Constructors: Constructors in JavaScript, like in most other OOP languages, provides a template
for creation of objects. In other words, it defines a set of properties and methods that would be
common to all objects initialized using the constructor.
function Vehicle(name, maker) {
this.name = name;
this.maker = maker;
} let car1 = new Vehicle('Fiesta', 'Ford');
let car2 = new Vehicle('Santa Fe', 'Hyundai')
console.log(car1.name); // Output: Fiesta
console.log(car2.name); // Output: Santa Fe
Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this
manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :
- It creates a new object and sets the constructor property of the object to schools (It is
important to note that this property is a special default property that is not enumerable and
cannot be changed by setting a “constructor: someFunction” property manually).
- Then, it sets up the object to work with the
Vehicle
function’s
prototype object ( Each function in JavaScript gets a prototype object, which is initially just an
empty object but can be modified.The object, when instantiated inherits all properties from its
constructor’s prototype object).
- Then calls Vehicle() in the context of the new object, which means that when the “this” keyword
is encountered in the constructor(vehicle()), it refers to the new object that was created in the
first step.
- Once this is finished, the newly created object is returned to car1 and car2(in the above
example).
class people {
constructor()
{
this.name = "kartik";
}
}
let person1 = new people();
// Output : kartik
console.log(person1.name);
Prototypes : Another way to create objects involves using prototypes. Every JavaScript function has a
prototype object property by default(it is empty by default). Methods or properties may be attached to
this property. A detailed description of prototypes is beyond the scope of this introduction to
objects.
However you may familiarize yourself with the basic syntax used as below:
let obj = Object.create(prototype_object, propertiesObject)
// the second propertiesObject argument is optional
Accessing Object Members
Object members(properties or methods) can be accessed using the :
- dot notation
(objectName.memberName)
let school = {
name : "name",
location : "Mumbai",
established : 1991,
20 : 1000,
displayinfo : function() {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
} console.log(school.name); console.log(school.established);
Output
- Bracket Notation :
objectName["memberName"]
let school = {
name : "name",
location : "Delhi",
established : 1919,
20 : 1000,
displayinfo : function() {
document.write(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
// Output : name
console.log(school['name']);
// Output: 1000
console.log(school['20']);
Iterating over all keys of an object
To iterate over all existing enumerable keys of an object, we may use the for...in construct. It is
worth noting that this allows us to access only those properties of an object which are enumerable
(Recall that enumerable is one of the four attributes of data properties).
For instance, properties inherited from the Object.prototype are not enumerable. But, enumerable
properties inherited from somewhere can also be accessed using the for...in construct
Iterating over all keys of an object
To iterate over all existing enumerable keys of an object, we may use the for...in construct. It is
worth noting that this allows us to access only those properties of an object which are enumerable
(Recall that enumerable is one of the four attributes of data properties).
For instance, properties inherited from the Object.prototype are not enumerable. But, enumerable
properties inherited from somewhere can also be accessed using the for...in construct
let person = {
gender : "male"
}
var person1 = Object.create(person);
person1.name = "kartik";
person1.age = 52;
person1.nationality = "indian";
for (let key in person1) {
// Output : name, age, nationality
// and gender
console.log(key);
}
Deleting Properties
To Delete a property of an object we can make use of the delete operator. An example of its usage has
been listed below:
let obj1 = {
propfirst : "kartik"
}
// Output : kartik
console.log(obj1.propfirst);
delete obj1.propfirst
// Output : undefined
console.log(obj1.propfirst);
JavaScript Events
Javascript has events to provide a dynamic interface to a webpage. These events are hooked to
elements in the Document Object Model(DOM).
These events by default use bubbling propagation i.e, upwards in the DOM from children to parent. We
can bind events either as inline or in an external script.
There are some javascript events:
- onclick events: This is a mouse event and provokes any logic defined if the user clicks on the
element it is bound to.
<!doctype html>
<html>
<head>
<script>
function onclick() { alert('Hi there!'); } </script>
</head>
<body>
<button type="button" onclick="onclick()">
Click me event</button> </body>
</html>
onkeyup event: This event is a keyboard event and executes instructions whenever a key is released
after pressing.
<!doctype html>
<html>
<head>
<script>
function onclick() { alert('Hi there!'); } </script>
</head>
<body>
<button type="button" onclick="onclick()">
Click me event</button> </body>
</html>
<!doctype html>
<html>
<head>
<script>
var a = 0; var b = 0; var c = 0; function changeBackground() { var x = document.getElementById('bg'); bg.style.backgroundColor = 'rgb('+a+', '+b+', '+c+')'; a += 1; b += a + 1; c += b + 1; if (a >
255) a = a - b; if (b >
255) b = a; if (c >
255) c = b; } </script>
</head>
<body>
<input id="bg" onkeyup="changeBackground()" placeholder="write something" style="color:#fff">
</body>
</html>
<!doctype html>
<html>
<head>
<script>
function hov() { var e = document.getElementById('hover'); e.style.display = 'none'; } </script>
</head>
<body>
<div id="hover" onmouseover="hov()" style="background-color:aqua;height:200px;width:200px;">
</div>
</body>
</html>
onchange event: This event detects the change in value of any element listing to this event.
<!doctype html>
<html>
<head>
</head>
<body>
<input onchange="alert(this.value)" type="number">
</body>
</html>
onload event: When an element is loaded completely, this event is evoked.
<!doctype html>
<html>
<head>
</head>
<body>
<img onload="alert('Image completely loaded')" src="img.png">
</body>
</html>
onfocus event: An element listing to this event executes instructions whenever it recieves focus.
<!doctype html>
<html>
<head>
<script>
function focused() { var e = document.getElementById('inp'); if (confirm('Got it?')) { e.blur(); } } </script>
</head>
<body>
<p >
Take the focus into the input box below:</p> <input id="inp" onfocus="focused()">
</body>
</html>
onblur event: This event is evoked when an element loses focus.
<!doctype html>
<html>
<head>
</head>
<body>
<p>
Write something in the input box and then click elsewhere in the document body.</p>
<input onblur="alert(this.value)">
</body>
</html>
PS: onmouseup event listens to left and middle mouse click, but onmousedown event listens to left,
middle, and right mouse clicks whereas onclick only handles left click.
if-else Statement in JavaScript
Decision Making in programming is similar to decision making in real life. In programming also we
face some situations where we want a certain block of code to be executed when some condition is
fulfilled.
A programming language uses control statements to control the flow of execution of the program based
on certain conditions. These are used to cause the flow of execution to advance and branch based on
changes to the state of a program.
JavaScript’s conditional statements:
- if
- if-else
- nested-if
- if-else-if
These statements allow you to control the flow of your program’s execution based upon conditions
known only during run time.
- if: if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
if(condition)
{
//code goes here }
here , condition after evaluation will be ethier true or false . if statement
accepts boolean values - if the value is true then it will execute the bloack
of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement
will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
if-else: 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 (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
// JavaScript program to illustrate If-else statement
var i = 10;
if (i < 15)
document.write("10 is less than 15");
else
document.write("false");
nested-if: A nested if is an if statement that is the target of another if or else. Nested if
statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
// JavaScript program to illustrate nested-if statement
var i = 10;
if (i == 10) {
// First if statement
if (i < 15)
document.write("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
document.write("i is smaller than 12 too");
else
document.write("i is greater than 15");
}
if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement;
code statement
else
statement;
example
// JavaScript program to illustrate nested-if statement
var i = 20;
if (i == 10)
document.write("i is 10");
else if (i == 15)
document.write("i is 15");
else if (i == 20)
document.write("i is 20");
else
document.write("i is not present");
Switch Case in JavaScript
A switch statement starts with a variable called switch value . each case indicates
a possible value for this variable and the code that should run if the variable
matches that values .
syntax
switch (level) {
case 'one':
title = 'level 1';
break;
case 'two':
title = 'level 2';
break;
case 'three':
title = 'level 3';
break;
case 'four':
title = 'level 4';
break;
}
- expression can be of type numbers or strings.
- Dulplicate case values are not allowed.
- The default statement is optional. If the expression passed to switch does not matches
with value in any case then the statement under default will be executed.
- The break statement is used inside the switch to terminate a statement sequence.
- The break statement is optional. If omitted, execution will continue on into the next
case.
If else VS. Switch statements
If Else :
- There is no need to provide else option . (You can just use if statement) .
- With a series of if statement they are all checked even if a match has been
found .
Switch Statement
- You have a defualt option that is run if none of the cases match .
- if a match is found that code is run; then the break statement stops the
rest of the switch statement running (providing better performance then
muitlple if statements).
JavaScript | Break and Continue
Break statement: The break statement is used to jump out of a loop. It can be used to “jump out” of a
switch() statement. It breaks the loop and continues executing the code after the loop
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript Break statement </title>
</head>
<body style="text-align:center;">
<div>
<h1>
Codolearnlt;/h1> <h2>
JavaScript Break</h2>
</div>
<p id="codo"></p>
<script>
var content = "";
var i;
for (i = 1; i < 1000; i++) {
if (i === 6) {
break;
}
content += "codolearn" + i + "";
}
document.getElementById("cod").innerHTML = content;
</script>
</body>
</html>
Continue statement: The continue statement “jumps over” one iteration in the loop. It breaks
iteration in the loop and continues executing the next iteration in the loop.
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript continue statement </title>
</head>
<body style="text-align:center;">
<div>
<h1>
codolearn</h1> <h2>
JavaScript continue</h2> </div>
<p id="codo">
</p> <script>
var content = "";
var i;
for (i = 1; i < 7; i++) {
if (i === 4) {
continue;
}
content += "codolearn" + i + "";
}
document.getElementById("codo").innerHTML = content;
</script>
</center>
</body>
</html>
JavaScript labels: In JavaScript, the label statements are written as the statements with a label
name and a colon.
Syntax:
- break statements: It is used to jump out of a loop or a switch without a label
reference while with label reference, it used to jump out of any code block.
break labelname;
- continue statements: It used to skip one loop iteration with or without a label
reference.
continue labelname;
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript continue statement </title>
</head>
<body style="text-align:center;">
<div>
<h1 style="color:green;">
codolearn </h1>
<h2>
JavaScript break</h2> </div>
<p id="codo">
</p> <!-- Script to use break label -->
<script>
var val = ["codolearner1", "codolearner2", "codolearner3", "codolearner4", "codolearner5"];
var print = "";
breaklabel: {
print += val[0] + "" + val[1] + "";
break breaklabel;
print += val[2] + ""+ val[3] + "" + val[4];
}
document.getElementById("codo").innerHTML = print;
</script>
</body>
</html>
JavaScript | Type Conversion
JavaScript is loosely typed language and most of the time operators automatically convert a value to
the right type but there are also cases when we need to explicitly do type conversions.
While JavaScript provides numerous ways to convert data from one type to another but there are two
most common data conversions :
- Converting Values to String
- Converting Values to Numbers
Implicit Conversion:
There are various operator and functions in JavaScript which automatically converts a value to the
right type like alert() function in JavaScript accepts any value and convert it into a string. But
various operator creates a problem like ‘+’ operator.
Example:
Input: "2" + "3"
Output: "23"
here + operator stands for string concatenation in this case.
But "3" - "1" gives output 2 by using Implicit Conversion.
Converting Values to Strings:
String() or toString() function can be used in JavaScript to convert a value to a string.
Syntax of String() function:
Example:
Input:
var v = 1555;
var s = String(v);
Output:
now s contains "1555".
Converting Values to Numbers:
We can use Number() function in JavaScript to convert a value to a Number. It can convert any
numerical text and boolean value to a Number. In case of strings of non-numbers it will convert it to
a NaN(Not a Number).
Syntax:
Example
Input:
var s = "144";
var n = Number(s);
Output:
now n contain 144(Number)
JavaScript Regular Expressions
Below is the example of the JavaScript Regular Expressions.
-
<script>
function GFGFun() {
var str = "Visit codolearn";
var n = str.search(/codolearn/i);
document.write(n);
}
codoFun();
</script>
A regular expression is a sequence of characters that forms a search pattern. The search pattern can
be used for text search and text to replace operations. A regular expression can be a single
character or a more complicated pattern. Regular expressions can be used to perform all types of
text search and text replace operations.
Regular Expression Modifiers :
Modifiers can be used to perform multiline searches:
Examples:
Expressions |
Description |
[abc] |
Find any of the character inside the brackets |
[0-9] |
Find any of the digits between the brackets 0 to 9 |
(x | y) |
Find any of the alternatives between x or y separated with | |
Regular Expression Patterns :
Metacharacters are characters with a special meaning:
Examples:
Metacharacter |
Description |
\d |
Used to find a digit |
\s |
Used to find a whitespace character |
\b |
Used to find a match at beginning or at the end of a word |
\uxxxx |
Used to find the Unicode character specified by the hexadecimal
number xxxxx |
Quantifiers define quantities:
Quantifier |
Description |
n+ |
Used to match any string that contains at least one n |
n* |
Used to match any string that ccontains zero or more occurrences of
n |
n? |
Used to matches any string that contains zero or one occurrences of
n |
Using String Methods:
In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for “codolearn” in a string:
Use String replace() With a Regular Expression :
Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:
Understanding variable scopes in JavaScript
In JavaScript, there are two types of scopes
-
Global Scope – Scope outside the outermost function attached to window.
-
Local Scope – Inside the function being executed.
Let’s look at the code below. We have a global variable defined in first line in global scope. Then
we have a local variable defined inside the function fun().
let globalLets = "This is a global variable";
function fun() {
let localLets = "This is a basic example local variable";
console.log(globalLets); // This is a global variable
console.log(localLets); // This is a local variable
}
fun();
Try
it Yourself
When we execute the function fun(), the output shows that both global, as well as local variables, are
accessible inside the function as we are able to console.log them. This shows that inside the function
we have access to both global variables (declared outside the function) and local variables (declared
inside the function). Let’s move the console.log statements outside the function and put them just after
calling the function.
let globalLets = "This is a global variable";
function fun() {
let localLets = "This is a local variable";
}
fun();
console.log(globalLets); // This is a global variable
console.log(localLets); // localLets is not defined
Try
it Yourself
We are still able to see the value of the global variable, but for local variable console.log throws an
error. This is because now the console.log statements are present in global scope where they have access to
global variables but cannot access the local variables.
Word of caution: Whenever you are declaring variables, always use the prefix let. If you don’t use the let
keyword, then the variables are by default created in the global scope. For instance, in the above example,
let’s just remove the keyword let before the declaration of localLet.
let globalLet = "This is a global variable";
function fun() {
let globalLet = "This is a local variable";
}
fun();
console.log(globalLet); // This is a global variable
Try
it Yourself
In this example, we have the declared a local as well as global variable “globalLet”. What matters here is
the scope in which we are accessing it. In the above example, we are accessing it in global scope, so it
will output the global variable as local variable is not present in its scope.Let’s move the console.log
statement inside the function fun().
let globalLet = "This is a global variable";
function fun() {
let globalLet = "This is a local variable";
console.log(globalLet); // This is a local variable
}
fun();
Try
it Yourself
Inside the function fun(), both the local as well as global variables are accessible. But when we console.log
the variable globalLet, firstly JavaScript tries to find a local variable in the current scope. It finds the
local variable and outputs it. Otherwise it would have search for the variable “globalLet” in the outer
scope (which in this case is global scope).
What if we want to access the global variable instead of local one here. Well, the window object comes to
our rescue. All the global variables are attached to window object and thus we can access the global
variable name as shown in example below.
After discussing about scopes in JavaScript, guessing the output of below code fragments should be a
cakewalk.
function fun(){
function fun2(){
i = 500;
}
fun2();
console.log(i); // 500
}
fun();
Try
it Yourself
In the first example as we didn’t use the keyword let, the variable “i” was assumed to be declared in global
scope and thus the output was 100. In the second example, “i” became a local variable and thus was not
accessible outside the scope of that function.
Let’s look at another example-
function fun(){
if(true){
let i = 100;
}
console.log(i); // i is not defined
}
fun();
Try
it Yourself
After ES2015, we started using let instead of var for declaring variables and also now the if block is also
counted as a block scope, hence in the above example we get an error instead of the value 100. If we change
the let to var we will get 100 as output as if block was not considered a block scope earlier, only
functions were.
Arrays In javascript
An array is a specaial type of variable it doest'n just store a one value
it store a list of values . In other words
In JavaScript, array is a single variable that is used to store different elements. It is often used when we
want to store list of elements and access them by a single variable. Unlike most languages where array is a
reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.
Creating an array
syntax
var array_name = [item1, item2, ...];
example
var cars = ["Lamborgini sain", "Lamborgini tarzo", "Bugatti divo", "Lamborgini SVJ23"];
Try
it Yourself
You can create a array and give it a name just like you would any other variable
the value are assinged to the array inside a pair of sqaure barakets and each value
are saperated by a comma . the value in the array do not need to be the same
datatype , so you can store a string a number and boolean all in the same array .
Converting Arrays to Strings
The JavaScript method toString() converts an array to a string of (comma separated) array values.
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
var cars = ["Lamborgini sain", "Lamborgini tarzo", "Bugatti divo", "Lamborgini SVJ23"];
document.getElementById("demo").innerHTML = cars.join(" + ");
Try
it Yourself
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
Popping
The pop() method removes the last element from an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Try
it Yourself
Pushing
The push() method adds a new element to an array (at the end):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Try
it Yourself
The push() method returns the new array length:
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first array element and "shifts" all other elements to a lower index.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
Try
it Yourself
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Try
it Yourself
Changing Elements
Array elements are accessed using their index number:
The length property provides an easy way to append a new element to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits
Try
it Yourself
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
Try
it Yourself
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items:
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
Try
it Yourself
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Merging (Concatenating) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays:
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys);
Try
it Yourself
The concat() method can take any number of array arguments:
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3);
Try
it Yourself
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
Try
it Yourself
This example slices out a part of an array starting from array element 3 ("Apple"):
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not including) the end argument.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
Try
it Yourself
If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the
array.
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a primitive value is expected.
This is always the case when you try to output an array.
These two examples will produce the same result:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Try
it Yourself
Finding Max and Min Values in an Array
There are no built-in functions for finding the highest or lowest value in a JavaScript array.
You will learn how you solve this problem in the next chapter of this tutorial.
JavaScript Array Iteration Methods
Array iteration methods operate on every array item.
Array.forEach()
The forEach()
method calls a function (a callback function) once for
each array element.
Example
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt = txt + value + "
";
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
The example above uses only the value parameter. The example can be rewritten
to:
Example
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "
";
}
Try it Yourself »
Array.forEach()
is supported in all browsers except Internet Explorer 8
or earlier:
Array.map()
The map()
method creates a new array by performing a function on each
array element.
The map()
method does not execute the function for array
elements without values.
The map()
method does not change the original array.
This example multiplies each array value by 2:
Example
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
When a callback function uses only the value parameter, the index and array
parameters can be omitted:
Example
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Try it Yourself »
Array.map()
is supported in all browsers except Internet Explorer 8 or
earlier.
Array.filter()
The filter()
method creates a new array with array elements that passes
a test.
This example creates a new array from elements with a value larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
In the example above, the callback function does not use the index and array
parameters, so they can be omitted:
Example
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Try it Yourself »
Array.filter()
is supported in all browsers except Internet Explorer 8
or earlier.
Array.reduce()
The reduce()
method runs a function on each array element to produce
(reduce it to) a single value.
The reduce()
method works from left-to-right in the array. See also
reduceRight()
.
The reduce()
method does not reduce the original array.
This example finds the sum of all numbers in an array:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
Try it Yourself »
Note that the function takes 4 arguments:
- The total (the initial value / previously returned value)
- The item value
- The item index
- The array itself
The example above does not use the index and array parameters. It can be
rewritten to:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »
The reduce()
method can accept an initial value:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction, 100);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »
Array.reduce()
is supported in all browsers except Internet Explorer 8
or earlier.
Array.reduceRight()
The reduceRight()
method runs a function on each array element to
produce (reduce it to) a single value.
The reduceRight()
works from right-to-left in the array. See also reduce()
.
The reduceRight()
method does not reduce the original array.
This example finds the sum of all numbers in an array:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
Try it Yourself »
Note that the function takes 4 arguments:
- The total (the initial value / previously returned value)
- The item value
- The item index
- The array itself
The example above does not use the index and array parameters. It can be
rewritten to:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »
Array.reduceRight()
is supported in all browsers except Internet
Explorer 8 or earlier.
Array.every()
The every()
method check if all array values pass a test.
This example check if all array values are larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
When a callback function uses the first parameter only (value), the other
parameters can be omitted:
Example
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
function myFunction(value) {
return value > 18;
}
Try it Yourself »
Array.every()
is supported in all browsers except Internet Explorer 8 or
earlier.
Array.some()
The some()
method check if some array values pass a test.
This example check if some array values are larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var someOver18 = numbers.some(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Array.some()
is supported in all browsers except Internet Explorer 8 or
earlier.
Array.indexOf()
The indexOf()
method searches an array for an element value and returns
its position.
Note: The first item has position 0, the second item has position 1, and so on.
Example
Search an array for the item "Apple":
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
Try it Yourself »
Array.indexOf()
is supported in all browsers except Internet Explorer 8
or earlier.
Syntax
array.indexOf(item, start)
item |
Required. The item to search for. |
start |
Optional. Where to start the search. Negative values will start at the given position
counting from the end, and search to the end. |
Array.indexOf()
returns -1 if the item is not found.
If the item is present more than once, it returns the position of the first
occurrence.
Array.lastIndexOf()
Array.lastIndexOf()
is the same as Array.indexOf()
, but
returns the position of the last occurrence of the specified element.
Example
Search an array for the item "Apple":
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
Try it Yourself »
Array.lastIndexOf()
is supported in all browsers except Internet
Explorer 8 or earlier.
Syntax
array.lastIndexOf(item, start)
item |
Required. The item to search for |
start |
Optional. Where to start the search. Negative values will start at the given position
counting from the end, and search to the beginning |
Array.find()
The find()
method returns the value of the first array element that
passes a
test function.
This example finds (returns the value of) the first element that is larger
than 18:
Example
var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Array.find()
is not supported in older browsers. The first browser
versions
with full support is listed below.
Array.findIndex()
The findIndex()
method returns the index of the first array element that
passes a test function.
This example finds the index of the first element that is larger than 18:
Example
var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Array.findIndex()
is not supported in older browsers. The first browser
versions with full support is listed below.
JavaScript Booleans
A JavaScript Boolean represents one of two values: true or
false.
Boolean Values
Very often, in programming, you will need a data type that can only have one
of two values, like
- YES / NO
- ON / OFF
- TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only
take the values true or false.
The Boolean() Function
You can use the Boolean()
function to find out if an expression (or a
variable) is
true:
Or even easier:
Comparisons and Conditions
The chapter JS Comparisons gives a full overview of comparison operators.
The chapter JS Conditions gives a full overview of conditional statements.
Here are some examples:
Operator |
Description |
Example |
== |
equal to |
if (day == "Monday") |
> |
greater than |
if (salary > 9000) |
< |
less than |
if (age < 18) |
The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.
Everything With a "Value" is True
Everything Without a "Value" is False
The Boolean value of 0 (zero) is false:
var x = 0;
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of -0 (minus zero) is false:
var x = -0;
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of "" (empty string) is false:
var x = "";
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of undefined is false:
var x;
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of null is false:
var x = null;
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of false is (you guessed it) false:
var x = false;
Boolean(x); // returns false
Try
it Yourself »
The Boolean value of NaN is false:
var x = 10 / "H";
Boolean(x); // returns false
Try
it Yourself »
Booleans Can be Objects
Normally JavaScript booleans are primitive values created from literals:
var
x = false;
But booleans can also be defined as objects with the keyword new
:
var y = new
Boolean(false);
Example
var x = false;
var y = new Boolean(false);
// typeof x returns boolean
// typeof y returns object
Do not create Boolean objects.
It slows down execution speed.
The new
keyword complicates
the code. This can produce some unexpected results:
When using the ==
operator, equal
booleans are equal:
Example
var x = false;
var y = new Boolean(false);
// (x == y) is true because x and y have equal values
Try
it Yourself »
When using the ===
operator, equal booleans are not equal, because the
===
operator expects equality in both type and value.
Example
var x = false;
var y = new Boolean(false);
// (x === y) is false because x and y have different types
Try
it Yourself »
Or even worse. Objects cannot be compared:
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always
return false.
JavaScript Comparison and Logical
Operators
Comparison and Logical operators are used to test for true
or
false
.
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.
Given that x = 5
, the table below explains the comparison operators:
Operator |
Description |
Comparing |
Returns |
== |
equal to |
x == 8 |
false |
|
x == 5 |
true |
|
x == "5" |
true |
|
=== |
equal value and equal type |
x === 5 |
true |
|
x === "5" |
false |
|
!= |
not equal |
x != 8 |
true |
|
!== |
not equal value or not equal type |
x !== 5 |
false |
|
x !== "5" |
true |
|
x !== 8 |
true |
|
> |
greater than |
x > 8 |
false |
|
< |
less than |
x < 8 |
true |
|
>= |
greater than or equal to |
x >= 8 |
false |
|
<= |
less than or equal to |
x <= 8 |
true |
|
How Can it be Used
Comparison operators can be used in conditional statements to compare values
and take action depending on the result:
if (age < 18) text = "Too young to buy alcohol";
You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x = 6
and y = 3
, the
table below explains the logical operators:
Operator |
Description |
Example |
Try it |
&& |
and |
(x < 10 && y > 1) is true |
|
|| |
or |
(x == 5 || y == 5) is false |
|
! |
not |
!(x == y) is true |
|
Conditional (Ternary) Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax
variablename = (condition) ? value1:value2
Example
If the variable age is a value below 18, the value of the variable voteable
will be "Too young", otherwise the value of voteable will be "Old enough".
Comparing Different Types
Comparing data of different types may give unexpected results.
When comparing a string with a number, JavaScript will convert the string to
a number when doing the comparison. An empty string converts to 0. A non-numeric
string converts to NaN
which is always false
.
Case |
Value |
2 < 12 |
true |
|
2 < "12" |
true |
|
2 < "John" |
false |
|
2 > "John" |
false |
|
2 == "John" |
false |
|
"2" < "12" |
false |
|
"2" > "12" |
true |
|
"2" == "12" |
false |
|
When comparing two strings, "2" will be greater than "12", because
(alphabetically) 1 is less than 2.
To secure a proper result, variables should be converted to the proper type
before comparison:
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
Try it Yourself
»
JavaScript For Loop
Loops can execute a block of code a number of times.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each
time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "
";
}
Try it Yourself
»
Different Kinds of Loops
JavaScript supports different kinds of loops:
for
- loops through a block of code a number of times
for/in
- loops through the properties of an object
for/of
- loops through the values of an
iterable object
while
- loops through a block of code while a specified
condition is true
do/while
- also loops through a block of code while a specified
condition is true
The For Loop
The for
loop has the following syntax:
for (statement 1;
statement 2; statement 3) {
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (i = 0; i < 5; i++) {
text += "The number is " + i + "
";
}
Try it Yourself
»
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i = 0).
Statement 2 defines the condition for the loop to run (i must be less than
5).
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is
optional.
You can initiate many values in statement 1 (separated by comma):
Example
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "
";
}
Try it Yourself
»
And you can omit statement 1 (like when your values are set
before the loop starts):
Example
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "
";
}
Try it Yourself
»
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is
also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the
loop will end.
If you omit statement 2, you must provide a break inside the
loop. Otherwise the loop will never end. This will crash your browser.
Read about breaks in a later chapter of this tutorial.
Statement 3
Often statement 3 increments the value of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is
optional.
Statement 3 can do anything like negative increment (i--), positive
increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "
";
i++;
}
Try it Yourself
»
The For/In Loop
The JavaScript for/in
statement loops through the properties of an
object:
Example
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
Try it Yourself
»
The For/Of Loop
The JavaScript for/of
statement loops
through the values of an iterable objects.
for/of
lets you loop over data structures
that are iterable such as Arrays, Strings, Maps, NodeLists, and more.
The for/of
loop has the following syntax:
for (variable of
iterable) {
}
variable - For every iteration the value of the next property is
assigned to the variable. Variable can be declared with
const
, let
, or var
.
iterable - An object that has iterable properties.
Looping over an Array
Example
var cars = ["BMW", "Volvo", "Mini"];
var x;
for (x of cars) {
document.write(x + "
");
}
Try it Yourself
»
Looping over a String
Example
var txt = "JavaScript";
var x;
for (x of txt) {
document.write(x + "
");
}
Try it Yourself
»
The While Loop
The while
loop and the do/while
loop will be explained in the next chapter.
JavaScript While Loop
Loops can execute a block of code
as long as a specified condition is true.
The While Loop
The while
loop loops through a block of code as long as a specified
condition is true.
Syntax
while (i < 10) {
text += "The number is " + i;
i++;
}
Example
In the following example, the code in the loop will run, over and over again, as long as
a variable (i) is less than 10:
If you forget to increase the variable used in the condition, the loop will never end.
This will crash your browser.
The Do/While Loop
The do/while
loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
}
while (condition);
Example
The example below uses a do/while
loop. The loop will always be
executed at least once, even if the condition is false, because the code block
is executed before the condition is tested:
Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
Comparing For and While
If you have read the previous chapter, about the for loop, you will discover that a while loop is
much the same as a for loop, with statement 1 and statement 3 omitted.
The loop in this example uses a for
loop to collect the car
names from the cars array:
Example
var
cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}
Try it Yourself
»
The loop in this example uses a while
loop to collect the
car names from the cars array:
Example
var
cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
while (cars[i])
{
text += cars[i] + "<br>";
i++;
}
Try it Yourself
»