Javascript
Javascript
var number = 2;
function Square (n) {
var res = n * n;
return res;
}
var newNumber = Square(3);
Your First Hello World Program
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
console.log("Hello World");
</script>
</body>
</html>
Variables
80 marks in history
Percentage of marks(80/100)
Grade she got if(80>75)..Distinction
Print the marks console.log(80)
Variables
var num = 1
var name = “PrepBytes”
var isCapital = true
Variables
Variables are containers
They store data values
For ex: var Variables are containers
They store data values
For ex: var x = 5 Click to add text
undefined
null
Data types
Click to add text
Non –Primitive Data type
var
let
const
var vs let vs const
• var declarations are globally scoped or function scoped
while let and const are block scoped.
return “undefined”.
var x;
console.log(x); // Outputs
"undefined" since the initialization
of "x" is not hoisted
x = 23;
Conclusion : Hoisting in JS
• It is a concept which says that you should always declare and
initialise all the variables is JS before using them.
JS
Variables naming convention
• Variable names can consist only of letters (a-z),(A-Z) numbers (0-9),
dollar sign symbols ($), and underscores (_)
ECMAScript2015 - ES6
Keywords reserved only in strict mode
Arithmetic Operators
Comparison Operators
Bitwise Operators
Increment,Decrement Operators
Logical Operators
Ternary Operators
Comma Operator
Arithmetic Operators
%,- , +,/, *
Arithmetic Operators
Comparison Operators
&&, ||, !
Logical Operators
Conditional or Ternary Operators
,
Exercise-1
1.Take two numbers and print the addition of that number.
Input:2 5
Output:7
If it rains, I won’tIfgo
it doesn’t rain ,I will go
Decision Making
You can use if-else statement, if-elif-else statements
when you are having very few conditions to check. If
you have more that 4 conditions than switch statement
will be more preferred.
let weather;
weather = "raining";
if (weather === "raining")
console.log(”I won't go for the party");
else
console.log(”I is will go to the party")
If else
If else
Switch Statement
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
//code block
}
Switch Statement
Switch Statement
LOOPS
Below are the loops available in JS :
for loop
for-in loop
for-of loop
while
do-while loop
Loops
labeled statement
break statement
continue statement
Exercise-2
Problem:A school has following grading rule:
1.below 10 and 10-E
2.11-20-D
3.21-30-C
4.31-40-B
5.41-50-A
ask user to enter marks out of 50 and print the grades
using switch statement.
Input:30
Output:C
Exercise-3
Problem:Write a program which takes a number from user
and print the table.
Input:3
Output:
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Functions
In JS, there are 3 ways
to create a function:
1. Regular function
2. Arrow function
3. Function Expression
Function
console.log(name[1]);
console.log(name.charAt(1));
console.log(“PrepBytes”.charAt(1));
console.log(“PrepBytes”[1]);
Strings comparison
let a = 'a'
let b = 'b'
if (a < b) { // true
console.log(a + ' is less than ' + b)
} else if (a > b) {
console.log(a + ' is greater than ' + b)
} else {
console.log(a + ' and ' + b + ' are equal.')
}
More string methods
index = name.lastIndexOf(“developer”);
Console.log(string3);
Output : PrepBytes
Strings concatenation
Slicing
newMessage = name.slice(7);
newMessage = name.slice(-7);
Slicing
Substring
Substring does not support negative index
For substr second parameter is length
newMessage = name.substring(7);
Substring
Replace
var name = You will be an amazing developer
name.replace(‘ ’, ‘-’);
name.replaceAll(‘ ’, ‘-’)
name.trim();
Replace
split
Output = 9
Word.length
Strings comparison
let a = 'a'
let b = 'b'
if (a < b) { // true
console.log(a + ' is less than ' + b)
} else if (a > b) {
console.log(a + ' is greater than ' + b)
} else {
console.log(a + ' and ' + b + ' are equal.')
}
Excercises-5
Problem:You are provided with a string you have to slice the
name from the string.
and print the sliced string.
(using slice)
Input:Hi Prepbytes
Output:Prepbytes
I am utkarsh
Regular Expression - RegExp in JS
11 34 45 56 78 89 90 54 67 78 54 32
Arrays
myArr.push(7)
myArr.pop()
myArr.shift()
myArr.unshift(‘4’,’5’)
Arrays Methods
myArr.slice(1,3)
myArr.splice(1,3,’a’,’b’,’c’,’d’)
myArr.reverse()
myArr.sort()
myArr.indexOf(3)
myArr.lastIndexOf(3)
For each
myArr.forEach(function(item) {
console.log(item)
})
myArr.map((item)=> {
console.log(item)
})
Filter
yArr = [“Hi”,”How”,”Are”,“You”]
yNewArr = myArr.filter((item)=> return typeof item ==
Maps
let sayings = new Map()
sayings.set(‘dog’, ‘woof')
Saying.set(‘cat’, ‘meow’)
sayings.size
sayings.get(‘dog’)
sayings.get(‘fox’)
sayings.has(‘fox’)
sayings.delete(‘fox’)
saying.size
for(let[key,value] of sayings) {
console.log(key + ' goes ' + value);
}
Maps
map.forEach()
Sets
for(let[key,value] of sayings) {
console.log(key + ' goes ' + value);
}
Exercise-6
Problem: you are provided an array of integer you have to print
the sum of array.
Input:
1234
Output:10
10
Javascript Objects
What are Objects?
const a = 'rahul';
const b = 24;
const c = {};
const object = { name: a, age: b, personalInfo: c };
Objects using Constructor
In Javascript, we can create objects using function
constructor and class constructor.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
const user = {
a: 'student',
b: 42,
};
console.log(Object.keys(user));
// expected output: Array ["a", "b"]
Object.values
const user = {
a: 'student',
b: 24,
};
console.log(Object.values(user));
// expected output: Array ["student", 24]
Exercise-7
Output :
My name is
PrepBuddy
Closures
A closure gives access to variables or other
properties of outer function or parent to
inner function or child function by creating
a lexical environment.
function test() {
test
showName();
test();
Event Loop
The event loop has one
simple job : to
monitor the call stack
and callback queue. If
the call stack is
empty, the event loop
will take the first
item from the callback
queue and will push it
to call stack, which
will effectively runs
it
Event Loop
What is DOM?
The Document Object Model (DOM) is the data
representation of the objects that comprise the
structure and content of a document on the web.
document.createElement(element) : create an
HTML element
<h1>Hello </h1>
Selectors :
1. By class name of element = .classname
2. By id of the element = #id
3. By tag name of element = tag
4. By this keyword = this
jQuery Event handlers
try();
Async and Await in JS
An async keyword will be added to a function when
you want that function to perform in a
asynchronous way in JS.
document.getElementById(“submitBtn")
.addEventListener(“click”,function(){alert(“Hello World !!”)});
Example : removeEventListener
document.getElementById(“submitBtn")
.removeEventListener(“click”,function(){alert(“Hello World !!”)});
ES6 v/s ES5
Local Storage :
Session Storage :