L1 JavaScript
L1 JavaScript
1.What is JavaScript?
2.How JS Powers the Internet
3.Variables
4.Data Types
5.Type Conversion, nAn, Infinity
6. JavaScript Operators
7. Strings
8. String Properties
9. String Operations
10. Inbuilt String functions
11. String Methods
What is JavaScript ?
● JavaScript is a high level, Interpreted programming language used to make web pages
more interactive.
● Every time a web page does more than just sit there and display static information for
you to look at — Timely Updates, Alerts, Action on Button Click etc. is using JavaScript.
Why Dynamically Typed Language ?
Dynamically-typed languages are those where the interpreter assigns variables a type at
runtime based on the variable's value at the time.
You do not have to explicitly declare the type of variable which is being declared.
● It is just a static unresponsive HTML with images, texts, buttons & other UI features.
● No use of such web page from the perspective of a business or the customers.
This is where JavaScript comes into the picture, It provides the following advantages:
● It is very fast because any code can run immediately instead of having to contact the
server.
● It allows you to create highly responsive interfaces to improve the user experience.
● JavaScript has no compilation step. Instead, an interpreter in the browser reads over
the JavaScript code, interprets each line and runs it.
● It provides dynamic functionality without even having to wait for the server to react and
show another page.
● There are 1.9 billion websites on the Internet today. And 95% of them use JavaScript in
some way or the other.
● Try turning off the JavaScript access on your web browser and you’d see several sites
and web apps start to crack and look dull and drab. That’s because it is JavaScript that
manages the interactivity of the web.
● Plus, developers love it because it is simple to learn and master. You could start with 0
coding experience and still be able to create something beautiful with just the knowledge
of JavaScript. For businesses, it means never having to struggle to find able JavaScript
developers.
Other than simplicity, JavaScript is also known for its speed and versatility. It can be used for the
following programming projects:
Reference :
https://insights.stackoverflow.com/survey/2021#programming-scripting-and-markup-languages
Server-side Rendering :
As discussed above, the traditional way of rendering dynamic web content follows the below
steps:
● A front-end web developer’s role is to create the code and mark-up that is rendered by a
web browser when you visit a site (read: they control what you see when you visit a
webpage).
● There are three main components when it comes to front-end development: HTML, CSS
and JavaScript. Each are critical for making a webpage what it is. HTML is the structure
and content of the site, CSS (Cascading Style Sheets) makes it look pretty, and, lastly,
JavaScript is what powers its interactivity. Each work hand-in-hand when it comes to
building websites, but the focus of this blog post is on JavaScript and how it’s used.
INTERACTIVITY
JavaScript is a very powerful tool that can do many things for a website. For one, it powers the
site’s general interactivity. JavaScript makes it possible to build rich UI components such as
image sliders, pop-ups, site navigation mega menus, form validations, tabs, accordions, and
much more.
PLUGINS
There are various plugins and that run off of JavaScript. If you’ve ever visited a site that features
banner ads, has chat support, suggests content, has forms, or offers social sharing, there’s a
good chance it’s powered by a 3rd party JavaScript plugin. Usually, these plugins have
configurable options that need additional set-up to function properly. Understanding the
configurable options of these plugins is essential. Plugins are generally intended to be easily
dropped into a site with little modification.
FRAMEWORKS
● A JavaScript framework can be a powerful tool you can use to help render the page.
These are typically only used when there are complex dynamic interactions that need to
occur.
● One example of this is if you have a multi-step form-fill. In this case, the form fill process
has certain steps that only occur based on previously entered information. Also, certain
data gets populated for certain inputs as well as previous inputs. Doing this without a
framework can be very difficult task to achieve. Things can get problematic, and this can
happen fast.
● Using a JavaScript framework helps resolve these issues so you can complete your
wonderful form, and make your clients happy. While there are dozens, the most popular
ones (as of this writing) are Google’s Angular, Facebook’s React and the open source
Vue.js.
● JavaScript is a very important tool for a front-end web developer. Without it, webpages
wouldn’t have become the dynamic web applications they are today. There would be no
image carousels. There would be no partial page reloads that keep your spot on the
page.
JavaScript Engine :
Each browser has its own JavaScript engine which is used to support the JavaScript scripts in
order for them to work properly. The basic job of a JavaScript engine is to take the JavaScript
code, then convert it into a fast, optimized code that can be interpreted by a browser. Below are
the names of the JavaScript engines used in some of the most popular browsers out there.
● Chrome: V8
● Firefox: SpiderMonkey
● Safari: JavaScript Core
● Microsoft Edge/ Internet Explorer: Chakra/ChakraCore.
What is a Variable :
Variable is a name given to a memory location that acts as a container for storing data
temporarily. They are nothing but reserved memory locations to store values.
JavaScript Variable
// Declaration
var a;
// Initialization
a = "John Doe";
if (someBool) {
console.log(a);
The name that points to "John Doe" is global, and the name that points to "Daniel Joan" is
defined within a block. However, when we try printing the name that's within scope, we run into :
Daniel Joan
var is not block-scoped. We may think that we've defined a local var name to point to "Daniel
Joan", but what we've done in reality is overwrite the var name that points to "John Doe".
Scope of let
A variable defined with the let keyword has a scope limited to the block or function in which it
is defined:
if(someBool){
console.log(firsta);
console.log(firsta);
This time around - the firsta referring to "Jane" and the firsta referring to "John" don't
overlap! The code results in:
Jane
John
The firsta declared within the block is limited to the block in scope and the one declared
outside the block is available globally. Both instances of firsta are treated as different
variable references, since they have different scopes.
const a = "John";
const a = "Jane";
Scope of const
The scope of a variable defined with the const keyword, like the scope of let declarations, is
limited to the block defined by curly braces (a function or a block). The main distinction is that
they cannot be updated or re-declared, implying that the value remains constant within the
scope:
const a = "John";
a = "Doe";
Data Types :
Reference types are also known as: complex types or container types.
An Array is a data structure that contains a list of elements of the same data type.
var student = {
roll no : 34,
name : "Mayank" ,
age : 27 ,
city : Delhi
};
3. Functions :
A function is a block of organized, reusable code that is used to perform a single, related
actions.
sum (3,4) ; // 7
sum (5,6) ; //11
result = '3' + 2;
console.log(result) // "32"
let result;
console.log(result); // 2
result = '4' - 2;
console.log(result); // 2
result = '4' * 2;
console.log(result); // 8
result = '4' / 2;
console.log(result); // 2
let result;
console.log(result); // NaN
console.log(result); // NaN
Example 4: Implicit Boolean Conversion to Number
let result;
console.log(result); // 3
result = 4 + true;
console.log(result); // 5
result = 4 + false;
console.log(result); // 4
Note: JavaScript considers 0 as false and all non-zero number as true. And, if true is
converted to a number, the result is always 1.
let result;
result = 4 + null;
console.log(result); // 4
result = 4 - null;
console.log(result); // 4
Example 6: undefined used with number, Boolean or null
let result;
result = 4 + undefined;
console.log(result); // NaN
result = 4 - undefined;
console.log(result); // NaN
console.log(result); // NaN
console.log(result); // NaN**
let result;
// string to number
result = Number('324');
console.log(result); // 324
result = Number('324e-1')
console.log(result); // 32.4
// boolean to number
result = Number(true);
console.log(result); // 1
result = Number(false);
console.log(result); // 0
let result;
result = Number(null);
console.log(result); // 0
console.log(result); // 0
let result;
result = Number('hello');
console.log(result); // NaN
result = Number(undefined);
console.log(result); // NaN
result = Number(NaN);
console.log(result); // NaN
Note: You can also generate numbers from strings using parseInt(), parseFloat(), unary
operator + and Math.floor(). For example,
let result;
result = parseInt('20.01');
console.log(result); // 20
result = parseFloat('20.01');
console.log(result); // 20.01
result = +'20.01';
console.log(result); // 20.01
result = Math.floor('20.01');
console.log(result); // 20
//number to string
let result;
result = String(324);
console.log(result); // "324"
console.log(result); // "6"
result = String(null);
console.log(result); // "null"
result = String(undefined);
console.log(result); // "undefined"
result = String(NaN);
console.log(result); // "NaN"
result = String(true);
console.log(result); // "true"
result = String(false);
console.log(result); // "false"
// using toString()
result = (324).toString();
console.log(result); // "324"
result = true.toString();
console.log(result); // "true"
Note: String() takes null and undefined and converts them to string. However,
toString() gives error when null are passed.
let result;
result = Boolean('');
console.log(result); // false
result = Boolean(0);
console.log(result); // false
result = Boolean(undefined);
console.log(result); // false
result = Boolean(null);
console.log(result); // false
result = Boolean(NaN);
console.log(result); // false
result = Boolean(324);
console.log(result); // true
result = Boolean('hello');
console.log(result); // true
console.log(result); // true
Interview Questions
Describe the Difference Between Var vs Let vs Const
Var
1. Function Scoped
2. Allows duplicate identifiers
3. Value can be updated
4. Hoisted and initialized with undefined.
Let
1. Block Scoped
2. Does NOT allow duplicate identifiers
3. Value can be updated
4. Hoisted BUT error if we try to access before declaration
Const
1. Block Scoped
2. Does NOT allow duplicate identifiers
3. Value cannot be updated
4. Hoisted BUT error if we try to access before declaration.
Implicit type coercion in JavaScript is the automatic conversion of value from one data type to
another. It takes place when the operands of an expression are of different data types.
● String coercion String coercion takes place while using the ‘ + ‘ operator. When a
number is added to a string, the number type is always converted to the string type.
var x = 3;
var y = "3";
x + y // Returns "33"
When JavaScript sees that the operands of the expression x + y are of different types ( one
being a number type and the other being a string type ), it converts the number type to the string
type and then performs the operation. Since after conversion, both the variables are of string
type, the ‘ + ‘ operator outputs the concatenated string “33”
● Boolean Coercion Boolean coercion takes place when using logical operators, ternary
operators, if statements, and loop checks. To understand boolean coercion in if
statements and operators, we need to understand truthy and falsy values. Truthy values
are those which will be converted (coerced) to true. Falsy values are those which will be
converted to false. All values except false, 0, 0n, -0, “”, null, undefined, and NaN are
truthy values.
var x = 0;
var y = 23;
if(x) { console.log(x) } // The code inside this block will not run
since the value of x is 0(Falsy)
var x = 220;
var y = "Hello";
var z = undefined;
if( x && y ){
console.log("Code runs" ); // This block runs because x && y
returns "Hello" (Truthy)
}
if( x || z ){
console.log("Code runs"); // This block runs because x || y
returns 220(Truthy)
}
● Equality Coercion Equality coercion takes place when using ‘ == ‘ operator. As we have
stated before**The ‘ == ‘operator compares values and not types.**While the above
statement is a simple way to explain == operator, it’s not completely trueThe reality is
that while using the ‘==’ operator, coercion takes place.The ‘==’ operator, converts both
the operands to the same type and then compares them.
var a = 12;
var b = "12";
a == b // Returns true because both 'a' and 'b' are converted to the
same type and then compared. Hence the operands are equal.
var a = 226;
var b = "226";
a === b // Returns false because coercion does not take place and the
operands are of different types. Hence they are not equal.
JavaScript Operators:
What is an Operator?
In JavaScript, an operator is a special symbol used to perform operations on operands (values
and variables). For example,
2 + 3; // 5
Here +is an operator that performs addition, and 2and 3are operands.
● Assignment Operators
● Arithmetic Operators
● Comparison Operators
● Logical Operators
● Bitwise Operators
● String Operators
● Other Operators
const x = 5;
Note : The commonly used assignment operator is =. You will understand other assignment
operators such as +=, -=, *= etc. once we learn arithmetic operators.
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic calculations. For example,
const number = 3 + 5; // 8
let x = 5;
let y = 3;
// addition
console.log('x + y = ', x + y); // 8
// subtraction
console.log('x - y = ', x - y); // 2
// multiplication
console.log('x * y = ', x * y); // 15
// division
console.log('x / y = ', x / y); // 1.6666666666666667
// remainder
console.log('x % y = ', x % y); // 2
// increment
console.log('++x = ', ++x); // x is now 6
console.log('x++ = ', x++); // prints 6 and then increased to 7
console.log('x = ', x); // 7
// decrement
console.log('--x = ', --x); // x is now 6
console.log('x-- = ', x--); // prints 6 and then decreased to 5
console.log('x = ', x); // 5
//exponentiation
console.log('x ** y =', x ** y);
a = 5
++a; // a becomes 6
a++; // a becomes 7
--a; // a becomes 6
a--; // a becomes 5
Simple enough till now. However, there is an important difference when these two operators are
used as a prefix and a postfix.
● If you use the ++operator as a prefix like ++var, the value of varis incremented by 1;
then it returns the value.
● If you use the ++ operator as a postfix like var++, the original value of var is returned
first; then var is incremented by 1.
The --operator works in a similar way to the ++operator except -- decreases the value by 1.
Example :
// 5 is displayed
// Then, var1 is increased to 6
console.log(var1++)
// var2 is increased to 6
// Then, var2 is displayed
console.log(++var2)
Output :
5
6
Comparison operators compare two values and return a Boolean value, either true or false.
For example,
const a = 3, b = 2;
console.log(a > b); // true
Here, the comparison operator >is used to compare whether a is greater than b.
Example 2: Comparison operators in JavaScript
// equal operator
console.log(2 == 2); // true
console.log(2 == '2'); // true
const x = 5, y = 3;
(x < 6) && (y < 5); // true
Here, &&is the logical operator AND. Since both x < 6and y < 5are true, the result is true.
// logical AND
console.log(true && true); // true
console.log(true && false); // false
// logical OR
console.log(true || false); // true
// logical NOT
console.log(!true); // false
Output:
true
false
true
false
For example,
//strings example
const name = 'Peter';
const name1 = "Jack";
const result = `The names are ${name} and ${name1}`;
Single quotes and double quotes are practically the same and you can use either of them.
Backticks are generally used when you need to include variables or expressions into a string.
This is done by wrapping variables or expressions with ${variable or expression}as
shown above.
You can also write a quote inside another quote. For example,
However, the quote should not match the surrounding quotes. For example,
const a = 'hello';
console.log(a[1]); // "e"
const a = 'hello';
console.log(a.charAt(1)); // "e"
let a = 'hello';
a[0] = 'H';
console.log(a); // "hello"
However, you can assign the variable name to a new string. For example,
let a = 'hello';
a = 'Hello';
console.log(a); // "Hello"
JavaScript is Case-Sensitive
JavaScript is case-sensitive. That means in JavaScript, the lowercase and uppercase letters are
treated as different values. For example,
const a = 'a';
const b = 'A'
console.log(a === b); // false
const a = 'hello';
console.log(a.length); // 5
JavaScript String Objects
Below is the list of the properties of String object and their description :
You can also create strings using the new keyword. For example,
const a = 'hello';
const b = new String('hello');
console.log(a); // "hello"
console.log(b); // "hello"
Note : It is recommended to avoid using string objects. Using string objects slows down the
program.
//converting to string
const result1 = String(a);
const result2 = String(b);
console.log(result1); // "225"
console.log(result2); // "true"
Escape Character
You can use the backslash escape character \ to include special characters in a string. For
example,
Output:
My name is 'Peter'.
// concatenation operator
console.log('hello' + 'world');
let a = 'JavaScript';
Output:
helloworld
JavaScript tutorial
Note : When + is used with strings, it performs concatenation. However, when + is used with
numbers, it performs addition.
Interview Questions
Given a string, reverse each word in the sentence
The spread operator is also indicated by the ... operator. It’ll spread an object’s property into
another object and spread the array entries into another array.
For example, if we have:
Then we get [1, 2, 3] as the value of bar since we made a copy of foo and assigned it to
bar with the spread operator.
It’s also useful for merging arrays. For instance, if we have:
Then baz would be [1, 2, 3, 3, 4, 5] since we combined the entries of the foo and
bar arrays into the baz array.
Thank You